界面:
项目结构:
代码
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>springmvc-2</display-name>
<!-- 配置filter 把POST请求转为 DELETE 、PUT请求 -->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class> org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC 的DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- 配置自动扫描类 -->
<context:component-scan base-package="com.jxust.springmvc"></context:component-scan>
<!--配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 静态资源交给默认的Servlet-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
Department.java
package com.jxust.springmvc.crud.entities;
/**
* 部门实体类
* @author Peng
* @Date2016年12月3日下午8:33:47
*/
public class Department {
private Integer id;
private String departmentName;
public Department() {
super();
}
public Department(Integer id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
Employee.java
package com.jxust.springmvc.crud.entities;
/**
* 员工实体类
* @author Peng
* @Date2016年12月3日下午8:33:18
*/
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male,0 female
private Integer gender;
private Department department;
public Employee() {
super();
}
public Employee(Integer id, String lastName, String email, Integer gender, Department department) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
}
// 省略 setter and getter
public void setDepartment(Department department) {
this.department = department;
}
}
DepartmentDao.java
package com.jxust.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.jxust.springmvc.crud.entities.Department;
@Repository
public class DepartmentDao {
private static Map<Integer,Department> departments = null;
static{
departments = new HashMap<Integer,Department>();
departments.put(101, new Department(101,"D-AA"));
departments.put(102, new Department(102,"D-BB"));
departments.put(103, new Department(103,"D-CC"));
departments.put(104, new Department(104,"D-DD"));
departments.put(105, new Department(105,"D-EE"));
}
public Collection<Department> getDepartments(){
return departments.values();
}
public Department getDepartment(Integer id){
return departments.get(id);
}
}
EmployeeDao.java
package com.jxust.springmvc.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.jxust.springmvc.crud.entities.Department;
import com.jxust.springmvc.crud.entities.Employee;
@Repository
public class EmployeeDao {
public static Map<Integer,Employee> employees = null;
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap<Integer,Employee>();
employees.put(1001, new Employee(1001,"E-AA","aa@163.com",1,new Department(101,"D-AA")));
employees.put(1002, new Employee(1002,"E-BB","bb@163.com",1,new Department(102,"D-BB")));
employees.put(1003, new Employee(1003,"E-CC","cc@163.com",0,new Department(103,"D-CC")));
employees.put(1004, new Employee(1004,"E-DD","dd@163.com",0,new Department(104,"D-DD")));
employees.put(1005, new Employee(1005,"E-EE","ee@163.com",1,new Department(105,"D-EE")));
}
private static Integer inintid = 1006;
public void save(Employee employee){
if(employee.getId()==null){
employee.setId(inintid++);
}
employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
public Collection<Employee> getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
Controller 控制器
EmployeeHandler.java
package com.jxust.springmvc.curd.handlers;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.jxust.springmvc.crud.dao.DepartmentDao;
import com.jxust.springmvc.crud.dao.EmployeeDao;
import com.jxust.springmvc.crud.entities.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
/**
* 显示所有Employee信息 对应list.jsp
*
* @param map
* @return
*/
@RequestMapping("/emps")
public String list(Map<String, Object> map) {
map.put("employees", employeeDao.getAll());
System.out.println("执行list方法,查询所有员工信息.....");
return "list";
}
/**
* 跳转到添加页面input.jsp
* get 请求
* @param map
* @return
*/
@RequestMapping(value = "/emp", method = RequestMethod.GET)
public String input(Map<String, Object> map) {
map.put("departments", departmentDao.getDepartments());
map.put("employee", new Employee());
System.out.println("执行input方法,跳转到添加页面input.jsp.....");
return "input";
}
/**
* 保存Employee操作
* post 请求
* @param employee
* @return
*/
@RequestMapping(value = "/emp", method = RequestMethod.POST)
public String save(Employee employee) {
System.out.println("执行save方法,保存添加的数据.....");
employeeDao.save(employee);
return "redirect:/emps";
}
/**
* 删除操作
* delete 请求
* @param id
* @return
*/
@RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
System.out.println("执行delete方法,删除一条数据.....");
employeeDao.delete(id);
return "redirect:/emps";
}
/**
* 转到修改页面input.jsp,并回显数据
* get 请求
* @param id
* @param map
* @return
*/
@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
public String input(@PathVariable("id") Integer id, Map<String, Object> map) {
map.put("employee", employeeDao.get(id));
map.put("departments", departmentDao.getDepartments());
return "input";
}
/**
* 执行修改操作时,lastName 不修改,为了防止为null,需要获取从数据库中获取包含该属性值的对象
* @param id
* @param map
*/
@ModelAttribute
public void getEmployee(@RequestParam(value = "id", required = false) Integer id, Map<String, Object> map) {
System.out.println("ModelAttribute方法执行....");
if (id != null) {
map.put("employee", employeeDao.get(id));
}
}
/**
* 修改操作
* put 请求
* @param employee
* @return
*/
@RequestMapping(value = "/emp", method = RequestMethod.PUT)
public String update(Employee employee) {
System.out.println("执行update方法...");
employeeDao.save(employee);
return "redirect:/emps";
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$(function() {
//alert("hello");
});
</script>
</head>
<body>
<a href="emps"> List ALL</a>
</body>
</html>
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$(function() {
//alert("hello");
$(".delete").click(function(){
var href = $(this).attr("href");
$("form").attr("action",href).submit();
return false;
})
});
</script>
</head>
<body>
<form action="" method="post">
<input type="hidden" name="_method" value="DELETE"/>
</form>
<c:if test="${empty requestScope.employees }">
没有任何员工信息。
</c:if>
<c:if test="${!empty requestScope.employees }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>ID</td>
<td>LastName</td>
<td>Email</td>
<td>Gender</td>
<td>Department</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<c:forEach items="${requestScope.employees }" var="emp">
<tr>
<th>${emp.id }</th>
<th>${emp.lastName }</th>
<th>${emp.email }</th>
<th>${emp.gender==0?'Female':'Male' }</th>
<th>${emp.department.departmentName }</th>
<th><a href="emp/${emp.id}">Edit</a></th>
<th><a class="delete" href="emp/${emp.id}">Delete</a></th>
</tr>
</c:forEach>
</table>
</c:if>
<br><br>
<a href="emp">Add New Employee</a>
</body>
</html>
input.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改和添加都使用这个页面</title>
</head>
<body>
<!--
1.为什么使用 form 标签
可以快速的开发出表单页面,而且可以更方便的进行表单值的回显
2.注意
可以通过 modelAttribute 属性指定绑定的模型属性,
若没有指定该属性,则默认从request 域对象中读取 command 的表单 bean,如果找不到command会报错
form:。。 是主要用来回显的,path里的对应属性都要有,不管其值为空等等
action="${pageContext.request.contextPath}/emp" 不使用这个input方法报错
/emp
-->
<form:form action="${pageContext.request.contextPath}/emp" method="post" modelAttribute="employee">
<!--path 属性对应Html 表单标签的 name 属性值 -->
<!-- 修改时,不显示lastName-->
<c:if test="${employee.id == null }">
LastName:<form:input path="lastName"/> <br>
</c:if>
<c:if test="${employee.id!=null }">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="put"/>
</c:if>
Email:<form:input path="email"/> <br>
<%
Map<Integer,String> genders = new HashMap<Integer,String>();
genders.put(1, "Male");
genders.put(0, "Female");
request.setAttribute("genders", genders);
%>
Gender:<br>
<form:radiobuttons path="gender" items="${genders }" delimiter="<br>"/> <br>
Department:
<!--path="department.id"用到了级联属性 -->
<form:select path="department.id" items="${departments }"
itemLabel="departmentName" itemValue="id"><br>
</form:select>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
笔记.txt
1. form:input,form:password,form:hidden,form:textarea
对应Html表单中的text,password,hidden,textarea 标签
2. form:radiobutton 单选框组件标签,当表单bean 对应的属性值和 value 值相等时,
单选框被选中
form:radiobuttons 单选框组标签,用于构造多个单选框
--items 可以是 List、String[] 、Map
--itemValue 指定radio的value值,可以是集合中bean的一个属性值
--itemLabel 指定radio的label 值
--delimiter 多个单选框可以通过 delimiter 指定分隔符
3. form:checkbox 复选框组件,用于构造单个复选框
form:checkboxs 用于构造多个复选框,使用方式同 form:radiobuttons标签
4. form:select 用于构造下拉框组件,使用方式同form:radiobuttons标签
5. form:option 下拉框选项组件标签。使用方式同form:radiobuttons标签
6. form:errors 显示表单组件或者数据校验所对应的错误
--<form:errors path="*" /> 显示表单所有错误
--<form:errors path="user* /> 显示所有以user为前缀的属性对应的错误
--<form:errors path="username"/> 显示特定表单对象属性的错误
--------------------------
<mvc:annotation-driven></mvc:annotation-driven>
会自动注册 RequestMappingHandlerMapping、RequestMappingHandlerAdapter
和ExceptionHandlerExceptionResolver三个bean
还提供了以下的支持
-支持使用ConversionService 示例对表单参数进行类型转换
-支持使用@NumberFormatannotation、@DateTimeFormat 注解完成数据类型的格式化
-支持使用 @Valid 注解对 JavaBean 实例进行JSR 303验证
-支持使用@RequestBody 和 @ResponseBody 注解