SpringMVC-RestfulCRUD
利用SpringMVC做一个CRUD(增删改查)符合Rest风格的;
C:Create:创建
R:Retrieve:查询
U:Update:更新
D:Delete:删除
数据库:保存数据;
使用Map,List保存数据之类
员工列表展示;查询所有员工;
员工列表展示:访问index.jsp----直接发送/emps------控制器查询所有员工------放在请求域中-----转发到list页面展示
员工添加:
在list页面点击“”员工添加“”----(查询出所有的部门信息要展示在页面)----来到添加页面(add.jsp)--------输入员工数据--------点击保存(/emp )------处理器收到员工保存请求(保存员工)--------保存完成以后还是来到列表页面;
员工列表展示
员工添加
原生的form表单
用了表单标签的页面可能会报这个错误;
请求域中没有一个command类型的对象;
来到页面之前一定要给请求域中放这个对象;
Department.java
package com.atguigu.bean;
public class Department {
private Integer id;
private String departmentName;
public Department() {
}
public Department(int i, String string) {
this.id = i;
this.departmentName = string;
}
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.atguigu.bean;
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
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;
}
public Employee() {
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department=" + department
+ "]";
}
}
DepartmentDao.java
package com.atguigu.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.atguigu.bean.Department;
/**
* 操作部门的dao
*/
@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"));
}
/**
* 返回所有的部门
* @return
*/
public Collection<Department> getDepartments(){
return departments.values();
}
/**
* 按照部门id查询部门
* @param id
* @return
*/
public Department getDepartment(Integer id){
return departments.get(id);
}
}
EmployeeDao.java
package com.atguigu.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.atguigu.bean.Department;
import com.atguigu.bean.Employee;
/**
* EmployeeDao:操作员工
*/
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap<Integer, Employee>();
employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1, new Department(101, "D-AA")));
employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1, new Department(102, "D-BB")));
employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0, new Department(103, "D-CC")));
employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0, new Department(104, "D-DD")));
employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1, new Department(105, "D-EE")));
}
//初始id
private static Integer initId = 1006;
/**
* 员工保存/更新二合一方法;
* @param employee
*/
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
//根据部门id单独查出部门信息设置到员工对象中,页面提交的只需要提交部门的id
employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
/**
* 查询所有员工
* @return
*/
public Collection<Employee> getAll(){
return employees.values();
}
/**
* 按照id查询某个员工
* @param id
* @return
*/
public Employee get(Integer id){
return employees.get(id);
}
/**
* 删除某个员工
* @param id
*/
public void delete(Integer id){
employees.remove(id);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>7.SpringMVC_crud</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<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>
<!-- 字符编码Filter -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 支持Rest风格转换的filter -->
<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>
</web-app>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--suppress ALL -->
<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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
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.0.xsd">
<context:component-scan base-package="com.atguigu"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 默认前端控制器是拦截所有资源(除过jsp),js文件就404了;要js文件的请求是交给tomcat处理的
http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js -->
<!-- 告诉SpringMVC,自己映射的请求就自己处理,不能处理的请求直接交给tomcat -->
<!-- 静态资源能访问,动态映射的请求就不行 -->
<mvc:default-servlet-handler/>
<!-- springmvc可以保证动态请求和静态请求都能访问 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!-- 访问项目就要展示员工列表页面 -->
<jsp:forward page="/emps"></jsp:forward>
EmployeeController.java
package com.atguigu.controller;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.atguigu.bean.Department;
import com.atguigu.bean.Employee;
import com.atguigu.dao.DepartmentDao;
import com.atguigu.dao.EmployeeDao;
@Controller
public class EmployeeController {
@Autowired
EmployeeDao employeeDao;
@Autowired
DepartmentDao departmentDao;
/**
* 查询所有员工
*
* @return
*/
@RequestMapping("/emps")
public String getEmps(Model model) {
Collection<Employee> all = employeeDao.getAll();
model.addAttribute("emps", all);
return "list";
}
/**
* 删除员工
*
* @return
*/
@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
public String deleteEmp(@PathVariable("id")Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
/**
* 查询员工,来到修改页面回显
*
* @param id
* @param model
* @return
*/
@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
public String getEmp(@PathVariable("id") Integer id, Model model) {
// 1、查出员工信息
Employee employee = employeeDao.get(id);
// 2、放在请求域中
model.addAttribute("employee", employee);
// 3、继续查出部门信息放在隐含模型中
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts", departments);
return "edit";
}
@RequestMapping(value = "/emp/{id}", method = RequestMethod.PUT)
public String updateEmp(@ModelAttribute("employee")Employee employee/* ,@PathVariable("id")Integer id */) {
System.out.println("要修改的员工:" + employee);
// xxxx 更新保存二合一;
employeeDao.save(employee);
return "redirect:/emps";
}
@ModelAttribute
public void myModelAttribute(
@RequestParam(value = "id", required = false) Integer id,Model model) {
if (id != null) {
Employee employee = employeeDao.get(id);
model.addAttribute("employee", employee);
}
System.out.println("hahha ");
}
/**
* 保存员工
*
* @param employee
* @return
*/
@RequestMapping(value = "/emp", method = RequestMethod.POST)
public String addEmp(Employee employee) {
System.out.println("要添加的员工:" + employee);
employeeDao.save(employee);
// 返回列表页面;重定向到查询所有员工的请求
return "redirect:/emps";
}
/**
* 去员工添加页面,去页面之前需要查出所有部门信息,进行展示的
*
* @return
*/
@RequestMapping("/toaddpage")
public String toAddPage(Model model) {
// 1、先查出所有部门
Collection<Department> departments = departmentDao.getDepartments();
// 2、放在请求域中
model.addAttribute("depts", departments);
model.addAttribute("employee", new Employee());
// 3、去添加页面
return "add";
}
}
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>员工列表</title>
<script type="text/javascript" src="${ctp}/scripts/jquery-1.9.1.min.js"></script>
</head>
<body>
<h1>员工列表</h1>
<%-- cellpadding:单元格里面文字到单元格边框的距离
cellspacing:单元格之间的距离
--%>
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<th>ID</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>departmentName</th>
<th>EDIT</th>
<th>DELETE</th>
</tr>
<c:forEach items="${emps}" var="emp">
<tr>
<td>${emp.id}</td>
<td>${emp.lastName}</td>
<td>${emp.email}</td>
<td>${emp.gender==0?"女":"男"}</td>
<td>${emp.department.departmentName}</td>
<td><a href="${ctp}/emp/${emp.id}">edit</a></td>
<td><a href="${ctp}/emp/${emp.id}" class="delBtn">delete</a></td>
</tr>
</c:forEach>
</table>
<a href="${ctp}/toaddpage">添加员工</a>
<form id="deleteForm" action="" method="post">
<input type="hidden" name="_method" value="DELETE" />
</form>
<script type="text/javascript">
$(function(){
$(".delBtn").click(function(){
//0、确认删除?
//1、改变表单的action指向
$("#deleteForm").attr("action",this.href);
//2、提交表单
$("#deleteForm").submit();
return false;
});
});
</script>
</body>
</html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>
</head>
<body>
<h1>员工添加</h1>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
<%--@elvariable id="employee" type=""--%>
<form:form action="${ctp}/emp" modelAttribute="employee" method="POST">
lastName:<form:input path="lastName"/><br/>
email:<form:input path="email"/><br/>
gender:<br/>
男:<form:radiobutton path="gender" value="1"/><br/>
女:<form:radiobutton path="gender" value="0"/><br/>
dept:
<form:select path="department.id"
items="${depts}"
itemLabel="departmentName"
itemValue="id">
</form:select><br/>
<input type="submit" value="保存"/>
</form:form>
</body>
</html>
edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!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>
<%
pageContext.setAttribute("ctp", request.getContextPath());
%>
</head>
<body>
<h1>员工修改页面</h1>
<!-- modelAttribute:这个表单的所有内容显示绑定的是请求域中 employee的值-->
<form:form action="${ctp}/emp/${employee.id}"
modelAttribute="employee" method="post">
<input type="hidden" name="_method" value="put"/>
<input type="hidden" name="id" value="${employee.id }"/>
email:<form:input path="email"/><br/>
gender:
男:<form:radiobutton path="gender" value="1"/>
女:<form:radiobutton path="gender" value="0"/><br/>
dept:
<form:select path="department.id" items="${depts}"
itemLabel="departmentName" itemValue="id">
</form:select> <br/>
<input type="submit" value="修改"/>
</form:form>
</body>
</html>