首页 > 学院 > 开发设计 > 正文

springmvc之Restful

2019-11-06 07:33:32
字体:
来源:转载
供稿:网友

1.什么是Restful

Rest的意思就是表述性状态转移。理解就是表示被为操作资源。其实也是一种基于http结构的东西。然后应该知道这不是一种定义的规范也不是什么标准。就是一种用来表示数据以及操作服务器中资源的方法。但是Rest web的服务却又依赖于Http协议。

2.Restful风格的增删改查策略

(1)GET方法通常用来获取某一资源或者资源集合。

(2)POST方法用于创建。

(3)PUT方法用于更新。

(4)DELETE方法用于从系统中删除资源。

3.sPRingmvc实现Restful风格

(1)准备工作

工程目录:

导包:

编写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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 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">  <display-name>springmvc_restful</display-name> <!--配置HiddenHttpMethodFilter-->  <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>    <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>  <servlet-mapping>    <servlet-name>springDispatcherServlet</servlet-name>    <url-pattern>/</url-pattern>  </servlet-mapping></web-app>

entity模型:

Department:

public class Department {	private Integer id;	private String departmentName;	public Department() {		// TODO Auto-generated constructor stub	}		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:

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;	}	@Override	public String toString() {		return "Employee [id=" + id + ", lastName=" + lastName + ", email="				+ email + ", gender=" + gender + ", department=" + department				+ "]";	}	public Employee() {		// TODO Auto-generated constructor stub	}}

dao层:

DepartmentDao:

@Repositorypublic 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:

@Repositorypublic 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, "张三", "aa@QQ.com", 1, new Department(101, "人事部")));		employees.put(1002, new Employee(1002, "李四", "bb@qq.com", 1, new Department(102, "财务部")));		employees.put(1003, new Employee(1003, "王五", "cc@qq.com", 0, new Department(103, "研发部")));		employees.put(1004, new Employee(1004, "赵六", "dd@qq.com", 0, new Department(104, "研发部")));		employees.put(1005, new Employee(1005, "田七", "ee@qq.com", 1, new Department(105, "人事部")));	}		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);	}}

(2)使用GET方法来查询

编写Controller:

@RequestMapping("/employeeController")@Controllerpublic class EmployeeController {		@Autowired	private EmployeeDao employeeDao;	@RequestMapping("/showList")	public String showList(Map<String,Object> map){		map.put("employees", employeeDao.getAll());		return "list";	}}编写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></head><body>	<a href="employeeController/showList">Show List</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 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>	<c:if test="${empty requestScope.employees }">没有任何员工信息</c:if>	<c:if test="${!empty requestScope.employees }">		<table border="1" cellpadding="10" cellspacing="0">			<tr>				<th>编号</th>					<th>姓名</th>					<th>邮箱</th>					<th>性别</th>					<th>部门</th>					<th>Edit</th>				<th>Delete</th>						</tr>	</c:if>		<c:forEach items="${requestScope.employees }" 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="">Edit</a></td>				<td><a href="">Delete</a></td>			</tr>	</c:forEach>	</table></body></html>结果:

使用fiddler抓包结果:可以发现使用的是GET请求。

(3)使用POST方法来增加

在EmployeeController控制器中编写一个添加员工和保存员工的方法。

        @RequestMapping(value="/addEmp",method=RequestMethod.GET)	public String addEmp(Map<String,Object> map){		map.put("departments", departmentDao.getDepartments());		map.put("employee", new Employee());		return "input";	}		@RequestMapping(value="/saveEmp",method=RequestMethod.POST)	public String saveEmp(Employee employee){		employeeDao.save(employee);		return "redirect:/employeeController/showList";	}编写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><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>list</title></head><body>	<c:if test="${empty requestScope.employees }">没有任何员工信息</c:if>	<c:if test="${!empty requestScope.employees }">		<table border="1" cellpadding="10" cellspacing="0">			<tr>				<th>编号</th>					<th>姓名</th>					<th>邮箱</th>					<th>性别</th>					<th>部门</th>					<th>编辑</th>				<th>删除</th>				<th><a href="addEmp">添加员工</a></th>						</tr>	</c:if>		<c:forEach items="${requestScope.employees }" 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="">Edit</a></td>				<td><a href="">Delete</a></td>			</tr>	</c:forEach>	</table></body></html>在input.jsp页面编写添加员工的表单:使用springmvc的标签

<%@ 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>input</title></head><body>	<form:form action="saveEmp" method="post" modelAttribute="employee">		姓名:<form:input path="lastName"/><br/>		邮箱:<form:input path="email"/><br/>		性别:<form:radiobutton path="gender" label="男" value="1"/>		<form:radiobutton path="gender" label="女" value="0"/><br/>		部门:<form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id">			</form:select><br/>		<input type="submit" value="提交"/>	</form:form></body></html>结果:

