SpringMVC基础-08-数据转换 & 数据格式化 & 数据校验

 

代码示例

Department.java:

 1 package com.atguigu.bean;
 2 
 3 public class Department {
 4 
 5     private Integer id;
 6     private String departmentName;
 7 
 8     public Department() {
 9     }
10     
11     public Department(int i, String string) {
12         this.id = i;
13         this.departmentName = string;
14     }
15 
16     public Integer getId() {
17         return id;
18     }
19 
20     public void setId(Integer id) {
21         this.id = id;
22     }
23 
24     public String getDepartmentName() {
25         return departmentName;
26     }
27 
28     public void setDepartmentName(String departmentName) {
29         this.departmentName = departmentName;
30     }
31 
32     @Override
33     public String toString() {
34         return "Department [id=" + id + ", departmentName=" + departmentName + "]";
35     }
36     
37 }

Employee.java:

  1 package com.atguigu.bean;
  2 
  3 import java.util.Date;
  4 
  5 import javax.validation.constraints.Future;
  6 import javax.validation.constraints.Past;
  7 
  8 import org.hibernate.validator.constraints.Email;
  9 import org.hibernate.validator.constraints.Length;
 10 import org.hibernate.validator.constraints.NotEmpty;
 11 import org.springframework.format.annotation.DateTimeFormat;
 12 import org.springframework.format.annotation.NumberFormat;
 13 
 14 import com.fasterxml.jackson.annotation.JsonFormat;
 15 import com.fasterxml.jackson.annotation.JsonIgnore;
 16 
 17 public class Employee {
 18 
 19     private Integer id;
 20     
 21     @NotEmpty(message="不能为空")
 22     @Length(min=5,max=17,message="我错了")
 23     private String lastName;
 24 
 25     
 26     @Email
 27     private String email;
 28     //1 male, 0 female
 29     private Integer gender;
 30     
 31 
 32     //规定页面提交的日期格式  
 33     //@Past:必须是一个过去的时间
 34     //@Future :必须是一个未来的时间
 35     @DateTimeFormat(pattern="yyyy-MM-dd")
 36 @Past
 37     @JsonFormat(pattern="yyyy-MM-dd")
 38     private Date birth = new Date();
 39     
 40     //假设页面,为了显示方便提交的工资是  ¥10,000.98
 41     @NumberFormat(pattern="#,###.##")
 42     private Double salary;
 43     
 44     @JsonIgnore
 45     private Department department;
 46     
 47     
 48     /**
 49      * @return the birth
 50      */
 51     public Date getBirth() {
 52         return birth;
 53     }
 54 
 55     /**
 56      * @param birth the birth to set
 57      */
 58     public void setBirth(Date birth) {
 59         this.birth = birth;
 60     }
 61 
 62     public Integer getId() {
 63         return id;
 64     }
 65 
 66     public void setId(Integer id) {
 67         this.id = id;
 68     }
 69 
 70     public String getLastName() {
 71         return lastName;
 72     }
 73 
 74     public void setLastName(String lastName) {
 75         this.lastName = lastName;
 76     }
 77 
 78     public String getEmail() {
 79         return email;
 80     }
 81 
 82     public void setEmail(String email) {
 83         this.email = email;
 84     }
 85 
 86     public Integer getGender() {
 87         return gender;
 88     }
 89 
 90     public void setGender(Integer gender) {
 91         this.gender = gender;
 92     }
 93 
 94     public Department getDepartment() {
 95         return department;
 96     }
 97 
 98     public void setDepartment(Department department) {
 99         this.department = department;
100     }
101 
102     public Employee(Integer id, String lastName, String email, Integer gender,
103             Department department) {
104         super();
105         this.id = id;
106         this.lastName = lastName;
107         this.email = email;
108         this.gender = gender;
109         this.department = department;
110     }
111 
112     public Employee() {
113     }
114 
115     /* (non-Javadoc)
116      * @see java.lang.Object#toString()
117      */
118     @Override
119     public String toString() {
120         return "Employee [id=" + id + ", lastName=" + lastName + ", email="
121                 + email + ", gender=" + gender + ", birth=" + birth
122                 + ", department=" + department + "]";
123     }
124 }

