Common annotations and usage in SpringMVC

Table of contents

What is Spring MVC?

Introduction to MVC

Common annotations in SpringMVC

@RequestMapping

Specify GET/POST method type

@GetMapping and PostMapping

Get parameters

Pass a single parameter

Pass object

​Edit passing multiple parameters

Backend parameter renaming

​Edit @RequestParam

@RequestBody receives JSON object

Get the parameter @PathVariable in the URL

Upload file @RequestPart

Several ways to obtain the project directory:

Get Cookie/Session/header

Get Cookie @CookieValue

GetHeader @RequestHeader

Session storage and retrieval


What is Spring MVC?

Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring framework from the beginning. The official name "Spring Web MVC" comes from the name of its source module (spring-webmvc), but the more common name is "Spring MVC".

From the above definition we can derive two key messages:

1. Spring MVC is a web framework.

2. Spring MVC is built based on Servlet API.

Introduction to MVC

SpringMVC is a Java-based request-driven lightweight Web framework that implements the MVC design model. It is a follow-up product of Spring FrameWork and has been integrated into Spring Web Flow. The Spring framework provides full-featured MVC modules for building web applications. Using Spring's pluggable MVC architecture, when using Spring for WEB development, you can choose to use Spring's Spring MVC framework or integrate other MVC development frameworks.

SpringMVC has become one of the most mainstream MVC frameworks, and with the release of Spring 3.0, it has become the best MVC framework.


Common annotations in SpringMVC

@RequestMapping

@RequestMapping is one of the most commonly used annotations in Spring web applications. It is used to register the route mapping of the interface.

Route mapping: The so-called route mapping means that when a user accesses a URL, the process of mapping the user's request to a method of a certain class in the program is called route mapping.

Basic usage of @RequestMapping:

@Controller
@RequestMapping("/p")
public class PersonController { 
    @RequestMapping("/index")
    public Object index(Person person) {
        // 获取参数
        System.out.println(person.getName() + ":" +
                person.getPassword());
        return "/index.html";
    }
}

 @RequestMapping can modify classes or methods. When modifying classes and methods, the accessed address is class + method. @RequestMapping can also directly modify the method. The code implementation is as follows:

@Controller
@ResponseBody // 定义返回的数据格式为⾮视图(text/html)
public class UserController {
       @RequestMapping("/hi")
       public String sayHi(){
              return "<h1>Hi,Spring MVC.</h1>";
       }
}

Specify GET/POST method type

We can explicitly specify @RequestMapping to receive POST, as shown below:

@Controller
@ResponseBody // 定义返回的数据格式为⾮⻚⾯
public class UserController {
        @RequestMapping(value = "/hi",method= RequestMethod.POST)
        public String sayHi(){
              return "<h1>Hi,Spring MVC.</h1>";
        }
}

@GetMapping and PostMapping

Three ways to write get requests:

// 写法1

@RequestMapping("/index")

// 写法2

@RequestMapping(value = "/index",method = RequestMethod.GET)

// 写法3

@GetMapping("/index")

There are two ways to write post requests:

// 写法1
@RequestMapping(value = "/index",method = RequestMethod.POST)
// 写法2
@PostMapping("/index")

Get parameters

Pass a single parameter

In Spring MVC, you can directly use the parameters in the method to pass parameters, such as the following code:

@Controller
@ResponseBody // 定义返回的数据格式为⾮⻚⾯
public class UserController {

        @RequestMapping("/name")
        public Object method_1(String name){
            System.out.println("参数 name:"+name);
            return name;
        }
}

Results accessed in a browser:

The results obtained in idea:

Pass object

And Spring MVC can automatically implement the assignment of parameter objects, such as Person objects:

import lombok.Data;

@Data
public class Person {
    private String name;
    private String password;

}

Pass object code implementation:

@RequestMapping("/person")
public Object method_2(Person p){
       System.out.println("对象中的 name:"+p.getName());
       System.out.println("对象中的 password:"+p.getPassword());
       return p.getName()+":"+p.getPassword();
}

Results accessed in a browser:

The results obtained in idea:

Pass multiple parameters

@RequestMapping("/many")
        public Object method_3(String name, String pwd) {
            System.out.println("name 参数:" + name);
            System.out.println("pwd 参数:" + pwd);
            return name+" "+pwd;
        }

