spingMVC学习笔记——RESTful形式的增删改查

项目结构

在这里插入图片描述

实体类

在这里插入图片描述
Employee.java

package com.mcc.springMVC.rest.pojo;

public class Employee {

	private Integer id;
	private String lastName;
	private String email;
	//1 male, 0 female
	private Integer gender;
	private Department department;
	
	public Employee() {}
	
	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 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;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", email="
				+ email + ", gender=" + gender + ", department=" + department
				+ "]";
	}
}

Department.java

package com.mcc.springMVC.rest.pojo;

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
				+ "]";
	}
}

DAO类

在这里插入图片描述
EmployeeDao.java

package com.mcc.springMVC.rest.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.mcc.springMVC.rest.pojo.Department;
import com.mcc.springMVC.rest.pojo.Employee;

@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() == null){
			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);
	}
}

DepartmentDao.java

package com.mcc.springMVC.rest.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import com.mcc.springMVC.rest.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);
	}	
}

控制层

在这里插入图片描述

  • 跳转到显示全部员工信息页面之前,要先查询全部员工信息,之后才能在页面上显示,
    使用请求转发无法触发servlet,因此使用重定向先访问getAll()

EmpCotroller.java

package com.mcc.springMVC.rest.control;

import java.util.Collection;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.mcc.springMVC.rest.dao.DepartmentDao;
import com.mcc.springMVC.rest.dao.EmployeeDao;
import com.mcc.springMVC.rest.pojo.Department;
import com.mcc.springMVC.rest.pojo.Employee;

@Controller
public class EmpController {
	@Autowired
	private EmployeeDao employeeDao;
	@Autowired
	private DepartmentDao departmentDao;
	/**
	 * 查询全部员工信息
	 * @param model
	 * @return listForAll视图
	 */
	@RequestMapping(value="/emps")
	public String getAll(Model model) {
		Collection<Employee> emps = employeeDao.getAll();
		model.addAttribute("emps", emps);
		return "listForAll";
	}
	/**
	 * 跳转到add视图
	 * 点击add按钮之后,跳转到添加视图时,要查询全部部门信息,用于显示在下来列表中
	 * @param model
	 * @return add添加视图
	 */
	@RequestMapping(value="/emp",method=RequestMethod.GET)
	public String toAddView(Model model) {
		//创建Map集合,存入gender的所有取值情况,用于表单中自动创建单选框
		HashMap<Integer,String> genderMap = new HashMap<Integer,String>();
		genderMap.put(1, "男");
		genderMap.put(0, "女");
		model.addAttribute("gender", genderMap);
		//获取所有部门信息,添加到Request域中,在下拉列表中显示
		Collection<Department> departments = departmentDao.getDepartments();
		model.addAttribute("departments", departments);
		//设置页面自动回显时,要搜索的域对象,默认key为command,这里是跳转到添加页面,因此不需要回显
		model.addAttribute("command",new Employee());
		return "edit";
	}
	/**
	 * 保存员工信息
	 * @param emp
	 * @return 重定向到getAll(),再由getAll()跳转到listForAll视图
	 */
	@RequestMapping(value="/emp",method=RequestMethod.POST)
	public String addEmp(Employee emp) {
		employeeDao.save(emp);
		//跳转到显示全部员工信息页面之前,要先查询全部员工信息,之后才能在页面上显示,
		//使用请求转发无法触发servlet,因此使用重定向先访问getAll()
		return "redirect:/emps";
	}
	/**
	 * 跳转到修改页面
	 * @param id
	 * @param model
	 * @return update视图
	 */
	@RequestMapping(value="/emp/{id}",method=RequestMethod.GET)
	public String toUpdateView(@PathVariable("id")Integer id, Model model) {
		//查询id员工信息,保存到域中,用于在页面中回显
		Employee employee = employeeDao.get(id);
		model.addAttribute("emp", employee);
		//创建Map集合,存入gender的所有取值情况,用于表单中自动创建单选框
		HashMap<Integer,String> genderMap = new HashMap<Integer,String>();
		genderMap.put(1, "男");
		genderMap.put(0, "女");
		model.addAttribute("gender", genderMap);
		//查询全部部门信息,用于在页面上回显下拉框
		Collection<Department> departments = departmentDao.getDepartments();
		model.addAttribute("departments", departments);
		//将员工信息保存到command中,用于自动回显
		model.addAttribute("command", employee);
		return "edit";
	}
	/**
	 * 修改员工信息
	 * @param employee
	 * @return 显示全部员工页面
	 */
	@RequestMapping(value="/emp",method=RequestMethod.PUT)
	public String updateEmp(Employee employee) {
		employeeDao.save(employee);
		return "redirect:/emps";
	}
	/**
	 * 删除用户信息
	 * @param id
	 * @return 显示全部员工页面
	 */
	@RequestMapping(value="/emp/{id}",method=RequestMethod.DELETE)
	public String deleteEmp(@PathVariable("id")Integer id) {
		employeeDao.delete(id);
		return "redirect:/emps";
	}	
}