MyStringToEmployeeConverter.java:

 1 package com.atguigu.component;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.core.convert.converter.Converter;
 5 
 6 import com.atguigu.bean.Employee;
 7 import com.atguigu.dao.DepartmentDao;
 8 
 9 /**
10  * 两个返回
11  * 
12  * S:Source T:Target 将s转为t
13  * 
14  * 
15  */
16 public class MyStringToEmployeeConverter implements Converter {
17 
18     @Autowired
19     DepartmentDao departmentDao;
20     
21     /**
22      * 自定义的转换规则
23      */
24     @Override
25     public Employee convert(String source) {
26         // TODO Auto-generated method stub
27         // [email protected]
28         System.out.println("页面提交的将要转换的字符串" + source);
29         Employee employee = new Employee();
30         if (source.contains("-")) {
31             String[] split = source.split("-");
32             employee.setLastName(split[0]);
33             employee.setEmail(split[1]);
34             employee.setGender(Integer.parseInt(split[2]));
35             employee.setDepartment(departmentDao.getDepartment(Integer.parseInt(split[3])));
36         }
37         return employee;
38     }
39 
40 }

AjaxTestController.java:

  1 package com.atguigu.controller;
  2 
  3 import java.io.FileInputStream;
  4 import java.io.FileNotFoundException;
  5 import java.util.Collection;
  6 
  7 import javax.servlet.ServletContext;
  8 import javax.servlet.http.HttpServletRequest;
  9 
 10 import org.springframework.beans.factory.annotation.Autowired;
 11 import org.springframework.http.HttpEntity;
 12 import org.springframework.http.HttpHeaders;
 13 import org.springframework.http.HttpStatus;
 14 import org.springframework.http.ResponseEntity;
 15 import org.springframework.stereotype.Controller;
 16 import org.springframework.util.MultiValueMap;
 17 import org.springframework.web.bind.annotation.RequestBody;
 18 import org.springframework.web.bind.annotation.RequestMapping;
 19 import org.springframework.web.bind.annotation.ResponseBody;
 20 
 21 import com.atguigu.bean.Employee;
 22 import com.atguigu.dao.EmployeeDao;
 23 
 24 @Controller
 25 public class AjaxTestController {
 26     
 27     @Autowired
 28     EmployeeDao employeeDao;
 29     
 30     /**
 31      * SpringMVC文件下载;
 32      * 
 33      * @param request
 34      * @return
 35      * @throws Exception
 36      */
 37     @RequestMapping("/download")
 38     public ResponseEntity download(HttpServletRequest request) throws Exception{
 39         
 40         //1、得到要下载的文件的流;
 41         //找到要下载的文件的真实路径
 42         ServletContext context = request.getServletContext();
 43         String realPath = context.getRealPath("/scripts/jquery-1.9.1.min.js");
 44         FileInputStream is = new FileInputStream(realPath);
 45         
 46         byte[] tmp = new byte[is.available()];
 47         is.read(tmp);
 48         is.close();
 49         
 50         //2、将要下载的文件流返回
 51         HttpHeaders httpHeaders = new HttpHeaders();
 52         httpHeaders.set("Content-Disposition", "attachment;filename="+"jquery-1.9.1.min.js");
 53         
 54         return new ResponseEntity(tmp, httpHeaders, HttpStatus.OK);
 55     }
 56     
 57     /**
 58      * 将返回数据放在响应体中
 59      * 
 60      * ResponseEntity:响应体中内容的类型
 61      * @return
 62      */
 63     //@ResponseBody
 64     @RequestMapping("/haha")
 65     public ResponseEntity hahah(){
 66         
 67         MultiValueMap headers = new HttpHeaders();
 68         String body = "

success

"; 69 headers.add("Set-Cookie", "username=hahahaha"); 70 71 return new ResponseEntity(body , headers, HttpStatus.OK); 72 } 73 74 75 /** 76 * 如果参数位置写HttpEntity str; 77 * 比@RequestBody更强,可以拿到请求头; 78 * @RequestHeader("") 79 * 80 * @param str 81 * @return 82 */ 83 @RequestMapping("/test02") 84 public String test02(HttpEntity str){ 85 System.out.println(str); 86 return "success"; 87 } 88 89 /** 90 * 91 */ 92 @RequestMapping("/test01") 93 public String test01(@RequestBody String str){ 94 System.out.println("请求体:"+str); 95 return "success"; 96 } 97 98 /** 99 * @RequestBody:请求体;获取一个请求的请求体 100 * @RequestParam: 101 * 102 * @ResponseBody:可以把对象转为json数据,返回给浏览器 103 * 104 * @RequestBody:接收json数据,封装为对象 105 * @return 106 */ 107 @RequestMapping("/testRequestBody") 108 public String testRequestBody(@RequestBody Employee employee){ 109 System.out.println("请求体:"+employee); 110 return "success"; 111 } 112 113 /** 114 * 将返回的数据放在响应体中; 115 * 如果是对象,jackson包自动将对象转为json格式 116 * @return 117 */ 118 @ResponseBody 119 @RequestMapping("/getallajax") 120 public Collection ajaxGetAll(){ 121 Collection all = employeeDao.getAll(); 122 return all; 123 } 124 125 }

EmployeeController.java:

  1 package com.atguigu.controller;
  2 
  3 import java.util.Collection;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import javax.validation.Valid;
  9 
 10 import org.springframework.beans.factory.annotation.Autowired;
 11 import org.springframework.stereotype.Controller;
 12 import org.springframework.ui.Model;
 13 import org.springframework.validation.BindingResult;
 14 import org.springframework.validation.FieldError;
 15 import org.springframework.web.bind.annotation.ModelAttribute;
 16 import org.springframework.web.bind.annotation.PathVariable;
 17 import org.springframework.web.bind.annotation.RequestMapping;
 18 import org.springframework.web.bind.annotation.RequestMethod;
 19 import org.springframework.web.bind.annotation.RequestParam;
 20 
 21 import com.atguigu.bean.Department;
 22 import com.atguigu.bean.Employee;
 23 import com.atguigu.dao.DepartmentDao;
 24 import com.atguigu.dao.EmployeeDao;
 25 
 26 @Controller
 27 public class EmployeeController {
 28 
 29     @Autowired
 30     EmployeeDao employeeDao;
 31 
 32     @Autowired
 33     DepartmentDao departmentDao;
 34 
 35     /**
 36      * 发送的请求是什么?
 37      * 
 38      * [email protected]
 39      * 
 40      * @RequestParam("empinfo")Employee employee; Employee employee =
 41      *                                  request.getParameter("empinfo");
 42      * 
 43      *                                  可以通过写一个自定义类型的转换器让其工作;
 44      * @param employee
 45      * @return
 46      */
 47     @RequestMapping("/quickadd")
 48     public String quickAdd(@RequestParam("empinfo") Employee employee) {
 49         System.out.println("封装:" + employee);
 50         employeeDao.save(employee);
 51         return "redirect:/emps";
 52     }
 53 
 54     /**
 55      * 查询所有员工
 56      * 
 57      * @return
 58      */
 59     @RequestMapping("/emps")
 60     public String getEmps(Model model) {
 61         Collection all = employeeDao.getAll();
 62         model.addAttribute("emps", all);
 63         return "list";
 64     }
 65 
 66     @RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
 67     public String deleteEmp(@PathVariable("id") Integer id) {
 68         employeeDao.delete(id);
 69         return "redirect:/emps";
 70     }
 71 
 72     /**
 73      * 查询员工,来到修改页面回显
 74      * 
 75      * @param id
 76      * @param model
 77      * @return
 78      */
 79     @RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
 80     public String getEmp(@PathVariable("id") Integer id, Model model) {
 81         // 1、查出员工信息
 82         Employee employee = employeeDao.get(id);
 83         // 2、放在请求域中
 84         model.addAttribute("employee", employee);
 85         // 3、继续查出部门信息放在隐含模型中
 86         Collection departments = departmentDao.getDepartments();
 87         model.addAttribute("depts", departments);
 88         return "edit";
 89     }
 90 
 91     @RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT)
 92     public String updateEmp(@ModelAttribute("employee") Employee employee/*
 93                                                                          */) {
 94         System.out.println("要修改的员工:" + employee);
 95         // xxxx 更新保存二合一;
 96         employeeDao.save(employee);
 97         return "redirect:/emps";
 98     }
 99 
100     @ModelAttribute
101     public void myModelAttribute(
102             @RequestParam(value = "id", required = false) Integer id,
103             Model model) {
104         if (id != null) {
105             Employee employee = employeeDao.get(id);
106             model.addAttribute("employee", employee);
107         }
108         System.out.println("hahha ");
109         // 1、先查出所有部门
110         Collection departments = departmentDao.getDepartments();
111         // 2、放在请求域中
112         model.addAttribute("depts", departments);
113     }
114 
115     /**
116      * 保存员工
117      * 
118      * @param employee
119      * @return
120      */
121     @RequestMapping(value = "/emp", method = RequestMethod.POST)
122     public String addEmp(@Valid Employee employee, BindingResult result,
123             Model model) {
124         System.out.println("要添加的员工:" + employee);
125         // 获取是否有校验错误
126         boolean hasErrors = result.hasErrors();
127         Map errorsMap = new HashMap();
128         if (hasErrors) {
129             List errors = result.getFieldErrors();
130             for (FieldError fieldError : errors) {
131                 
132                 System.out.println("错误消息提示:" + fieldError.getDefaultMessage());
133                 System.out.println("错误的字段是?" + fieldError.getField());
134                 System.out.println(fieldError);
135                 System.out.println("------------------------");
136                 errorsMap.put(fieldError.getField(),
137                         fieldError.getDefaultMessage());
138             }
139             model.addAttribute("errorInfo", errorsMap);
140             System.out.println("有校验错误");
141             return "add";
142         } else {
143             employeeDao.save(employee);
144             // 返回列表页面;重定向到查询所有员工的请求
145             return "redirect:/emps";
146         }
147     }
148 
149     /**
150      * 去员工添加页面,去页面之前需要查出所有部门信息,进行展示的
151      * 
152      * @return
153      */
154     @RequestMapping("/toaddpage")
155     public String toAddPage(Model model) {
156 
157         model.addAttribute("employee", new Employee());
158         // 3、去添加页面
159         return "add";
160     }
161 
162 }

HelloController.java:

 1 package com.atguigu.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 
 6 @Controller
 7 public class HelloController {
 8     
 9     @RequestMapping("/hello")
10     public String handle01(){
11         return "success";
12     }
13 
14 }

DepartmentDao.java:

 1 package com.atguigu.dao;
 2 
 3 import java.util.Collection;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 
 7 import org.springframework.stereotype.Repository;
 8 
 9 import com.atguigu.bean.Department;
10 
11 /**
12  * 操作部门的dao
13  * @author lfy
14  *
15  */
16 @Repository
17 public class DepartmentDao {
18 
19     private static Map departments = null;
20     
21     static{
22         departments = new HashMap();
23         
24         departments.put(101, new Department(101, "D-AA"));
25         departments.put(102, new Department(102, "D-BB"));
26         departments.put(103, new Department(103, "D-CC"));
27         departments.put(104, new Department(104, "D-DD"));
28         departments.put(105, new Department(105, "D-EE"));
29     }
30     
31     /**
32      * 返回所有的部门
33      * @return
34      */
35     public Collection getDepartments(){
36         return departments.values();
37     }
38     
39     /**
40      * 按照部门id查询部门
41      * @param id
42      * @return
43      */
44     public Department getDepartment(Integer id){
45         return departments.get(id);
46     }
47     
48 }

EmployeeDao.java:

 1 package com.atguigu.dao;
 2 
 3 import java.util.Collection;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 
 7 import org.springframework.beans.factory.annotation.Autowired;
 8 import org.springframework.stereotype.Repository;
 9 
10 import com.atguigu.bean.Department;
11 import com.atguigu.bean.Employee;
12 
13 
14 /**
15  * EmployeeDao:操作员工
16  * @author lfy
17  *
18  */
19 @Repository
20 public class EmployeeDao {
21 
22     private static Map employees = null;
23     
24     @Autowired
25     private DepartmentDao departmentDao;
26     
27     static{
28         employees = new HashMap();
29 
30         employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
31         employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
32         employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
33         employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
34         employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE")));
35     }
36     
37     //初始id
38     private static Integer initId = 1006;
39     
40     /**
41      * 员工保存/更新二合一方法;
42      * @param employee
43      */
44     public void save(Employee employee){
45         if(employee.getId() == null){
46             employee.setId(initId++);
47         }
48         
49         //根据部门id单独查出部门信息设置到员工对象中,页面提交的只需要提交部门的id
50         employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
51         employees.put(employee.getId(), employee);
52     }
53     
54     /**
55      * 查询所有员工
56      * @return
57      */
58     public Collection getAll(){
59         return employees.values();
60     }
61     
62     /**
63      * 按照id查询某个员工
64      * @param id
65      * @return
66      */
67     public Employee get(Integer id){
68         return employees.get(id);
69     }
70     
71     /**
72      * 删除某个员工
73      * @param id
74      */
75     public void delete(Integer id){
76         employees.remove(id);
77     }
78 }

errors_en_US.properties:

1 #Email.email=email incorrect!~~
2 Email=email buzhengque~~~
3 NotEmpty=must not empty~~
4 Length.java.lang.String= length incorrect ,must between {2} and {1} ~~
5 Past=must a past time~~~
6 typeMismatch.birth=birth geshi buzhengque

errors_zh_CN.properties:

1 Email.email=\u90AE\u7BB1\u4E0D\u5BF9!~~
2 NotEmpty=\u4E0D\u80FD\u4E3A\u7A7A~~
3 Length.java.lang.String= \u957F\u5EA6\u4E0D\u5BF9~~
4 Past=\u65F6\u95F4\u5FC5\u987B\u662F\u8FC7\u53BB\u7684~~~
5 typeMismatch.birth=\u751F\u65E5\u7684\u683C\u5F0F\u4E0D\u6B63\u786E

springmvc.xml:

 1 
 2 
 9 
10     
11     
12     
13         
14         
15     
16 
17     
19     
20     
21     
22     
23     
24     
25     
26     
27     
29     
31     
32         
33         
34             
35                 
36             
37         
38     
39     
40     
41     
42         
43     
44 

web.xml:

 1 
 4 
 5 
 8     8.SpringMVC_dataBinder
 9     
10         index.jsp
11     
12 
13     
15     
16         springDispatcherServlet
17         org.springframework.web.servlet.DispatcherServlet
18         
19             
20             contextConfigLocation
21             classpath:springmvc.xml
22         
23         1
24     
25 
26     
27     
28         springDispatcherServlet
29         /
30     
31 
32     
33     
34     
35         CharacterEncodingFilter
36         org.springframework.web.filter.CharacterEncodingFilter
37         
38         
39             encoding
40             
41             utf-8
42         
43         
44             
45             forceEncoding
46             true
47         
48     
49     
50         CharacterEncodingFilter
51         /*
52     
53 
54     
55     
56         HiddenHttpMethodFilter
57         org.springframework.web.filter.HiddenHttpMethodFilter
58     
59     
60         HiddenHttpMethodFilter
61         /*
62     
63     
66 
67 

emps.jsp:

 1 <%@page import="java.util.Date"%>
 2 <%@ page language="java" contentType="text/html; charset=UTF-8"
 3     pageEncoding="UTF-8"%>
 4 
 5 
 6 
 7 
 8 Insert title here
 9 <%
10     pageContext.setAttribute("ctp", request.getContextPath());
11 %>
12 
13 
14 
15 <%=new Date() %>
16 ajax获取所有员工
17 18
19 20
21 39 40

index.jsp:

1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2     pageEncoding="UTF-8"%>
3 
4 

testOther.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 
 4 
 5 
 6 
 7 Insert title here
 8 <%
 9     pageContext.setAttribute("ctp", request.getContextPath());
10 %>
11 
12 
13 
14     
16 19
20 ajax发送json数据 21 22 46

add.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 4 <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 5 
 6 
 7 
 8 
 9 Insert title here
10 
11 
12 

员工添加

13 26 <% 27 pageContext.setAttribute("ctp", request.getContextPath()); 28 %> 29 30 35 lastName: 36 -->${errorInfo.lastName } 37
38 email: 39 -->${errorInfo.email } 40
41 gender:
42 男:
43 女:
44 birth: 45 --->${errorInfo.birth } 46
47 dept: 48 53
57 58
59 60 61 62 63 64 <%--
65 lastName:
66 email:
67 gender:
68 男:
69 女:
70 dept: 71 77 78
--%> 79 80

edit.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 4 
 5 
 6 
 7 
 8 Insert title here
 9 <%
10     pageContext.setAttribute("ctp", request.getContextPath());
11 %>
12 
13 
14 

员工修改页面

15 16 18 19 20 email:
21 gender:    22 男:    23 女:
24 dept: 25 27
28 29 30
31 32

list.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 
 5 
 6 <%
 7         pageContext.setAttribute("ctp", request.getContextPath());
 8 %>
 9 
10 
11 员工列表
12 
13 
14 
15     
16     

员工列表

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
IDlastNameemailgenderbirthdepartmentNameEDITDELETE
${emp.id }${emp.lastName}${emp.email }${emp.gender==0?"女":"男" }${emp.birth}${emp.department.departmentName }editdelete
41 添加员工
42 43
44 45 46 47
48 49
50 51
52 64 65

success.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 
 4 
 5 
 6 
 7 Insert title here
 8 
 9 
10 

成功!

11 jackson-annotations-2.1.5.jar 12 jackson-core-2.1.5.jar 13 jackson-databind-2.1.5.jar 14 15

 相关依赖:

 1 
 2 
 5     
 6         SpringMVC
 7         com.atguigu
 8         1.0-SNAPSHOT
 9     
10     4.0.0
11     war
12     8.SpringMVC_dataBinder
13 
14     
15         
16         
17             org.apache.taglibs
18             taglibs-standard-impl
19             1.2.5
20         
21 
22         
23         
24             org.apache.taglibs
25             taglibs-standard-spec
26             1.2.5
27         
28 
29         
30         
31             org.hibernate.validator
32             hibernate-validator
33             6.1.5.Final
34         
35 
36         
37         
38             com.fasterxml.jackson.core
39             jackson-databind
40             2.11.0
41         
42 
43 
44     
45 
46 

 

你可能感兴趣的:(SpringMVC基础-08-数据转换 & 数据格式化 & 数据校验)