Results accessed in a browser:

When there are multiple parameters, when the front-end and back-end match parameters, they match by the name of the parameter. Therefore, the position of the parameter does not affect the result of the back-end obtaining the parameter. 

Backend parameter renaming

In some special cases, the parameter key passed by the front end may be inconsistent with the key received by our back end. For example, the front end passes a time to the back end, and the back end has a createtime field to receive it, so this will occur. If the parameters cannot be received, if this happens, we can use @RequestParam to rename the parameter values ​​of the front and back ends.

Backend implementation code:

@RequestMapping("/createtime")
public Object method_4(@RequestParam("time") String createtime) {
      System.out.println("时间:" + createtime);
      return createtime;
}

Front-end access results:

 @RequestParam

In the above example, if we pass a non-time parameter to the front end, the program will report an error, as shown in the following figure:

This is because the backend has declared that the frontend must pass a time parameter, but the frontend does not pass it to the backend. We can find out the clues by looking at the implementation details of the @RequestParam annotation. The annotation is implemented as follows:

required: means necessary. The default is true. If no parameters are passed, an error will be reported.

We can avoid reporting an error without passing it by setting required=false in @RequestParam. The specific implementation is as follows:

@RequestMapping("/createtime")
public Object method_4(@RequestParam(value = "time",required = false) String createtime) {
       System.out.println("时间:" + createtime);
       return createtime;
}

@RequestBody receives JSON object

Backend code:

@RequestMapping(value = "/m5", method = RequestMethod.POST)
public Object method_5(@RequestBody Person person) {
       System.out.println("Person:" + person);
       return true;
}

Here, postman is used to construct a json request:

Get the parameter @PathVariable in the URL

Backend code:

@PostMapping("/m6/{name}/{password}")
public Object method_6(@PathVariable String name, @PathVariable String password) {
       System.out.println("name:" + name);
       System.out.println("password:" + password);
       return true;
}

 Front-end method address:

Note: {name} and {password} are indispensable.

Upload file @RequestPart

@RequestMapping("/param")
public String param(String name, @RequestPart("myfile") MultipartFile file) throws IOException {
            // 获取⽂件后缀名
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // ⽂件保存地址
        String filePath = ClassUtils.getDefaultClassLoader().getResource("static").getPath() +
                    "/" + UUID.randomUUID() + fileName;
            // 保存⽂件
        file.transferTo(new File(filePath));
        return filePath + " 上传成功.";
}

Several ways to obtain the project directory:

ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).getPath();
new ClassPathResource("").getFile().getAbsolutePath();
ClassUtils.getDefaultClassLoader().getResource("").getPath();
ResourceUtils.getFile("classpath:static/").getPath();

Get Cookie/Session/header

Get Cookie @CookieValue

@RequestMapping("/cookie")
@ResponseBody
public String cookie(@CookieValue("bite") String bite) {
       return "cookie:" + bite;
}

GetHeader @RequestHeader

@RequestMapping("/header")
@ResponseBody
public String header(@RequestHeader("User-Agent") String userAgent) {
     return "userAgent:"+userAgent;
}

Session storage and retrieval

Session storage is similar to Servlet and is obtained using HttpServletRequest, as shown in the following code:

@RequestMapping("/setsess")
@ResponseBody
public String setsess(HttpServletRequest request) {
        // 获取 HttpSession 对象,参数设置为 true 表示如果没有 session 对象就创建⼀个session
        HttpSession session = request.getSession(true);
        if(session!=null){
            session.setAttribute("username","java");
        }
        return "session 存储成功";
}

You can use HttpServletRequest to read the Session, as shown in the following code:

@RequestMapping("/sess")
@ResponseBody
public String sess(HttpServletRequest request) {
        // 如果 session 不存在,不会⾃动创建
        HttpSession session = request.getSession(false);
        String username = "暂⽆";
        if(session!=null && session.getAttribute("username")!=null){
            username = (String) session.getAttribute("username");
        }
        return "username:"+username;
}

A simpler way to get the Session:

@RequestMapping("/sess2")
@ResponseBody
public String sess2(@SessionAttribute(value = "username",required = false) String username{
     return "username:"+username;
}

Guess you like

Origin blog.csdn.net/m0_62468521/article/details/131348464