Table of contents
Second, the return value of the controller method
2.2 The return value is String
2.3 The return value is ModelAndView
3. Some session objects set data
3.1 request domain setting data
3.1.1 Use parameters as native HttpServletRequest
3.1.2 Use parameters as Model and ModelMap
3.1.3 Use parameters as Map collection
3.2 session domain setting data
3.3 context domain setting data
4. Request Forwarding & Redirection
4.1 Native request forwarding and redirection writing
4.1.1 Redirecting controller methods
4.1.2 Redirection test results
4.1.3 Request to forward test results
4.2 Request forwarding and redirection provided by springmvc
Related readings of previous columns & articles
4. Spring MVC series of columns
1. Configure the view parser
By default, SpringMVC will jump to the view page after the controller is executed, and the view resolver can find the corresponding view. The previous 404 exception is that the view cannot be found because the view resolver is not configured. 13 view resolvers are provided in SpringMVC to support different view technologies. InternalResourceViewResolver is the default view resolver of SpringMVC, which is used to resolve JSP views.
Add the following tags to configure the view resolver
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图前缀 -->
<property name="prefix" value="/"/>
<!-- 视图后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
Second, the return value of the controller method
We can set the jump view through the return value of the controller method. The controller method supports the following return value types:
2.1 The return value is void
At this point, it will jump to the jsp page whose name is prefix + method path name + suffix
2.1.1 Controller methods
/**
* SpringMVC处理响应——控制器方法(根据返回值)
*/
// 路径是helloMVC,方法执行完后会跳转到/helloMVC.jsp
@RequestMapping("helloMVC")
public void helloMVC(){
System.out.println("hello SpringMVC!");
}
2.1.2 jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>MVC</title>
</head>
<body>
<h1>欢迎来到SpringMVC!</h1>
</body>
</html>
2.1.3 Test results
Access path: http://localhost:8080/helloMVC
OK, indeed the jsp page is returned
2.2 The return value is String
At this time, it will jump to the jsp page whose name is prefix + return value + suffix
2.2.1 Controller methods
// 返回值是String,此时会跳转到名字是 前缀+返回值+后缀 的jsp页面
@RequestMapping("c2/hello1")
public String helloMVC1(){
System.out.println("Hello SpringMVC!");
return "helloMVC";
}
2.2.2 Test results
Access path: http://localhost:8080/c2/hello1
OK, the helloMVC1 page is not returned this time, and it has indeed been successfully implemented.
2.3 The return value is ModelAndView
This is an object provided by SpringMVC, which can set data to the request field and specify the page to jump to. This object contains Model object and View object.
- Model: Set data to the request field.
- View: Specify the page to jump to.
2.3.1 Controller methods
// 返回值为ModelAndView
@RequestMapping("/c2/hello2")
public ModelAndView useMAV(){
System.out.println("返回值类型为ModelAndView");
// 1.创建ModelAndView对象
ModelAndView modelAndView = new ModelAndView();
// 2.获取Model对象,本质是一个Map
Map<String,Object> model = modelAndView.getModel();
// 3.使用Model对象向request域设置数据
model.put("username","黄庆禧");
// 4.使用view对象设置跳转的路径
modelAndView.setViewName("lyl-HQX");
return modelAndView;
}
OK, a username attribute is set here, and the attribute value is Huang Qingxi
2.3.2 JSP pages
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>lyl-HQX</title>
</head>
<body>
<h1>name: 你好!${requestScope.name}</h1>
<h1>username: 你好!${requestScope.username}</h1>
<h1>request-Map 你好!${requestScope.usernameMap}</h1>
<h1>session 地址是:${sessionScope.address}</h1>
<h1>context 年龄是:${applicationScope.age}</h1>
</body>
</html>
OK, let me explain here, the parameters used here are needed later.
2.3.3 Test results
OK, indeed Huang Qingxi's name can be successfully printed.
3. Some session objects set data
When the return value of the controller is ModelAndView, we can set data to the request field. We also have the following methods to set data to the request field:
3.1 request domain setting data
3.1.1 Use parameters as native HttpServletRequest
controller method
/**
* SpringMVC处理响应-request域
*/
// 使用原生的HttpServletRequest
@RequestMapping("/c2/hello3")
public String setRequestModel(HttpServletRequest request){
request.setAttribute("username","会洗碗的CV工程师");
return "lyl-HQX";
}
OK, the username attribute value is a CV engineer who can wash dishes, and see if it can be obtained successfully
Test Results
OK, you can see that it was successfully obtained. Next try some other parameters.
3.1.2 Use parameters as Model and ModelMap
SpringMVC provides the Model interface and the ModelMap class. The controller method adds these two types of parameters, uses the parameters to set the data, and the data will be stored in the request field.
controller method
//使用Model、ModelMap
@RequestMapping("/c2/hello4")
public String setRequestModel2(Model model, ModelMap modelMap){
// 使用Model将数据存入request域
model.addAttribute("username","LYL");
// 使用ModelMap将数据传入request域
modelMap.addAttribute("usernameMap","HQX");
return "lyl-HQX";
}
Test Results
OK, you can see that both attributes have been successfully obtained.
3.1.3 Use parameters as Map collection
The bottom layer of the Model interface is a Map collection. We can set parameters of the Map type for the controller method, add key-value pairs to the Map, and the data will also be stored in the request field.
controller method
// 使用Map集合
@RequestMapping("/c2/hello5")
public String setRequestModel3(Map map){
map.put("username","程序员");
map.put("usernameMap","程序员");
return "lyl-HQX";
}
Test Results
OK, it can be seen that the same as above can be used.
3.2 session domain setting data
Session scope means that it is valid in the current session. In SpringMVC, only the HttpSession object can be used to pass the value of the Session scope.
3.2.1 Controller methods
/**
* SpringMVC处理响应-session域设置数据
*/
@RequestMapping("/c2/hello6")
public String setSessionModel(HttpSession session){
session.setAttribute("address","北京");
return "lyl-HQX";
}
OK, this time I set an address attribute in the session field to see if it can be obtained successfully
3.2.2 Test results
Ok, you can see that it was successfully obtained.
3.3 context domain 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.
3.2.1 Controller methods
/**
* SpringMVC处理响应-context域设置数据
*/
@RequestMapping("/c2/hello7")
public String setContextModel(HttpSession session){
ServletContext servletContext = session.getServletContext();
servletContext.setAttribute("age",10);
return "lyl-HQX";
}
This time, use the context field to set an age attribute to see if you can get the corresponding value.
3.2.2 Test results
OK, indeed successfully obtained.
4. 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 through the view parser is the 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:
4.1 Native request forwarding and redirection writing
4.1.1 Redirecting controller methods
/**
* SpringMVC处理响应-请求转发&重定向
*/
@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");
}
OK, this is a redirect to /c2/hello9, and then write a controller method for /c2/hello9 to see if the console can print it out.
@RequestMapping("/c2/hello9")
public void myForward2(HttpServletRequest request){
System.out.println("hello");
System.out.println(request.getAttribute("name"));
}
4.1.2 Redirection test results
OK, you can see that the redirection has indeed gone. Note that after being redirected here, the attribute value of the request field cannot be obtained. I will try to see if the request forwarding is possible later. The redirect address bar will change, but the request forward address bar will not change.
4.1.3 Request to forward test results
OK, you can see that the attribute value can be obtained after the request is forwarded, and the address bar has not changed.
4.2 Request forwarding and redirection provided by springmvc
// SpringMVC提供一种关于重定向和请求转发更为简单的写法
@RequestMapping("/c2/hello10")
public String myForward3(HttpServletRequest request){
request.setAttribute("name","程序员");
// 请求转发
return "forward:/c2/hello9";
// 重定向
//return "redirect:/c2/hello9";
}
OK, that's all I've learned this time. Those who are interested can read my column below.
Related readings of previous columns & articles
If you don’t know anything about the content of this issue, you can also go to see the content of previous issues. The following is a series of column articles such as Maven and Mybatis carefully crafted by bloggers in the past. Don’t miss it when you pass by! If it is helpful to you, please like it and bookmark it. Among them, some of the Spring columns are being updated, so they cannot be viewed, but they can be viewed after the bloggers have completed all the updates.
1. Maven series of columns
Maven Series Column | Maven project development |
Maven aggregation development [example detailed explanation --- 5555 words] |