簡單SpringMVC增刪改查,表單驗證功能

首先,新建maven項目,pom.xml引入依賴


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.qfedu</groupId>

<artifactId>Day17SpringMVC</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>war</packaging>

<dependencies>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>4.3.6.RELEASE</version>

</dependency>

<dependency>

<groupId>javax.servlet.jsp</groupId>

<artifactId>jsp-api</artifactId>

<version>2.2</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>3.0.1</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>jstl</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

</dependencies>

<build>

<plugins>

    <plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>3.6.1</version>

<configuration>

<source>1.8</source>

<target>1.8</target>

</configuration>

</plugin>

<!-- 添加tomcat插件 -->

    <plugin>

<groupId>org.apache.tomcat.maven</groupId>

<artifactId>tomcat7-maven-plugin</artifactId>

<version>2.2</version>

<configuration>

<path>/</path>

<port>8081</port>

</configuration>

</plugin>

</plugins>

</build>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

</properties>

</project>

MVC三層架構(gòu)建包,對emp員工類里的list(模仿數(shù)據(jù)庫數(shù)據(jù))增刪改查


public class Emp {

private int eid;

private Stringename;

private double salary;

//省略get、set、toSting等方法

}

dao層


public class EmpDao {

public static Listemps=new ArrayList<>();

static {

for (int i =0; i <20 ; i++) {

emps.add(new Emp(i,"name"+i,10000+(i*100)));

}

}

public List getAllEmp(){

return emps;

}

public Emp getEmpByEid(int id){

return emps.get(id);

}

public boolean updateEmp(Emp emp){

try {

emps.set(emp.getEid(),emp);

return true;

}catch (Exception e){

e.printStackTrace();

}

return false;

}

public boolean delEmpById(int eid){

try {

emps.remove(eid);

return true;

}catch (Exception e){

e.printStackTrace();

}

return false;

}

}

service層


public class EmpService {

public EmpDaoempDao=new EmpDao();

public List getAllEmp(){

return empDao.getAllEmp();

}

public Emp getEmpByEid(int id){

return empDao.getEmpByEid(id);

}

public boolean updateEmp(Emp emp){

return empDao.updateEmp(emp);

}

public boolean delEmpById(int eid){

return empDao.delEmpById(eid);

}

}

control層 實現(xiàn)controller接口和采用注解方式,所以要配xml

重要代碼


package com.qfedu.control;

import com.qfedu.EmpValidate;

import com.qfedu.bean.Emp;

import com.qfedu.service.EmpService;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.validation.BindingResult;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.List;

@Controller

@RequestMapping("/emp")

public class EmpControl {

EmpServiceempService=new EmpService();

@RequestMapping("/emps")

public String getEmps(HttpServletRequest request){

List emps=empService.getAllEmp();

if (emps!=null){

request.setAttribute("list",emps);

}

return "emp.jsp";

}

@RequestMapping("/getEmpByEid")

public  String getEmpByEid(Model model,HttpServletRequest request){

String seid=request.getParameter("eid");

Emp emp=empService.getEmpByEid(Integer.valueOf(seid));

model.addAttribute("emp",emp);

return "updateEmp.jsp";

}

@PostMapping("/updateEmp")

public String updateEmp(Emp emp){

System.out.println(emp);

boolean flg=empService.updateEmp(emp);

if (flg){

return "redirect:/emp/emps";

}

return "";

}

@GetMapping("/delEmpByEid/{eid}")

public String delEmpByEid(@PathVariable int eid){

boolean flg=empService.delEmpById(eid);

if (flg){

return "redirect:/emp/emps";

}

return "";

}

@GetMapping("/saveEmp")

public ModelAndView saveEmp(){

ModelAndView mv=new ModelAndView("saveEmp.jsp","emp",new Emp());

return mv;

}

@PostMapping("/saveEmp")

public String saveEmp(Emp e, BindingResult result,Model model){

EmpValidate ev=new EmpValidate();

ev.validate(e,result);

if (result.hasErrors()){

model.addAttribute("emp",e);

return  "saveEmp.jsp";

}

return "redirect:/emp/emps";

}

}

spring-mvc.xml


<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

      xmlns:mvc="http://www.springframework.org/schema/mvc"

      xmlns:context="http://www.springframework.org/schema/context"

      xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd

http://www.springframework.org/schema/context

      http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 配置SpringMVC的視圖解析器 可以分別指定前綴和后綴 prefix: /WEB-INF/view/,那么控制器那邊會在虛擬視圖前拼接該字符串 suffix:.jsp .html,那么控制器那邊會在虛擬視圖后面拼接該字符串 拼接完字符串的效果 /WEB-INF/view/index.html /WEB-INF/view/detail.jsp -->

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/view/"/>

<!-- <property name="suffix" value=".html"></property>-->

<!--缺省狀態(tài)沒有后綴  加.html路徑正確,但靜態(tài)訪問不了-->

   </bean>

<!--    訪問靜態(tài)資源,初始化等html取消suffix-->

    <mvc:default-servlet-handler />

<!--    注解類之后,在配置文件配置以下-->

    <mvc:annotation-driven/>

<context:component-scan base-package="com.qfedu.control" />

<!--    寫name可以寫/ ,controller 根據(jù)請求路徑,掃描包,查到以下類-->

    <bean name="/ProductInput" class="com.qfedu.control.ProductInputControl"/>

<bean name="/ProductSave" class="com.qfedu.control.ProductSaveControl"/>

<!-- 驗證數(shù)據(jù)-->

    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">

<property name="basename" value="/WEB-INF/msg"/>

</bean>

</beans>

Varlidate驗證表單參數(shù)


import com.qfedu.bean.Emp;

import org.springframework.validation.Errors;

import org.springframework.validation.ValidationUtils;

import org.springframework.validation.Validator;

public class EmpValidateimplements Validator {

@Override

    public boolean supports(Class aClass) {

return Emp.class.isAssignableFrom(aClass);

}

@Override

    public void validate(Object o, Errors errors) {

Emp emp= (Emp) o;

//        ValidationUtils.rejectIfEmpty(errors, "eid","emp.eid");

        ValidationUtils.rejectIfEmpty(errors,"eid","emp.eid");

ValidationUtils.rejectIfEmpty(errors,"ename","emp.ename");

ValidationUtils.rejectIfEmpty(errors,"salary","emp.salary");

double salary = emp.getSalary();

if(salary <0){

errors.rejectValue("salary","emp.salary.invalidate");

}

}

}

xml里配置的msg路徑文件

image

/saveEmp請求下的saveEmp.jsp

image

當瀏覽器是英文狀態(tài),自動調(diào)用msg_en_US.properties

emp.eid=the eid of employee cannot be empty.

emp.ename=the name of employee cannot be empty.

emp.salary=the salary of employee cannot be empty.

emp.salary.invalidate=the salary of employee cannot be negative.

點擊提交結(jié)果如下圖實現(xiàn)

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容