代码示例
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<String, Employee> { 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 // empAdmin-admin@qq.com-1-101 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<byte[]> 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<byte[]>(tmp, httpHeaders, HttpStatus.OK); 55 } 56 57 /** 58 * 将返回数据放在响应体中 59 * 60 * ResponseEntity<String>:响应体中内容的类型 61 * @return 62 */ 63 //@ResponseBody 64 @RequestMapping("/haha") 65 public ResponseEntity<String> hahah(){ 66 67 MultiValueMap<String, String> headers = new HttpHeaders(); 68 String body = "<h1>success</h1>"; 69 headers.add("Set-Cookie", "username=hahahaha"); 70 71 return new ResponseEntity<String>(body , headers, HttpStatus.OK); 72 } 73 74 75 /** 76 * 如果参数位置写HttpEntity<String> str; 77 * 比@RequestBody更强,可以拿到请求头; 78 * @RequestHeader("") 79 * 80 * @param str 81 * @return 82 */ 83 @RequestMapping("/test02") 84 public String test02(HttpEntity<String> 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<Employee> ajaxGetAll(){ 121 Collection<Employee> 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 * quickadd?empinfo=empAdmin-admin@qq.com-1-101 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<Employee> 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<Department> 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<Department> 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<String, Object> errorsMap = new HashMap<String, Object>(); 128 if (hasErrors) { 129 List<FieldError> 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<Integer, Department> departments = null; 20 21 static{ 22 departments = new HashMap<Integer, Department>(); 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<Department> 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<Integer, Employee> employees = null; 23 24 @Autowired 25 private DepartmentDao departmentDao; 26 27 static{ 28 employees = new HashMap<Integer, Employee>(); 29 30 employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA"))); 31 employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB"))); 32 employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC"))); 33 employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD"))); 34 employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 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<Employee> 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=u90AEu7BB1u4E0Du5BF9!~~ 2 NotEmpty=u4E0Du80FDu4E3Au7A7A~~ 3 Length.java.lang.String= u957Fu5EA6u4E0Du5BF9~~ 4 Past=u65F6u95F4u5FC5u987Bu662Fu8FC7u53BBu7684~~~ 5 typeMismatch.birth=u751Fu65E5u7684u683Cu5F0Fu4E0Du6B63u786E
springmvc.xml:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> 9 10 <context:component-scan base-package="com.atguigu"></context:component-scan> 11 12 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 13 <property name="prefix" value="/WEB-INF/pages/"></property> 14 <property name="suffix" value=".jsp"></property> 15 </bean> 16 17 <!-- 默认前端控制器是拦截所有资源(除过jsp),js文件就404了;要js文件的请求是交给tomcat处理的 18 http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js --> 19 <!-- 告诉SpringMVC,自己映射的请求就自己处理,不能处理的请求直接交给tomcat --> 20 <!-- 静态资源能访问,动态映射的请求就不行 --> 21 <mvc:default-servlet-handler/> 22 <!-- springmvc可以保证动态请求和静态请求都能访问 --> 23 24 <!-- conversion-service="conversionService":使用我们自己配置的类型转换组件 --> 25 <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> 26 27 <!-- 告诉SpringMVC别用默认的ConversionService, 28 而用我自定义的ConversionService、可能有我们自定义的Converter; --> 29 <!-- 以后写自定义类型转换器的时候,就使用FormattingConversionServiceFactoryBean来注册; 30 既具有类型转换还有格式化功能 --> 31 <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 32 <!--converters转换器中添加我们自定义的类型转换器 --> 33 <property name="converters"> 34 <set> 35 <bean class="com.atguigu.component.MyStringToEmployeeConverter"></bean> 36 </set> 37 </property> 38 </bean> 39 40 <!-- 管理国际化资源文件 --> 41 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> 42 <property name="basename" value="errors"></property> 43 </bean> 44 </beans>
web.xml:
1 <!DOCTYPE web-app PUBLIC 2 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 3 "http://java.sun.com/dtd/web-app_2_3.dtd" > 4 5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" 6 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 7 id="WebApp_ID" version="3.0"> 8 <display-name>8.SpringMVC_dataBinder</display-name> 9 <welcome-file-list> 10 <welcome-file>index.jsp</welcome-file> 11 </welcome-file-list> 12 13 <!-- The front controller of this Spring Web application, 14 responsible for handling all application requests --> 15 <servlet> 16 <servlet-name>springDispatcherServlet</servlet-name> 17 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 18 <init-param> 19 <!-- contextConfigLocation:指定SpringMVC配置文件位置 --> 20 <param-name>contextConfigLocation</param-name> 21 <param-value>classpath:springmvc.xml</param-value> 22 </init-param> 23 <load-on-startup>1</load-on-startup> 24 </servlet> 25 26 <!-- Map all requests to the DispatcherServlet for handling --> 27 <servlet-mapping> 28 <servlet-name>springDispatcherServlet</servlet-name> 29 <url-pattern>/</url-pattern> 30 </servlet-mapping> 31 32 <!-- 配置一个字符编码的Filter;一定注意:字符编码filter一般都在其他Filter之前; --> 33 <!--配置字符集编码的Filter--> 34 <filter> 35 <filter-name>CharacterEncodingFilter</filter-name> 36 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 37 <!-- encoding:指定解决POST请求乱码 --> 38 <init-param> 39 <param-name>encoding</param-name> 40 <!--不区分大小写--> 41 <param-value>utf-8</param-value> 42 </init-param> 43 <init-param> 44 <!-- forceEncoding:顺手解决响应乱码;response.setCharacterEncoding(this.encoding); --> 45 <param-name>forceEncoding</param-name> 46 <param-value>true</param-value> 47 </init-param> 48 </filter> 49 <filter-mapping> 50 <filter-name>CharacterEncodingFilter</filter-name> 51 <url-pattern>/*</url-pattern> 52 </filter-mapping> 53 54 <!--支持Rest风格的Filter(开启PUT、DELETE请求)--> 55 <filter> 56 <filter-name>HiddenHttpMethodFilter</filter-name> 57 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 58 </filter> 59 <filter-mapping> 60 <filter-name>HiddenHttpMethodFilter</filter-name> 61 <url-pattern>/*</url-pattern> 62 </filter-mapping> 63 <!-- 使用SpringMVC前端控制器写完就直接写字符编码过滤器; 64 Tomcat一装上,上手就是server.xml的8080处添加URIEncoding="UTF-8" 65 --> 66 67 </web-app>
emps.jsp:
1 <%@page import="java.util.Date"%> 2 <%@ page language="java" contentType="text/html; charset=UTF-8" 3 pageEncoding="UTF-8"%> 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 <% 10 pageContext.setAttribute("ctp", request.getContextPath()); 11 %> 12 <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> 13 </head> 14 <body> 15 <%=new Date() %> 16 <a href="${ctp }/getallajax">ajax获取所有员工</a><br/> 17 18 <div> 19 20 </div> 21 <script type="text/javascript"> 22 $("a:first").click(function(){ 23 //1、发送ajax获取所有员工上 24 $.ajax({ 25 url:"${ctp}/getallajax", 26 type:"GET", 27 success:function(data){ 28 //console.log(data); 29 $.each(data,function(){ 30 var empInfo = this.lastName+"-->"+this.birth+"--->"+this.gender; 31 $("div").append(empInfo+"<br/>"); 32 }); 33 } 34 }); 35 36 return false; 37 }); 38 </script> 39 </body> 40 </html>
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!-- 访问项目就要展示员工列表页面 --> 4 <jsp:forward page="/emps"></jsp:forward>
testOther.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 <% 9 pageContext.setAttribute("ctp", request.getContextPath()); 10 %> 11 </head> 12 <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> 13 <body> 14 <form action="${ctp }/test02" method="post" 15 enctype="multipart/form-data"> 16 <input name="username" value="tomcat" /> <input name="password" 17 value="123456"> <input type="file" name="file" /> <input 18 type="submit" /> 19 </form> 20 <a href="${ctp }/testRequestBody">ajax发送json数据</a> 21 </body> 22 <script type="text/javascript"> 23 $("a:first").click(function() { 24 //点击发送ajax请求,请求带的数据是json 25 var emp = { 26 lastName : "张三", 27 email : "aaa@aa.com", 28 gender : 0 29 }; 30 //alert(typeof emp); 31 //js对象 32 var empStr = JSON.stringify(emp); 33 //alert(typeof empStr); 34 $.ajax({ 35 url : '${ctp}/testRequestBody', 36 type : "POST", 37 data : empStr, 38 contentType : "application/json", 39 success : function(data) { 40 alert(data); 41 } 42 }); 43 return false; 44 }); 45 </script> 46 </html>
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 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 6 <html> 7 <head> 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 9 <title>Insert title here</title> 10 </head> 11 <body> 12 <h1>员工添加</h1> 13 <!-- 14 表单标签; 15 通过 SpringMVC的表单标签可以实现将模型数据中的属性和 HTML 表单元素相绑定, 16 以实现表单数据更便捷编辑和表单值的回显 17 1)、SpringMVC认为,表单数据中的每一项最终都是要回显的; 18 path指定的是一个属性;这个属性是从隐含模型(请求域中取出的某个对象中的属性); 19 path指定的每一个属性,请求域中必须有一个对象,拥有这个属性; 20 这个对象就是请求域中的command; 21 modelAttribute="": 22 1)、以前我们表单标签会从请求域中获取一个command对象;把这个对象中的每一个属性对应的显示出来 23 2)、可以告诉SpringMVC不要去取command的值了,我放了一个modelAttribute指定的值; 24 取对象用的key就用我modelAttribute指定的; 25 --> 26 <% 27 pageContext.setAttribute("ctp", request.getContextPath()); 28 %> 29 <form:form action="${ctp }/emp" modelAttribute="employee" method="POST"> 30 <!-- path就是原来html-input的name项:需要写 31 path: 32 1)、当做原生的name项 33 2)、自动回显隐含模型中某个对象对应的这个属性的值 34 --> 35 lastName:<form:input path="lastName"/> 36 <form:errorspath="lastName"/>-->${errorInfo.lastName } 37 <br/> 38 email:<form:input path="email"/> 39 <form:errors path="email"/>-->${errorInfo.email } 40 <br/> 41 gender:<br/> 42 男:<form:radiobutton path="gender" value="1"/><br/> 43 女:<form:radiobutton path="gender" value="0"/><br/> 44 birth:<form:input path="birth"/> 45 <form:errors path="birth"/>--->${errorInfo.birth } 46 <br/> 47 dept: 48 <!-- 49 items="":指定要遍历的集合 ;自动遍历;遍历出的每一个元素是一个department对象 50 itemLabel="属性名":指定遍历出的这个对象的哪个属性是作为option标签体的值 51 itemValue="属性名":指定刚才遍历出来的这个对象的哪个属性是作为要提交 的value值 52 --> 53 <form:select path="department.id" 54 items="${depts }" 55 itemLabel="departmentName" 56 itemValue="id"></form:select><br/> 57 <input type="submit" value="保存"/> 58 </form:form> 59 60 61 62 63 <!-- (Employee) --> 64 <%-- <form action=""> 65 lastName:<input type="text" name="lastName"/><br/> 66 email:<input type="text" name="email"/><br/> 67 gender: <br/> 68 男:<input type="radio" name="gender" value="1"/><br/> 69 女:<input type="radio" name="gender" value="0"><br/> 70 dept: 71 <select name="department.id"> 72 <c:forEach items="${depts }" var="deptItem"> 73 <!-- 标签体中的是在页面的提示选项信息,value才是真正提交的值 --> 74 <option value="${deptItem.id }">${deptItem.departmentName }</option> 75 </c:forEach> 76 </select> 77 <input type="submit" value="提交"/> 78 </form> --%> 79 </body> 80 </html>
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 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <head> 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 8 <title>Insert title here</title> 9 <% 10 pageContext.setAttribute("ctp", request.getContextPath()); 11 %> 12 </head> 13 <body> 14 <h1>员工修改页面</h1> 15 <!-- modelAttribute:这个表单的所有内容显示绑定的是请求域中 employee的值--> 16 <form:form action="${ctp }/emp/${employee.id }" 17 modelAttribute="employee" method="post"> 18 <input type="hidden" name="_method" value="put"/> 19 <input type="hidden" name="id" value="${employee.id }"/> 20 email:<form:input path="email"/><br/> 21 gender: 22 男:<form:radiobutton path="gender" value="1"/> 23 女:<form:radiobutton path="gender" value="0"/><br/> 24 dept: 25 <form:select path="department.id" items="${depts }" 26 itemLabel="departmentName" itemValue="id"></form:select> 27 <br/> 28 <input type="submit" value="修改"/> 29 30 </form:form> 31 </body> 32 </html>
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 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 5 <html> 6 <% 7 pageContext.setAttribute("ctp", request.getContextPath()); 8 %> 9 <head> 10 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 11 <title>员工列表</title> 12 <script type="text/javascript" src="${ctp }/scripts/jquery-1.9.1.min.js"></script> 13 </head> 14 <body> 15 16 <h1>员工列表</h1> 17 <table border="1" cellpadding="5" cellspacing="0"> 18 <tr> 19 <th>ID</th> 20 <th>lastName</th> 21 <th>email</th> 22 <th>gender</th> 23 <th>birth</th> 24 <th>departmentName</th> 25 <th>EDIT</th> 26 <th>DELETE</th> 27 </tr> 28 <c:forEach items="${emps }" var="emp"> 29 <tr> 30 <td>${emp.id }</td> 31 <td>${emp.lastName}</td> 32 <td>${emp.email }</td> 33 <td>${emp.gender==0?"女":"男" }</td> 34 <td>${emp.birth}</td> 35 <td>${emp.department.departmentName }</td> 36 <td><a href="${ctp }/emp/${emp.id }">edit</a></td> 37 <td><a href="${ctp }/emp/${emp.id }" class="delBtn">delete</a></td> 38 </tr> 39 </c:forEach> 40 </table> 41 <a href="${ctp }/toaddpage">添加员工</a><br/> 42 43 <form action="${ctp }/quickadd"> 44 <!--将员工的所有信息都写上,自动封装对象 --> 45 <input name="empinfo" value="empAdmin-admin@qq.com-1-101"/> 46 <input type="submit" value="快速添加"/> 47 </form> 48 49 <form id="deleteForm" action="${ctp }/emp/${emp.id }" method="post"> 50 <input type="hidden" name="_method" value="DELETE" /> 51 </form> 52 <script type="text/javascript"> 53 $(function(){ 54 $(".delBtn").click(function(){ 55 //0、确认删除? 56 //1、改变表单的action指向; 57 $("#deleteForm").attr("action",this.href); 58 //2、提交表单; 59 $("#deleteForm").submit(); 60 return false; 61 }); 62 }); 63 </script> 64 </body> 65 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h1>成功!</h1> 11 jackson-annotations-2.1.5.jar 12 jackson-core-2.1.5.jar 13 jackson-databind-2.1.5.jar 14 </body> 15 </html>
相关依赖:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <parent> 6 <artifactId>SpringMVC</artifactId> 7 <groupId>com.atguigu</groupId> 8 <version>1.0-SNAPSHOT</version> 9 </parent> 10 <modelVersion>4.0.0</modelVersion> 11 <packaging>war</packaging> 12 <artifactId>8.SpringMVC_dataBinder</artifactId> 13 14 <dependencies> 15 <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl --> 16 <dependency> 17 <groupId>org.apache.taglibs</groupId> 18 <artifactId>taglibs-standard-impl</artifactId> 19 <version>1.2.5</version> 20 </dependency> 21 22 <!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-spec --> 23 <dependency> 24 <groupId>org.apache.taglibs</groupId> 25 <artifactId>taglibs-standard-spec</artifactId> 26 <version>1.2.5</version> 27 </dependency> 28 29 <!-- https://mvnrepository.com/artifact/org.hibernate.validator/hibernate-validator --> 30 <dependency> 31 <groupId>org.hibernate.validator</groupId> 32 <artifactId>hibernate-validator</artifactId> 33 <version>6.1.5.Final</version> 34 </dependency> 35 36 <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --> 37 <dependency> 38 <groupId>com.fasterxml.jackson.core</groupId> 39 <artifactId>jackson-databind</artifactId> 40 <version>2.11.0</version> 41 </dependency> 42 43 44 </dependencies> 45 46 </project>