Table of contents
SpringMVC processes response _context domain setting data
SpringMVC processing response_request forwarding & redirection
Common annotations of SpringMVC:
SpringMVC annotation_@RequestParam
SpringMVC注解_@RequestHeader、@CookieValue
SpringMVC annotation_@SessionAttributes
SpringMVC annotation_@ModelAttribute
SpringMVC annotation_RESTful style support
SpringMVC handles response _context field setting data
The context scope means that it is valid throughout the application. Passing values to the context scope in SpringMVC can only be achieved using the ServletContext object. However, this object cannot be directly injected into the method parameters, and needs to be obtained through the HttpSession object.
1. Write the controller method
@RequestMapping("/c2/hello7") public String setContextModel(HttpSession session){ ServletContext servletContext = session.getServletContext(); servletContext.setAttribute("age",10); return "xiaotong"; }
2. Write jsp pages
<%@ page contentType="text/html;charset=UTF-8" language="java"%> <html> <head> <title>百战不败</title> </head> <body> <h1>你好!${requestScope.name}</h1> <h1>地址是!${sessionScope.address}</h1> <h1>年纪是!${applicationScope.age}</h1> </body> </html>
SpringMVC processing response_request forwarding & redirection
In the previous case, we found that the value in the request field can be passed to the jsp page, that is, the bottom layer of the view jumping to the view through the view parser is request forwarding.
If we do not want to use a view resolver when jumping, we can use native HttpServletRequest for request forwarding or HttpServletResponse for redirection:
@RequestMapping("/c2/hello8")
public void myForward1(HttpServletRequest request, HttpServletResponse response)
throws Exception{
request.setAttribute("name","辛苦学堂");
// 请求转发
// request.getRequestDispatcher("/c2/hello9").forward(request,response);
// 原生重定向
response.sendRedirect("/c2/hello9");
}
@RequestMapping("/c2/hello9")
public void myForward2(HttpServletRequest request){
System.out.println("hello");
System.out.println(request.getAttribute("name"));
}
SpringMVC also provides a simpler way of request forwarding and redirection:
@RequestMapping("/c2/hello10")
public String myForward3(HttpServletRequest request){
request.setAttribute("name","辛苦学堂");
// 请求转发
return "forward:/c2/hello9";
// 重定向
// return "redirect:/c2/hello9";
}
SpringMVC implements the functions of the controller through annotations. Next, we will study the common annotations of SpringMVC in detail:
Common annotations of SpringMVC:
SpringMVC annotation_@Controller
Function: Mark the controller and hand it over to the Spring container for management.
Location: Above Class
SpringMVC annotation_@RequestMapping
Role: Set the request path for the controller method
Position: Above a method or class. Used on a class, it means that all controller methods in the class use this address as the parent path.
Attributes:
1. value/path: request path
2. method: Specify the request method
3. params: specifies the request parameters that must be sent
4. headers: Specify the request headers that the request must contain
@Controller
@RequestMapping("/c3")
public class MyController3 {
/*
访问路径为 /c3/annotation1
支持post和get请求
请求时必须带有age参数
请求时必须带有User-agent请求头
*/
@RequestMapping(path = "/annotation1",method =
{RequestMethod.GET,RequestMethod.POST},params = {"age"},headers = {"User-agent"})
public String annotation1(String username){
System.out.println(username);
return "xiaotong";
}
}
SpringMVC annotation_@RequestParam
Role: Get request parameters in the controller method
Position: Before the method parameter
Attributes:
1. name: Specify the name of the request parameter
2. defaultValue: Set the default value for the parameter
3. required: Whether the setting is a parameter that must be passed in
/*
定义请求的参数名为username,默认值为sxt,不是必须的参数
*/
@RequestMapping("/annotation2")
public String annotation2(@RequestParam(name = "username",defaultValue = "txc",required =
false) String name){
System.out.println(name);
return "baizhan";
}
SpringMVC注解_@RequestHeader、@CookieValue
@RequestHeader
Role: Get the request header data in the controller method
Position: Before the method parameter
@CookieValue
Role: Get Cookie data in the controller method
Position: Before the method parameter
/*
获取User-Agent请求头
获取JSESSIONID的Cookie值
*/
@RequestMapping("/annotation3")
public String annotation3(@RequestHeader("User-Agent")
String userAgent, @CookieValue("JSESSIONID") String jSessionId){
System.out.println(userAgent);
System.out.println(jSessionId);
return "xiaotong";
}
SpringMVC annotation_@SessionAttributes
Function: store the data in the Model model in the session domain
Location: Above Class
@Controller @RequestMapping("/c4") // 将模型中的name数据保存到session中 @SessionAttributes("name") public class MyController4 { @RequestMapping("/t1") public String t1(Model model){ // model中保存name数据 model.addAttribute("name","北京大乱斗"); return "xiaotong"; } @RequestMapping("/t2") public String t2(HttpSession session){ // 从session中获取name数据 System.out.println(session.getAttribute("name")); return "xiaotong"; } }
SpringMVC annotation_@ModelAttribute
Function 1: Set the specified method to be executed before other methods of the controller
Position: above the method
@Controller @RequestMapping("/c5") public class MyController5 { @ModelAttribute public void before(){ System.out.println("前置方法"); } @RequestMapping("/t1") public String t1(){ System.out.println("t1"); return "baizhan"; } }
Function 2: Obtain data from the Model model and assign values to parameters
Position: Before the method parameter
@Controller @RequestMapping("/c6") public class MyController6 { // 前置方法向Model中设置数据 @ModelAttribute public void before(Model model){ model.addAttribute("name","辛苦学堂"); } // 该参数不是从请求中获取,而是从Model中获取 @RequestMapping("/t1") public String t1(@ModelAttribute("name") String name){ System.out.println(name); return "xiaotong"; } }
SpringMVC annotation_RESTful style support
Introduction to RESTful style
RESTful style is a design style of URL path. In the RESTful URL path, any data on the network can be regarded as a resource, which can be a piece of text, a picture, or a Java object. And each resource will occupy a network path, no matter whether the resource is added, deleted, modified or checked, the access path is the same.
Traditional URL:
Find the student with id 1: http://localhost:8080/student/findById?id=30
Delete the student whose id is 1: http://localhost:8080/student/deleteById?id=30
RESTful style URL:
Find the student whose id is 30: http://localhost:8080/student/30
Delete the student whose id is 30: http://localhost:8080/student/30
So how to distinguish which kind of operation is the resource? According to different request methods, it is judged what operation is being performed.
We have learned two request methods before, GET request and POST request, and there are four request methods for accessing RESTful style URLs:
1. GET request: query operation
2. POST request: add operation
3. DELETE request: delete operation
4. PUT request: modify operation
RESTful style URL:
Find the student whose id is 30: http://localhost:8080/student/30 GET method request
Delete the student whose id is 30: http://localhost:8080/student/30 DELETE request
Advantages of RESTful style:
The structure is clear, standard-compliant, easy to understand, and easy to expand.