Chapter 6 RESTful of SpringMVC

1. RESTful

1. Introduction to RESTful

REST: Representational State Transfer, presentation layer resource state transfer

①Resources

Think of a server as consisting of many discrete resources. Each resource is a nameable abstraction on the server

②Representation of resources

The representation of the source can have multiple formats, such as HTML/XML/JSON/plain text/picture/video/audio

③State transition

State transfer refers to the transfer (transfer) between the client and the server to represent the representation of the state of the resource. Through the expression of transferring and operating resources, the purpose of operating resources is indirectly realized.

2. Implementation of RESTful

①In the HTTP protocol, there are four verbs indicating the operation mode: GET, POST, PUT, DELETE

②Corresponding to four basic operations: GET is used to obtain resources, POST is used to create new resources, PUT is used to update resources, and DELETE is used to delete resources

③The REST style advocates the use of a unified style design for URL addresses, using / instead of question marks to ensure the consistency of the style.

 

 3. Use RESTful simulation to operate user resources

①UserController controller

@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 page

 4. HiddenHttpMethodFilter

  • Since browsers only support get and post requests, sending put and delete requests requires SpringMVC to provide HiddenHttpMethodFilter
  • HiddenHttpMethodFilter handles the conditions for put and delete requests:
    • a> The request method of the current request must be post
    • b>The current request must transmit the request parameter _method

  • If the above conditions are met, the HiddenHttpMethodFilter filter will convert the request method of the current request into the value of the request parameter _method, so the value of the request parameter _method is the final request method

①In web.xml, configure the filter

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

【Notice】

① SpringMVC provides two filters: CharacterEncodingFilter and HiddenHttpMethodFilter

② When registering in web.xml, you must first register CharacterEncodingFilter, and then register HiddenHttpMethodFilter

③The reason is: the request.setCharacterEncoding(encoding) method of setting the character set through the request.setCharacterEncoding(encoding) method in the CharacterEncodingFilter requires that there should not be any previous operation to obtain the request parameters. And HiddenHttpMethodFilter just has an operation to get the request method.

 5. Simulate PUT and DELETE requests

Simulate PUT to modify user information

①html page (the form must be POST, there is a _method method, and the value is PUT)

②Controller

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

2. Specific cases of RESTful

1. Preparations

 ①Create Employee's javaBean under the bean package

② Create EmployeeDao.class in the dao package

	@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);
   }
}

Because the annotation @Repository is added to start scanning in dao

 ② Create a controller under the controller package

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

③Index.html page

2. Query all employee information

① Write under the controller

@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 page display

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

Effect

 3. Delete employee information by id

①In the employee_list.html page, add a delete link. Pay special attention to th:action="@{/employee/} +${employee.id} "

 ②Click the delete button. Under the EmployeeController controller, get the id value of the placeholder through @PathVariable("id"). Redirect to listing page

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

4. Add employee information

 ①Click the Add button

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

Forward to add page 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>

②Execute the add operation in the controller method, and use Employee employee to save the request data. The premise is that the name of the form form must be consistent with the name of the class attribute

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

5. Modify employee information

①Click the Modify button on the employee_list.html page

 ② Execute the controller method EmployeeController, query the object to be modified according to the id, and save it in the Model domain. The request is forwarded to 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";
}

③On the employee_update.html page, read the domain object. The PUT method under the Post request. Add the id hidden field, and the request is forwarded to the controller

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

④Under the EmployeeController controller. Execute employeeDao.save(employee); to implement modification.

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

Guess you like

Origin blog.csdn.net/jbkjhji/article/details/131067112