配置文件

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_4_0.xsd" version="4.0">
  <display-name>RESTful_CRUD</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <!-- 配置字符编码过滤器 -->
  <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>
  </filter>
  <filter-mapping>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 配置 REST 风格过滤器-->
  <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>
  
  <!-- 配置核心控制器 -->
  <!-- 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-REST.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-REST.xml

在这里插入图片描述

  • 配置Tomcat的默认servlet,即DefaultServlet(注意:该注解要配合开启MVC驱动注解使用才有效)
  • DefaultServlet的请求路径与DispatcherServlet的请求路径相同,都为 /
  • 处理请求时,开发人员编写的Servlet优先级高于DefaultServlet,因此,当收到客户端传来的请求时,DispatcherServlet先去搜索项目中有无能够处理该请求的方法,若有,则处理请求,若没有,则该请求交给DefaultServlet处理。
  • 对于静态资源而言,DispatcherServlet不能处理,需要使用DefaultServlet处理,所以要配置Tomcat的DefaultServlet
<?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.xsd
	http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	
	<!-- 开启组件扫描 -->
	<context:component-scan base-package="com.mcc.springMVC.rest"></context:component-scan>
	
	<!-- 配置视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<!-- 
		配置Tomcat的默认servlet,即DefaultServlet(注意:该注解要配合开启MVC驱动注解使用才有效)
		
		DefaultServlet的请求路径与DispatcherServlet的请求路径相同,都为 /,
		处理请求时,开发人员编写的Servlet优先级高于DefaultServlet,
		因此,当收到客户端传来的请求时,DispatcherServlet先去搜索项目中有无能够处理该请求的方法,
		若有,则处理请求,若没有,则该请求交给DefaultServlet处理。
		
		对于静态资源而言,DispatcherServlet不能处理,需要使用DefaultServlet处理,所以要配置Tomcat的DefaultServlet
	 -->
	<mvc:default-servlet-handler/>
	
	<!-- 开启MVC驱动 -->
	<mvc:annotation-driven/>
	
</beans>

页面

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
	<a href="${ pageContext.request.contextPath }/emps">显示全部员工信息</a>
</body>
</html>

CURD页面

在这里插入图片描述

  • script标签如果使用src引入了jQuery文件,那么该标签内部就不能再写jQuery代码,如果要写代码,需要重新写一个script标签。
  • 遍历过程为所有信息绑定删除链接,不能使用id,因为遍历时id都相同,要使用class。
  • 将a标签的href属性赋值给form表单的action属性,点击a标签之后,阻止a标签的提交行为,转而提交表单即可。
  • 问题:为什么不在form表单中直接书写action属性?
    原因:删除需要传递id值,每个信息的id值是在遍历时与对应的信息绑定的,若直接书写action值,只绑定了一个信息的id,因此不可行。

listForAll.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>显示全部员工信息</title>
	<!-- 
		script标签如果使用src引入了jQuery文件,那么该标签内部就不能再写jQuery代码,
		如果要写代码,需要重新写一个script标签。
	 -->
	<script type="text/javascript" src="${ pageContext.request.contextPath }/static/jquery-1.7.2.js"></script>
	<script type="text/javascript">
		$(function(){
			$("a.delete").click(function(){
				//获取当前正在操作的用户名
				var empName = $("#empName").text();
				//提示用户是否确认删除
				if(confirm("是否要删除用户:"+empName)){
					//获取form表单的action属性,将当前正在执行操作的a标签的href属性赋值给action,之后执行提交操作
					$("#del_form").attr("action", $(this).attr("href")).submit();
					//阻止a标签的默认请求操作
					return false;
				}
				//取消删除时也要阻止a标签的默认操作
				return false;
			});
		});
	</script>
</head>
<body>
	<table>
		<tr>
			<th>id</th>
			<th>name</th>
			<th>gender</th>
			<th>email</th>
			<th>department_name</th>
			<th>option(<a href="${ pageContext.request.contextPath }/emp">add</a>)</th>
		</tr>
		<c:forEach items="${ emps }" var="emps">
			<tr>
				<td>${ emps.id }</td>
				<td id="empName">${ emps.lastName }</td>
				<td>${ emps.gender eq '1' ? '男' : '女' }</td>
				<td>${ emps.email }</td>
				<td>${ emps.department.departmentName }</td>
				<td>
					<a href="${ pageContext.request.contextPath }/emp/${ emps.id }">update</a>
					<!-- 
						遍历过程为所有信息绑定删除链接,不能使用id,因为遍历时id都相同,要使用class。
						将a标签的href属性赋值给form表单的action属性,
						点击a标签之后,阻止a标签的提交行为,转而提交表单即可。
						
						问题:为什么不在form表单中直接书写action属性?
						原因:删除需要传递id值,每个信息的id值是在遍历时与对应的信息绑定的,
							若直接书写action值,只绑定了一个信息的id,因此不可行。
					 -->
					<a class="delete" href="${ pageContext.request.contextPath }/emp/${ emps.id }">delete</a>
				</td>
			</tr>
		</c:forEach>
	</table>
	
	<!-- 实现DELETE请求的form表单 -->
	<form id="del_form" method="post">
		<input type="hidden" name="_method" value="DELETE"/>
	</form>
	
