Controller
- Controller complex provides the behavior of accessing application program, which is usually realized by two methods of interface definition or annotation definition.
- The controller is responsible for parsing the user's request and converting it into a model.
- In Spring MVC, a controller class can contain multiple methods in
- 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; }
- 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; } }
- 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"/>
- 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>
- test
- 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
- @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);
- 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"/>
- 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"; } }
- test
- 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
- @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.
- On a class, the address is used as the parent path for all methods in the class that respond to requests.
- Comment on method only
//Access path: http://localhost:8080/h1 @Controller public class TestController { @RequestMapping("/h1") public String test(){ return "test"; } }
- 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
- Resources: everything on the Internet can be abstracted
- Operation for resource: use POST, DELETE, PUT and GET to operate the resource with different methods.
- Add, delete, modify and query respectively.
Learning test
- Create a new class RestFulController
@Controller public class RestFulController { }
- 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?
- Make the path more concise;
- It's more convenient to get parameters, and the framework will automatically perform type conversion.
- 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.
- 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
- 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"; }
- We use the browser address bar to access. The default is Get request, and an error of 405 will be reported:
- 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!