SpringMVC_return value type and response data_hehe.employment.over.38.1

38.1 Return value classification

38.1.1 Return string

  • The controller method returns a string to specify the logical view name, which is resolved into the physical view address by the view resolver.
  • Example:
    /**
     * 返回String
     * @param model
     * @return
     */
     //指定逻辑视图名,经过视图解析器解析为 jsp 物理路径:/WEB-INF/pages/success.jsp
    @RequestMapping("/testString")
    public String testString(Model model){
    
    
        System.out.println("testString方法执行了...");
        // 模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("xww");
        user.setPassword("123");
        user.setAge(20);
        // model对象
        model.addAttribute("user",user);
        return "success";
    }
    <a href="user/testString">testString</a>

38.1.2 The return value is void

  • If the return value of the controller method is written as void, the execution program reports a 404 exception, and the JSP page is not found by default.
    • By default, it will jump to the @RequestMapping(value="/initUpdate") initUpdate page.
  • You can use request forwarding or redirection to jump to the specified page
  • Example:
    /**
     * 是void
     * 请求转发一次请求,不用编写项目的名称
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
    
    
        System.out.println("testVoid方法执行了...");
        // 编写请求转发的程序
        // request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

        // 重定向
        // response.sendRedirect(request.getContextPath()+"/index.jsp");

        // 设置中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        // 直接会进行响应
        response.getWriter().print("你好");

        return;
    }

38.1.3 The return value is a ModelAndView object

  • The ModelAndView object is an object provided by Spring that can be used to adjust specific JSP views.
    Examples:
    /**
     * 返回ModelAndView
     * @return
     */
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
    
    
        // 创建ModelAndView对象
        ModelAndView mv = new ModelAndView();
        System.out.println("testModelAndView方法执行了...");
        // 模拟从数据库中查询出User对象
        User user = new User();
        user.setUsername("xww");
        user.setPassword("456");
        user.setAge(30);

        // 把user对象存储到mv对象中,也会把user对象存入到request对象
        mv.addObject("user",user);

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

        return mv;
    }

38.1.4 Forwarding and Redirection Provided by SpringMVC Framework

  • forward request forwarding
    • The controller method returns String type, you can also write it if you want to forward the request
    • Example:
    /**
     * 使用关键字的方式进行转发或者重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
    
    
        System.out.println("testForwardOrRedirect方法执行了...");

        // 请求的转发
        // return "forward:/WEB-INF/pages/success.jsp";

        // 重定向
        return "redirect:/index.jsp";
    }

38.2 ResponseBody responds to json data

  • DispatcherServlet will intercept all resources, causing a problem that static resources (img, css, js) will also be intercepted and cannot be used. To solve the problem, you need to configure static resources without interception. Add the following configuration to the springmvc.xml configuration file:
    • mvc:resourcesLabel configuration does not filter
      • The location element represents all files under the package in the webapp directory
      • The mapping element represents all request paths beginning with /static, such as /static/a or /static/a/b
    <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
  • In the process of converting between json string and JavaBean object, jackson jar package is required
    <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>
  • Example:
    /**
     * 模拟异步请求响应
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
    
    
        System.out.println("testAjax方法执行了...");
        // 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
        System.out.println(user);
        // 做响应,模拟查询数据库
        user.setUsername("haha");
        user.setAge(40);
        // 做响应
        return user;
    }
    <script>
        // 页面加载,绑定单击事件
        $(function(){
     
     
            $("#btn").click(function(){
     
     
                // alert("hello btn");
                // 发送ajax请求
                $.ajax({
     
     
                    // 编写json格式,设置属性和值
                    url:"user/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"username":"hehe","password":"123","age":30}',
                    dataType:"json",
                    type:"post",
                    success:function(data){
     
     
                        // data服务器端响应的json的数据,进行解析
                        alert(data);
                        alert(data.username);
                        alert(data.password);
                        alert(data.age);
                    }
                });

            });
        });

    </script>

Guess you like

Origin blog.csdn.net/qq_44686266/article/details/114870458