第6章SpringMVC的RESTful

一、RESTful

1.RESTful简介

REST:Representational State Transfer,表现层资源状态转移

①资源

将服务器看作是由很多离散的资源组成。每个资源是服务器上一个可命名的抽象概念

②资源的表述

源的表述可以有多种格式,例如HTML/XML/JSON/纯文本/图片/视频/音频

③状态转移

状态转移说的是:在客户端和服务器端之间转移(transfer)代表资源状态的表述。通过转移和操作资源的表述,来间接实现操作资源的目的。

2.RESTful的实现

①HTTP协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE

②对应四种基本操作:GET用来获取资源、POST用来新建资源、PUT用来更新资源、DELETE用来删除资源

③REST风格提倡URL地址使用统一的风格设计,都使用/,不使用问号,保证风格的一致性。

 

 3.使用RESTful模拟操作用户资源

①UserController控制器

@Controller
public class UserController {
   @RequestMapping(value = "/user",method = RequestMethod.GET)
   public String getAllUser(){
      System.out.println("查询用户信息");
      return "success";
   }

   @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
   public String getOneUser(){
      System.out.println("查询id用户信息");
      return "success";
   }

   @RequestMapping(value = "/user",method = RequestMethod.POST)
   public String insertUser(String username,String password){
      System.out.println("增加用户信息,用户名:"+username+"密码是:"+password);
      return "success";
   }
}

②test_rest.html页面

 4. HiddenHttpMethodFilter

  • 由于浏览器只支持get和post方式请求,发送put和delete请求需要使用SpringMVC 提供了 HiddenHttpMethodFilter
  • HiddenHttpMethodFilter 处理put和delete请求的条件:
    • a>当前请求的请求方式必须为post
    • b>当前请求必须传输请求参数_method

  • 满足以上条件,HiddenHttpMethodFilter 过滤器就会将当前请求的请求方式转换为请求参数_method的值,因此请求参数_method的值才是最终的请求方式

①在web.xml,配置过滤器

<!--配置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>

【注意】

①SpringMVC中提供了两个过滤器:CharacterEncodingFilter和HiddenHttpMethodFilter

②在web.xml中注册时,必须先注册CharacterEncodingFilter,再注册HiddenHttpMethodFilter

③原因是:在 CharacterEncodingFilter 中通过 request.setCharacterEncoding(encoding) 方法设置字符集的request.setCharacterEncoding(encoding) 方法要求前面不能有任何获取请求参数的操作。而 HiddenHttpMethodFilter 恰恰有一个获取请求方式的操作。

 5.模拟PUT和DELETE请求

模拟PUT修改用户信息

①html页面(表单必须是POST,有一个_method方法,值是PUT)

②控制器

@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String updateUser(String username,String password){
   System.out.println("修改用户信息,用户名:"+username+password);
   return "success";
}

二、RESTful具体案例

1.准备工作

 ①在bean包下创建Employee的javaBean

② 在dao包创建EmployeeDao.class

	@Repository
public class EmployeeDao {
   private static Map<Integer, Employee> employees = null;

   static {
      employees = new HashMap<Integer,Employee>();
      employees.put(1001, new Employee(1001, "E-AA", "[email protected]", 1));
      employees.put(1002, new Employee(1002, "E-BB", "[email protected]", 1));
      employees.put(1003, new Employee(1003, "E-CC", "[email protected]", 0));
      employees.put(1004, new Employee(1004, "E-DD", "[email protected]", 0));
      employees.put(1005, new Employee(1005, "E-EE", "[email protected]", 1));
   }

   private static Integer initId = 1006;

   public void save(Employee employee){
      if (employee.getId() == null){
         employee.setId(initId++);
      }
      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);
   }
}

因为加了注解@Repository在dao开启扫描

 ②在controller包下创建控制器

@Controller
public class EmployeeController {
   @Autowired
   private EmployeeDao employeeDao;
   @RequestMapping("/")
   public String index() {
      return "index";
   }
}

③Index.html页面

2.查询所有员工信息

①在控制器下编写

@RequestMapping(value = "/employee",method = RequestMethod.GET)
public String getEmployeeList(Model model) {
   Collection<Employee> allemployee = employeeDao.getAll();
   model.addAttribute("employeeList",allemployee);
   return "employee_list";
}

 ②employee_list.html页面展示

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>所有员工信息</title>
</head>
<body>
<table border="1" cellpadding="0" cellspacing="0" style="text-align: center;" id="dataTable">
    <tr>
        <th colspan="5">Employee Info</th>
    </tr>
    <tr>
        <th>id</th>
        <th>lastName</th>
        <th>email</th>
        <th>gender</th>
        <th>options</th>
    </tr>

    <tr th:each="employee:${employeeList}">
        <td th:text="${employee.id}"></td>
        <td th:text="${employee.lastName}"></td>
        <td th:text="${employee.email}"></td>
        <td th:text="${employee.gender}"></td>
        <td>
            <a href="">delete</a>
            <a href="">update</a>
        </td>
    </tr>

</table>
</body>
</html>

效果

 3.按id删除员工信息

①在employee_list.html页面,添加删除链接。特别注意th:action="@{/employee/}+${employee.id}"

 ②点击删除按钮。在EmployeeController控制器下,通过@PathVariable("id")获取占位符的id值。重定向到列表页面

@RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id){  //@PathVariable("id")获取占位符的值
   employeeDao.delete(id);
   return "redirect:/employee";
}

4.添加员工信息

 ①点击添加按钮

@RequestMapping("/toAdd")
public String retunAdd(){
   return "employee_add";
}

转发到添加页面employee_add.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form th:action="@{/employee}" method="post">
    用户名:<input type="text" name="lastName"> <br>
    邮箱:<input type="text" name="email"> <br>
    性别:<input type="radio" name="gender" value="1">男
    <input type="radio" name="gender" value="1">女<br>
    <input type="submit" value="提交">
</form>
</body>
</html>

②在控制器方法执行添加操作,采用Employee employee保存请求数据。前提是form表单的name要和类属性名一致

@RequestMapping(value = "/employee",method = RequestMethod.POST)
public String addEmp(Employee employee){
   employeeDao.save(employee);
   return "redirect:/employee";
}

5.修改员工信息

①employee_list.html页面点击修改按钮

 ②执行控制器方法EmployeeController,根据id查询到要修改的对象,把他保存到Model域中。请求转发到employee_update.html

@RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
public String updateHtml(@PathVariable("id") Integer id,Model model){
   Employee employee = employeeDao.get(id);
   model.addAttribute("employee",employee);
   return "employee_update.html";
}

③employee_update.html页面中,读取域对象。Post请求下的PUT方法。加上id隐藏域,请求转发到控制器

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form th:action="@{/employee}" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="hidden" name="id" th:value="${employee.id}">
    用户名:<input type="text" name="lastName" th:value="${employee.lastName}"> <br>
    邮箱:<input type="text" name="email"  th:value="${employee.email}"> <br>
    性别:<input type="radio" name="gender" value="1" th:field="${employee.gender}">男
    <input type="radio" name="gender" value="2" th:field="${employee.gender}">女<br>
    <input type="submit" value="提交">
</form>
</body>
</html>

④EmployeeController控制器下。执行employeeDao.save(employee);实现修改。

@RequestMapping(value = "/employee",method = RequestMethod.PUT)
public String updateEmp(Employee employee){
   employeeDao.save(employee);
   return "redirect:/employee";
}

猜你喜欢

转载自blog.csdn.net/jbkjhji/article/details/131067112