</body>
</html>

edit.jsp:添加和修改页面

  • <form:form></form:form>可以实现表单的自动回显,相当于有一个隐式的value属性。该标签会自动在指定的域对象中搜索与path属性同名的属性,搜索到之后,会将该域对象的属性值赋值给path的value属性,实现数据的回显以及发送。例如,域对象user中包含username和password属性,path=“username”,指定搜索的域对象为user后,会将user的username值赋值给path的username。
  • modelAttribute:设置在哪个域对象中搜索数据,默认为command。
<%@ 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>
<html>
<head>
<meta charset="UTF-8">
<title>修改员工信息</title>
</head>
<body>
	<!-- modelAttribute:设置在哪个域对象中搜索数据,默认为command -->
	<form:form action="${ pageContext.request.contextPath }/emp" method="POST" modelAttribute="command">
		<c:if test="${ not empty command.id }">
			<form:hidden path="id"/>
		</c:if>
		<table>
			<tr>
				<td>name:</td>
				<td><form:input path="lastName"/></td>
			</tr>
			<tr>
				<td>email:</td>
				<td><form:input path="email"/></td>
			</tr>
			<tr>
				<td>gender:</td>
				<td>
					<!-- 遍历gender,并自动将key作为返回值,value作为显示在页面的信息 -->
					<form:radiobuttons path="gender" items="${ gender }"/>
				</td>
			</tr>
			<tr>
				<td>department:</td>
				<td>
					<!-- item:遍历的对象,itemValue:返回的值,itemLabel:显示的信息 -->
					<form:select path="department.id">
						<form:options items="${ departments }" itemValue="id" itemLabel="departmentName"/>
					</form:select>
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="UPDATE"/></td>
			</tr>
		</table>
	</form:form>
</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"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>添加员工</title>
</head>
<body>
	<form action="${ pageContext.request.contextPath }/emp" method="POST">
		<table>
			<tr>
				<td>name:</td>
				<td><input type="text" name="lastName"/></td>
			</tr>
			<tr>
				<td>email:</td>
				<td><input type="text" name="email"/></td>
			</tr>
			<tr>
				<td>gender:</td>
				<td><input type="radio" name="gender" value="1"/><input type="radio" name="gender" value="0"/>
				</td>
			</tr>
			<tr>
				<td>department:</td>
				<td>
					<select name="department.id">
						<option>-----select departmentName-----</option>
						<c:forEach items="${ departments }" var="depts">
							<option value="${ depts.id }">${ depts.departmentName }</option>
						</c:forEach>
					</select>
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="ADD"/></td>
			</tr>
		</table>
	</form>
</body>
</html>

update.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>修改员工信息</title>
</head>
<body>
	<form action="${ pageContext.request.contextPath }/emp" method="POST">
		<input type="hidden" name="id" value="${ emp.id }"/>
		<input type="hidden" name="_method" value="PUT"/>
		<table>
			<tr>
				<td>name:</td>
				<td><input type="text" name="lastName" value="${ emp.lastName }"/></td>
			</tr>
			<tr>
				<td>email:</td>
				<td><input type="text" name="email" value="${ emp.email }"/></td>
			</tr>
			<tr>
				<td>gender:</td>
				<td><input type="radio" name="gender" value="1" ${ emp.gender eq '1' ? 'checked' : '' }/><input type="radio" name="gender" value="0" ${ emp.gender eq '0' ? 'checked' : '' }/>
					<!-- 
					男<input type="radio" name="gender" value="0" <c:if test="${ emp.gender eq '1' }">checked="checked"</c:if>/>
					女<input type="radio" name="gender" value="0" <c:if test="${ emp.gender eq '0' }">checked="checked"</c:if>/>
					 --!>
				</td>
			</tr>
			<tr>
				<td>department:</td>
				<td>
					<select name="department.id">
						<option>-----select departmentName-----</option>
						<c:forEach items="${ departments }" var="depts">
							<option value="${ depts.id }" ${ depts.id eq emp.department.id ? 'selected' : '' }>${ depts.departmentName }</option>
						</c:forEach>
					</select>
				</td>
			</tr>
			<tr>
				<td><input type="submit" value="UPDATE"/></td>
			</tr>
		</table>
	</form>	
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值