SpringMVC: RestFul style and controller usage

Controller

The controller provides complex behaviors to access the application program, which is usually implemented through two methods: interface definition or annotation definition .

The controller is responsible for parsing the user's request and transforming it into a model.

A controller class can contain multiple methods in Spring MVC

In Spring MVC, there are many ways to configure Controller

Implement the Controller interface

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

//实现该接口的类获得控制器功能
public interface Controller {
    
    
   //处理请求且返回一个模型与视图对象
   ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}

Write a Controller class, ControllerTest1

//定义控制器
//注意点:不要导错包,实现Controller接口,重写方法;
public class ControllerTest1 implements Controller {
    
    

   public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    
    
       //返回一个模型视图对象
       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 class that handles the request

<bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
编写前端test.jsp,注意在WEB-INF/jsp目录下编写,对应我们的视图解析器

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Kuangshen</title>
</head>
<body>
${msg}
</body>
</html>

Configure Tomcat to run the test. I don’t have a project release name. The configuration is a /, so the request does not need to add the project name, OK!

Description:

Implementing the interface Controller to define the controller is the older way

The disadvantage is: there is only one method in a controller, if you want multiple methods, you need to define multiple Controllers; the definition method is more troublesome;

Use annotation @Controller

The @Controller annotation type is used to declare that the instance of the Spring class is a controller (the other three annotations are mentioned when talking about IOC);

Spring can use the scanning mechanism to find all annotation-based controller classes in the application. In order to ensure that Spring can find your controller, you need to declare component scanning in the configuration file.

<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>

Add a ControllerTest2 class and implement it with annotations;

//@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2{
    
    

   //映射访问路径
   @RequestMapping("/t2")
   public String index(Model model){
    
    
       //Spring MVC会自动实例化一个Model对象用于向视图中传值
       model.addAttribute("msg", "ControllerTest2");
       //返回视图位置
       return "test";
  }

}

RequestMapping

The @RequestMapping annotation is used to map the url to a controller class or a specific handler method. Can be used on classes or methods. Used on classes, it means that all methods in the class that respond to requests use this address as the parent path.

In order to test the conclusions more accurately, we can add a project name to test myweb

Annotate only the method

@Controller
public class TestController {
    
    
   @RequestMapping("/h1")
   public String test(){
    
    
       return "test";
  }
}

Access path: http://localhost:8080/project name/h1

Annotate classes and methods at the same time

@Controller
@RequestMapping("/admin")
public class TestController {
    
    
   @RequestMapping("/h1")
   public String test(){
    
    
       return "test";
  }
}

Access path: http://localhost:8080 / project name/ admin /h1, you need to specify the path of the class and then the path of the method;

RestFul style

concept

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

Features

Resources: All things on the Internet can be abstracted as resources

Resource operations: use POST, DELETE, PUT, GET, and use different methods to operate on resources.

Respectively add, delete, modify, and query.

Operate resources in the traditional way: achieve different effects through different parameters! Single method, post and get

http://127.0.0.1/item/queryItem.action?id=1 查询,GET

http://127.0.0.1/item/saveItem.action 新增,POST

http://127.0.0.1/item/updateItem.action 更新,POST

http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST

Use RESTful operation resources: you can achieve different effects through different request methods! As follows: The request address is the same, but the function can be different!

http://127.0.0.1/item/1 查询,GET

http://127.0.0.1/item 新增,POST

http://127.0.0.1/item 更新,PUT

http://127.0.0.1/item/1 删除,DELETE

Case study

Create a new class RestFulController

@Controller
public class RestFulController {
    
    
}

You can use the @PathVariable annotation in Spring MVC to bind the value of the method parameter to a URI template variable.

@Controller
public class RestFulController {
    
    

   //映射访问路径
   @RequestMapping("/commit/{p1}/{p2}")
   public String index(@PathVariable int p1, @PathVariable int p2, Model model){
    
    
       
       int result = p1+p2;
       //Spring MVC会自动实例化一个Model对象用于向视图中传值
       model.addAttribute("msg", "结果:"+result);
       //返回视图位置
       return "test";
       
  }
   
}

What are the benefits of using path variables?

  1. Make the path more concise;

  2. Obtaining parameters is more convenient, and the framework will automatically perform type conversion.

  3. The access parameters can be restricted by the type of the 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 will not be the parameter Conversion failed.

Use the method attribute to specify the request type

Used to restrict the type of request, which can narrow the scope of the request. Specify the type of request predicate such as GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE, etc.

Let's test it:

Add a method

//映射访问路径,必须是POST请求
@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 Get request, and error 405 will be reported:

summary:

The @RequestMapping annotation of Spring MVC can handle HTTP request methods, such as GET, PUT, POST, DELETE and PATCH.

All address bar requests will be HTTP GET by default.

The method-level annotation variants are as follows: combined annotations

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping is a combination annotation, usually used more!

What it plays is a shortcut of @RequestMapping(method =RequestMethod.GET).

Guess you like

Origin blog.csdn.net/david2000999/article/details/115274295