fiddler抓包结果:

(4)使用DELETE方法来删除

实际上使用DELETE方法来删除也是基于POST请求。

编写控制器:

@RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)	public String deleteEmp(@PathVariable("id") Integer id){		employeeDao.delete(id);		return "redirect:/showList";	}导入jquery-1.9.1.min.js文件,由于我们稍后要使用jquery来发送post请求。

编写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><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>list</title><script type="text/Javascript" src="scripts/jquery-1.9.1.min.js"></script><script type="text/javascript">	$(function(){		$(".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>				<th>编号</th>					<th>姓名</th>					<th>邮箱</th>					<th>性别</th>					<th>部门</th>					<th>编辑</th>				<th>删除</th>				<th><a href="addEmp">添加员工</a></th>						</tr>	</c:if>		<c:forEach items="${requestScope.employees }" 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="">修改</a></td>				<td><a href="delete/${emp.id}" class="delete">删除</a></td>			</tr>	</c:forEach>	</table></body></html>解释:由于我们需要使用超链接来发送请求,但是超链接只能发送GET请求,如果想要用超链接发送post请求,就需要使用jquery脚本来发送。

问题1:为什么springmvc加载不了静态资源,就是为什么页面用不了jquery?虽然我们配置了DispatcherServlet中/方式来接收所有请求,但是restful风格却将他们当成普通请求(静态资源等)。实际上就是没有对应的解析器去解析这些资源。

解决方式:在springmvc.xml中采用<mvc:default-servlet-handler/>配置。

将在 SpringMVC 上下文中定义一个DefaultServletHttpRequestHandler,它会对进入 DispatcherServlet 的请求进行筛查, 如果发现是没有经过映射的请求, 就将该请求交由 WEB 应用服务器默认的 Servlet 处理.。如果不是静态资源的请求,才由DispatcherServlet继续处理。一般 WEB 应用服务器默认的 Servlet 的名称都是 default。若所使用的 WEB 服务器的默认 Servlet 名称不是 default,则需要通过 default-servlet-name 属性显式指定。

问题2:使用了<mvc:default-servlet-handler/>标签,却使得注解@RequestMapping失效

解决方式:在springmvc.xml中采用<mvc:annotation-driven></mvc:annotation-driven>配置。

结果:赵六被删除

fiddler抓包结果:

问题3:为什么这次没有使用在Controller控制器上写@RequestMapping路径呢?解决方式:由于在Controller上添加了@RequestMapping请求类路径,则导致在使用jquery-1.9.1.min.js脚本文件时,springmvc自动就给添加了类路径,导致使用jquery文件失败。所以不采用类路径了。

(5)使用PUT方法来修改

虽然使用PUT方法来修改,但是实际上还是使用POST请求。

编写请求页面list.jsp:

<td><a href="editEmp/${emp.id}">修改</a></td>编写接收修改超链接的方法

@RequestMapping(value="/editEmp/{id}",method=RequestMethod.GET)public String editEmp(@PathVariable("id") Integer id,Map<String,Object> map){	map.put("employee", employeeDao.get(id));	map.put("departments", departmentDao.getDepartments());	return "/input";}编写修改页面input.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%@ 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><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>input</title></head><body>	<form:form action="${pageContext.request.contextPath }/saveEmp" method="POST" modelAttribute="employee">		<c:if test="${employee.id ==null }">			姓名:<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>		邮箱:<form:input path="email"/><br/>		性别:<form:radiobutton path="gender" label="男" value="1"/>		<form:radiobutton path="gender" label="女" value="0"/><br/>		部门:<form:select path="department.id" items="${departments }" itemLabel="departmentName" itemValue="id">			</form:select><br/>		<input type="submit" value="提交"/>	</form:form></body></html>编写接收修改页面提交数据的方法:

@ModelAttributepublic void getEmp(@RequestParam(value="id",required=false) Integer id,Map<String,Object> map){	if(id !=null){		map.put("employee", employeeDao.get(id));	}}	@RequestMapping(value="/saveEmp",method=RequestMethod.PUT)public String updateEmp(Employee employee){	employeeDao.save(employee);	return "redirect:/showList";}至于为什么使用@ModelAttribute注解:

http://blog.csdn.net/ya_1249463314/article/details/56681459#t1

回显页面还是之前的list.jsp文件。

结果:

-------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------

使用fiddler抓包:


上一篇:关于堆的判断 (25分)

下一篇:LeeeCode 412

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表