首先,新建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三层架构建包,对emp员工类里的list(模仿数据库数据)增删改查
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层 实现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>-->
<!--缺省状态没有后缀 加.html路径正确,但静态访问不了-->
</bean>
<!-- 访问静态资源,初始化等html取消suffix-->
<mvc:default-servlet-handler />
<!-- 注解类之后,在配置文件配置以下-->
<mvc:annotation-driven/>
<context:component-scan base-package="com.qfedu.control" />
<!-- 写name可以写/ ,controller 根据请求路径,扫描包,查到以下类-->
<bean name="/ProductInput" class="com.qfedu.control.ProductInputControl"/>
<bean name="/ProductSave" class="com.qfedu.control.ProductSaveControl"/>
<!-- 验证数据-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/msg"/>
</bean>
</beans>
Varlidate验证表单参数
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路径文件
/saveEmp请求下的saveEmp.jsp
当浏览器是英文状态,自动调用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.