目标: 实现数据库的增删改查。
实现: 使用静态数据-代替连接数据库,-数据静态存放在dao层
相关细节: restrul风格 -- 不知如何解释,那就举个例子:假如你想对数据库进行增删改查操作,那么使用rest风格,你就只需要
在写一个相同的URI,但是类型不同就可以实现。例如:
增加:URI: localhost:8080/test/operate 类型: POST
删除:URI: localhost:8080/test/operate 类型: DELETE
修改:URI: localhost:8080/test/operate 类型: PUT
查询:URI: localhost:8080/test/operate 类型: GET
只需要这样写,就可以实现相关操作,实现需要借助org.springframework.web.filter.HiddenHttpMethodFilter,来将相关的POST请求转换为PUT、DELETE。
实现细节:在提交时需要设置相关属性
<form id="form" action="emp/{id}" method="post">
<!-- name必须为 _method value 为相关操作类型 例:PUT DELETE -->
<input type="hidden" name="_method" value="DELETE" />
</form>
同时在controller中也需要设置RequestMapping的属性来判断请求是否由该方法处理
// 设置映射地址 - 接收一个参数id 该请求类型为 DELETE
@RequestMapping(value="/emp/{id}",method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
System.out.println("delete:"+id);
employeeDao.delete(id);
return "redirect:/emps";//重定向
}
--- 总体实现:
0.配置springmvc.xml 以及 web.xml
// web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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_3_0.xsd" id="WebApp_ID" version="3.0">
<!-- 配置分发器 -->
<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> <!-- 拦截所有请求 但不会拦截 *.jsp等请求 -->
</servlet-mapping>
<!-- HiddenHttpMethodFilter:将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> <!-- 拦截所有,匹配所有 包括 *.jsp-->
</filter-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.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.1.xsd">
<!-- 扫描包 -->
<context:component-scan base-package="com.yyl"></context:component-scan>
<!-- 配置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 自动判断请求类型,不会拦截静态资源 -->
<mvc:default-servlet-handler/>
<!-- 注册驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
1.导入spring相关jar包
2.编写pojo实体类
// 员工信息
public class Employee {
private int id;
private String lastName;
private String email;
// 1 男 0 女
private Integer gender;
private Department department;
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender
+ ", department=" + department + "]";
}
public Employee(int 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() {
super();
}
}
// 部门信息
public class Department {
private int id;
private String departmentName;
public Department() {
super();
}
public int getId() {
return id;
}
public void setId(int 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 + "]";
}
public Department(int id, String departmentName) {
super();
this.id = id;
this.departmentName = departmentName;
}
}
2.编写dao层代码
// departmentDao
@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", "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 initId = 1006;
public void save(Employee employee){
if(employee.getId() == 0 ){
employee.setId(initId++);
}
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);
}
}
//employeeDao
package com.yyl.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.yyl.crud.pojo.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);
}
}
3.编写controller实现类 -- 前端页面 -list.jsp 显示员工所有信息 -input 添加修改员工信息 -index.jsp 提供进入list.jsp链接
@Controller
public class EmployHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
// 该方法会在目标方法执行前执行
// 主要目的 -- 因为作修改操作时,不允许修改lastName
// 而 在修改操作时,处理方法会在容器中找相关对象,找到就会为其相关属性赋值
// 所以在修改操作前 先将原本的对象放入map中,在修改时只允许修改除了lastName
// 之外的属性,那么提交后的数据只会修改提交的属性数据,lastName不会修改
@ModelAttribute
public void getEmployee(@RequestParam(value = "id",required = false)Integer id,Map<String,Object>map) {
if(id!=null) {
map.put("employee", employeeDao.get(id));
}
}
// 映射地址 /emp 并且请求类型为 PUT -- 处理修改操作
@RequestMapping(value="/emp",method = RequestMethod.PUT)
public String update(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}
// 映射地址 /emp 并且 后跟 id 并且请求类型为 GET -- 处理获取信息修改操作
@RequestMapping(value="/emp/{id}",method = RequestMethod.GET)
public String edit(@PathVariable("id") Integer id,Map<String,Object>map) {
map.put("employee", employeeDao.get(id));
map.put("department",departmentDao.getDepartments());
return "input";
}
// 映射地址 /emp 后跟参数id 并且请求类型为 DELETE -- 处理删除操作 根据id删除信息
@RequestMapping(value="/emp/{id}",method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
System.out.println("delete:"+id);
employeeDao.delete(id);
//System.out.println(employeeDao.getAll());
return "redirect:/emps";
}
// 映射地址 /emp 并且请求类型为 POST -- 处理添加 - 提交 操作
@RequestMapping(value="/emp",method = RequestMethod.POST)
public String save(Employee employee) { // 如果提交的表单数据时一个pojo对象,参数
employeeDao.save(employee); // 设置为该pojo对象,会自动为pojo对象赋值
return "redirect:/emps";
}
// 映射地址 /emp 并且请求类型为 GET -- 处理点击添加链接时操作
@RequestMapping(value="/emp",method = RequestMethod.GET)
public String departments(Map<String,Object> map) {
map.put("department",departmentDao.getDepartments());
map.put("employee", new Employee());
return "input";
}
// 映射地址 /emps -- 显示全部信息
@RequestMapping("/emps")
public String list(Map<String,Object> map) {
map.put("employees", employeeDao.getAll()); // 在了requestScope作用域
return "list"; // 可以获取该对象
}
}
4.前端页面编写
// index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<a href="emps">显示所有员工信息</a>
</body>
</html>
// 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>
<html>
<head>
<meta charset="utf-8">
<title>list</title>
<script type="text/javascript" src="/SpringMVC02/js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function() {
$("#del").click(function() {
var href = $("#del").attr("href");
$("#form").attr("action", href).submit();
return false;
})
})
</script>
</head>
<body>
// 设置URI提交类型
<form id="form" action="emp/{id}" 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">
<tr>
<td>ID</td>
<td>lastName</td>
<td>email</td>
<td>gender</td>
<td>DeparmenttName</td>
<td>edit</td>
<td>delete</td>
</tr>
<c:forEach items="${requestScope.employees }" var="emp">
<tr>
<td>${emp.id }</td>
<td>${emp.lastName }</td>
<td>${emp.email }</td>
<td>${emp.gender==1? '男':'女' }</td>
<td>${emp.department.departmentName }</td>
<td><a href="emp/${emp.id}">edit</a></td>
<td><a id="del" href="emp/${emp.id}">delete</a></td>
</tr>
</c:forEach>
</c:if>
</table>
<br><br><br>
<a href="emp">添加</a>
</body>
</html>
// input.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>添加</title>
</head>
<body>
<form:form action="${pageContext.request.contextPath}/emp" method="POST" modelAttribute="employee">
// 如果employee.id为0那么就是添加操作,否则就是修改,修改操作会隐藏lastName域
<c:if test="${employee.id == 0}">
lastName:<form:input path="lastName" />
</c:if>
<c:if test="${employee.id != 0}">
<form:hidden path="id" />
<input type="hidden" name="_method" value="PUT"/>
</c:if>
<br>
email:<form:input path="email" />
<br>
<%
Map<String, String> gender = new HashMap<String, String>();
gender.put("1", "男");
gender.put("0", "女");
request.setAttribute("gender", gender);
%>
Gender:<form:radiobuttons path="gender" items="${gender }" />
<br>
Department:<form:select path="department.id" items="${department }" itemLabel="departmentName" itemValue="id"></form:select>
<br>
<input type="submit" value="submit"/>
</form:form>
</body>
</html>
相关处理流程:
增加:在list.jsp 页面下点击 添加 链接 href=‘emp’,EmployHandler 交由相关方法处理 - - URI : localhost:8080/emp get请求,方法内,1.获取部门信息(在添加页面[input.jsp]中下拉框选择部门)。2.放入map(requestScope作用域中) 3.请求转发到input.jsp页面,input.jsp页面解析,el表达式判断是否有employee.id值,没有,添加操作,显示lastName域,填写信息,提交URI:localhost:8080/emp ,POST请求,交由相关方法处理,--保存信息,同时重定向到显示所有信息页面。
修改: 在list.jsp页面下选择修改的行,点击 edit 连接,URI:localhost:8080/emp/${emp.id},GET请求,交由修改方法处理,
修改方法,将该行信息存入map(requestScope作用域中),然后请求转发到input.jsp页面,input.jsp页面判断在相关作用域中存在employee.id那么就会解析为修改请求,同时隐藏-lastName域(禁止修改),注意该方法执行前,会有一个方法提前执行,拥有@ModelAttribute的方法,判断是否有employee.id决定创建employee对象,如果employee.id为空,那么不处理,为其他处理,否则将当前id的employee信息存入作用域中(因为lastName不允许修改,故在修改时,让修改的对象为作用域中已存在的,那么只会修改提交的属性[修改时,会隐藏lastName域,所以不会有值被提交],这样lastName不会改变),最后重定向到显示所有信息页面。
删除:同上-注意,由于删除操作不会提供第二个页面,所以在当前页面提交请求,所以在list.jsp页面需要写一个form表单,设置请求(<input type="hidden" name="_method" value="DELETE" />)为DELETE,然后通过jquery实现当点击删除链接时,设置将链接的href:emp/${emp.id} ,设置为form表单的action属性,同时,将form表单提交,并且链接失效,这样,通过form表单提交就会是,DELETE类型的请求。