Spring MVC self study log 04 (Controller and RestFul style)

Keywords: Spring JSP Java

Controller

  1. Controller complex provides the behavior of accessing application program, which is usually realized by two methods of interface definition or annotation definition.
  2. The controller is responsible for parsing the user's request and converting it into a model.
  3. In Spring MVC, a controller class can contain multiple methods in
  4. In Spring MVC, there are many ways to configure the Controller

Implement Controller interface

Controller is an interface. Under the org.springframework.web.servlet.mvc package, there is only one method in the interface;

//Implement the class of the interface to obtain the controller function
public interface Controller {
    //Process the request and return a model and view object
    ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
  1. Write a Controller class, ControllerTest1
//Define controller
//Note: do not import the wrong package, implement the Controller interface and rewrite the method;
public class ControllerTest1 implements Controller {

    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //Returns a model view object
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","Test1Controller");
        mv.setViewName("test");
        return mv;
    }
}
  1. After writing, go to the Spring configuration file to register the requested bean; name corresponds to the request path, and class corresponds to the request class
<bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
  1. Write the front-end test.jsp in the WEB-INF/jsp directory, corresponding to our view parser
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Kuangshen</title>
</head>
<body>
    ${msg}
</body>
</html>
  1. test
  2. Explain
    The disadvantage of the old method is that there is only one method in a Controller, if there are more than one methods, you need to define more than one Controller; the way of defining is more cumbersome

So use the annotation @ Controller

  1. @The Controller annotation type is used to declare that the instance of Spring class is a Controller (another three annotations are mentioned when talking about IOC);
  2. Spring can use the scanning mechanism to find all annotation based controller classes in the application. To ensure spring can find your controller, you need to declare component scanning in the configuration file.
<! -- automatically scan the specified package, and submit all the following annotation classes to IOC container management -- >
<context:component-scan base-package="com.kuang.controller"/>
  1. Add a ControllerTest2 class, which is implemented by annotation;
//@The class annotated by the Controller will be automatically added to the Spring context, and all the methods in the class will be added,
//If the return value is Spring and a specific page can jump, it will be parsed by the view parser
@Controller
public class ControllerTest2{

    //Map access path
    @RequestMapping("/t2")
    public String index(Model model){
        //Spring MVC will automatically instantiate a Model object to pass values to the view
        model.addAttribute("msg", "ControllerTest2");
        //Return to view location
        return "test";
    }

}
  1. test
  2. Note: it can be found that both our requests can point to a view, but the result of the page result is different. From this, we can see that the view is reused, and the relationship between the controller and the view is weak coupling.

RequestMapping

  1. @The RequestMapping annotation is used to map a url to a controller class or to a specific handler method. Can be used on a class or method.
  2. On a class, the address is used as the parent path for all methods in the class that respond to requests.
  3. Comment on method only
//Access path: http://localhost:8080/h1
@Controller
public class TestController {
    @RequestMapping("/h1")
    public String test(){
        return "test";
    }
}
  1. Annotate classes and methods at the same time
//Access path: http://localhost:8080/admin/h1, you need to specify the path of the class first and then the path of the method;
@Controller
@RequestMapping("/admin")
public class TestController {
    @RequestMapping("/h1")
    public String test(){
        return "test";
    }
}

RestFul style

Restful is a style of resource location and resource operation. It's not a standard or an agreement, it's just a style. The software designed based on this style can be more concise, more hierarchical, and easier to implement mechanisms such as caching.

function

  1. Resources: everything on the Internet can be abstracted
  2. Operation for resource: use POST, DELETE, PUT and GET to operate the resource with different methods.
  3. Add, delete, modify and query respectively.

Learning test

  1. Create a new class RestFulController
@Controller
public class RestFulController {
}
  1. In Spring MVC, you can use @ PathVariable annotation to bind the value of method parameter to a URI template variable.
@Controller
public class RestFulController {

    //Map access path
    @RequestMapping("/commit/{p1}/{p2}")
    public String index(@PathVariable int p1, @PathVariable int p2, Model model){
        
        int result = p1+p2;
        //Spring MVC will automatically instantiate a Model object to pass values to the view
        model.addAttribute("msg", "Result:"+result);
        //Return to view location
        return "test";
        
    }
    
}

Let's test the request

Thinking: what are the benefits of using path variables?

  1. Make the path more concise;
  2. It's more convenient to get parameters, and the framework will automatically perform type conversion.
  3. Access parameters can be constrained by the type of path variable. If the types are different, the corresponding request method cannot be accessed. For example, if the access path is / commit/1/a, the path does not match the method, and the parameter conversion will not fail.
  4. Let's modify the corresponding parameter type and test again
//Map access path
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable String p2, Model model){

    String result = p1+p2;
    //Spring MVC will automatically instantiate a Model object to pass values to the view
    model.addAttribute("msg", "Result:"+result);
    //Return to view location
    return "test";
}

Use the method property to specify the request type

The type used to constrain the request, which can be narrowed down. Specify the type of request predicate, such as GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE, etc

  1. Add a method
//Map access path, must be POST request
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String index2(Model model){
    model.addAttribute("msg", "hello!");
    return "test";
}
  1. We use the browser address bar to access. The default is Get request, and an error of 405 will be reported:
  2. If you change POST to GET, it is normal;
//Map access path, must be Get request
@RequestMapping(value = "/hello",method = {RequestMethod.GET})
public String index2(Model model){
    model.addAttribute("msg", "hello!");
    return "test";
}

Summary

Spring MVC's @ RequestMapping annotation can handle HTTP request methods, such as GET, PUT, POST, DELETE and PATCH. All address bar requests will be of the HTTP GET type by default.

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

@GetMapping is a composite annotation that acts as a shortcut to @ RequestMapping(method =RequestMethod.GET). Usually use more!

Published 21 original articles, praised 0, visited 220
Private letter follow

Posted by googlehunter on Wed, 29 Jan 2020 19:19:03 -0800