SSM's SpringMVC series (three) ---- response data and result view

In the last article, we talked about the binding of SpringMVC request parameters and common annotations . Now let’s talk about the response data and result view in SpringMVC.

Response data and result view

(Controller)The return value of the method in the controller can be one of the following:

  • String String type
  • void No return value
  • ModelAndView SpringMVC provides us with an object that can contain data and views
  • JavaBean 对象( jsonRespond by data)

The return value is String

  • When the controller returns a Stringtype, the default is to return the logical view name , which is then parsed into the physical view address by the view resolver , and finally the bottom layer forwards the request to the corresponding page through request forwarding .

  • Environment to build in front of you can go and see my previous article Portal

  • response.jspCode:

<a href="user/testString">testString</a>
  • Controller code
@Controller
@RequestMapping("/user")
public class UserController {
    
    

    /**
     * 返回值为 String ,结合 model 对象保存数据
     * @param model
     * @return
     */
    @RequestMapping("/testString")
    public String testString(Model model){
    
    
        System.out.println("testString执行了。。。");
        // 模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("老王");
        user.setPassword("123");
        user.setAge(30);
        // model对象
        model.addAttribute("user",user);
        return "success";
    }
}

The return value is void

  • When used voidas the return value of a controller method, the default forwarding path@RequestMapping after the method execution ends is the path bound to the current method, which is the value in . But the fact that the return value is also parsed view resolver , so usually reported 404errors. For example, there is a controller method at this time:
@RequestMapping("/testVoid")
    public void testVoid(Model model){
    
    
        System.out.println("testString执行了。。。");
    }

Insert picture description here

  • If you only want to use voidthe return value, they also want to respond to the request, such as forwarding or redirecting the request, then we can use Servletto provide a native API method parameters as the controller
  • Request forwarding
@RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response)throws Exception{
    
    
        System.out.println("testString执行了。。。");
        // 转发是一次请求,无需加项目虚拟目录,但是因为直接通过原生api进行转发,不会经过视图解析器,所以应该写具体路径
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        // 转发或重定向后,如果还有代码,会继续执行,此时可以使用 return; 结束
        return;
    }
  • Redirect
 @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response)throws Exception{
    
    
        System.out.println("testString执行了。。。");
        // 重定向,需要项目虚拟目录
        response.sendRedirect(request.getContextPath()+"/index.jsp");
        return;
    }
  • Generate a response directly like the client, such as responding to json data
@RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response)throws Exception{
    
    
        System.out.println("testString执行了。。。");
        // 解决中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 直接会进行响应
        response.getWriter().print("你好");
        return;
    }

When the method parameters contained HttpServletResponse, even if the method body without any treatment, after the method will not jump to another page. Regarding this point, check the official documentation because SpringMVC will think that it has responded to the request at this time, so it will not help us jump to other pages.

The return value is ModelAndView

  • When the method returns the value of the controller ModelAndView, when in fact equivalent to the return value of a first embodiment Stringtogether with parameters Model, as ModelAndViewmay be incoming data (using the page directly acquired EL expressions: ${attributeName}), but also may be provided The name of the logical view to jump to.

  • success.jspCode:

<body>
    <h3>执行成功</h3>
    ${requestScope.user}
</body>
  • Controller method
    /**
     * 返回ModelAndView
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
    
    
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView方法执行了...");
        // 模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("小王");
        user.setPassword("456");
        user.setAge(20);
        // 把user对象存储到mv对象中,也会把user对象存入到request对象
        mv.addObject("user",user);

        // 跳转到哪个页面
        mv.setViewName("success");
        return mv;
    }

Request forwarding and redirection

  • The method of the controller when the return value of Stringtime, the default is to forward the request , we can also like the above example, the use of native Servlet API forward or redirect the request to complete. However, SpringMVC also provides another way for us is to use forward:and redirect:keywords.
    /**
     * 使用关键字的方式进行转发或者重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
    
    
        System.out.println("testForwardOrRedirect方法执行了...");

        // 请求的转发 forward: 关键字转发,不会使用视图解析器
        // return "forward:/WEB-INF/pages/success.jsp";

        // redirect: 关键字重定向,不用加项目路径
        return "redirect:/index.jsp";
    }
  • For forward:keywords, according to the official documentation, the bottom layer also uses the Servlet native API for forwarding, that is RequestDispatcher.forward(), it does not pass through the view resolver, so the forwarding path requires a specific path.

Insert picture description here
It should be noted that if it is used, the formward:path must be written as the actual viewurl , not the logical view.
It is equivalent to " request.getRequestDispatcher("url").forward(request,response)". Using request forwarding, it can be forwarded to jsp or to other controller methods.

  • For response:keywords, according to the official documentation, SpringMVC will redirect according to the current Servlet context, so there is no need to write the project path.
    Insert picture description here
    It is equivalent to " response.sendRedirect(url)". It should be noted that if you are redirected to a jsp page, the jsp page cannot be written in the WEB-INFdirectory, otherwise it cannot be found .

Use @RequestBody and @ResponseBody for json interaction

  • In a development, most of the time the client submits jsondata, the server receives jsonthe data and parsing, and then generates a jsonresponse to the client. This time we can use @RequestBodyand @ResponseBodyto complete jsoninteractive data.
  • response.jspCode:
<%--
  Created by IntelliJ IDEA.
  User: 15728
  Date: 2021/2/19
  Time: 20:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery.min.js"></script>
    <script>
        // 页面加载,绑定单击事件
        $(function(){
    
    
           $("#btn").click(function () {
    
    
              //alert("你好");
               // 发送ajax请求
               $.ajax({
    
    
                   //编写json格式,设置属性和值
                   url:"user/testAjax",
                   contentType:"application/json;charset=UTF-8",
                   data:'{"username":"一个Java小白","password":"123","age":18}',
                   dataType:"json",
                   type:"post",
                   success:function (data) {
    
    
                       // data服务器端响应的json的数据,进行解析
                       alert(data);
                       alert(data.username);
                       alert(data.password);
                       alert(data.age);
                   }
               });
           });
        });

    </script>
</head>
<body>
    <button id="btn">发送ajax的请求</button>
</body>
</html>

Because we have configured the front controller DispatcherServlet, all requests will be intercepted, including static resources. In order to prevent the imported from jquery.jsbeing intercepted, we need springmvc.xmlto configure not to intercept static resources in the configuration file

  <!--前端控制器,哪些静态资源不拦截-->
  <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
  <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
  <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript --> 
  • locationAttribute: Specify webappthe package in the directory
  • mappingProperties: expressed in /staticall requested paths beginning
  • Controller code
 /**
     * 模拟异步请求响应
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
    
    
        System.out.println("testAjax方法执行了...");
        // 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
        System.out.println(user);
        // 做响应,模拟查询数据库
        user.setUsername("一个Java小白2");
        user.setAge(20);
        // 做响应
        return user;
    }
  • The client sends a jsonstring, using the server @RequestBodyacquiring the content request body, and the use of jacksonthe jsonstring is encapsulated into the User object; server uses @ResponseBodyto generate a response by jacksonthe User json object into a string.
  • SpringMVC uses MappingJacksonHttpMessageConverterby default for conversion, so it needs to import jacksonthe dependency
	<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>

Import errors, the same way. Portal

  • When using jackson to automatically convert between json and JavaBean objects, you need to ensure that the keys of the json string correspond to the JavaBean attribute names one-to-one

Guess you like

Origin blog.csdn.net/weixin_43844418/article/details/113871281
Recommended