Response data and view the results SpringMVC-

Response data and view the results SpringMVC-

1. Return Value Category

  1.1 String 

Controller method returns the string can be the name of the specified logical view, resolved to a physical address view through the view resolver.

    / ** 
     * Return Value String 
     * name specified logical view, the view through the physical path parser is jsp: /WEB-INF/pages/success.jsp 
     * @param Model 
     * @return 
     * / 
    @RequestMapping ( "/ testString" )
     public String testString (the Model Model) { 
        System.out.println ( "method testString performed ..." ); 
        the User User = new new the User (); 
        user.setUsername ( "John Doe" ); 
        user.setAge ( 18 is ); 
        user.setSex ( "F" );
 //         store 
        model.addAttribute ( "user", user);
        return "success";
    }

  1.2 void, no return value

  Servlet API as the original parameters of the controller in the method.

    (1) forwards the request using the request:

   /**
     * 没有返回值
     * @param
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = new User();
        user.setUsername("张三");
        user.setAge(18);
        user.setSex("女");
        //存储
        request.setAttribute("user", user);
        System.out.println(user);

        //请求转发
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
       //设置中文乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
 return;
    }

    (2) redirect response:

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

    (3) can enter the corresponding results response. E.g. json response data.

 // will directly respond 
        response.getWriter () print ( "hello" ).;

   1.3 ModelAndView

  ModelAndView SpringMVC is an object to provide us, the subject method can be used as the return value of the controller.

  

   / ** 
     * ModelAndView: Jump view data storage + 
     * @param ModelAndView 
     * @return 
     * / 
    @RequestMapping ( "/ testModelAndView" )
     public ModelAndView testModedAndView (ModelAndView ModelAndView) { 
        the User User = new new the User (); 
        user.setUsername ( " Wang Wu " ); 
        user.setSex ( " male " ); 
        user.setAge ( 16 ); 

        // store 
        modelAndView.addObject (" the User " , the User); 

        // Jump view 
        modelAndView.setViewName (" Success " );
        return modelAndView;
    }

 

2. Forwarding and Redirection

  2.1 forward forward

  controller provides a method of type String return value after the default is to forward the request. We can also be written as:

    / ** 
     * use keywords forwarding and redirection 
     * @return 
     * / 
    @ RequestMapping ( "/ testForwardOrRedirect" )
     public String testForwardOrRedirect () {
         // forward the request 
        return "Forward: / the WEB-INF / Pages and the / Success. JSP " ;
   
    }

  Note: If the forward: then it must be written to be actual views url, can not be written logical view.

      It corresponds to "request.getRequestDispatcher (" url ") forward (request, response);.". Use request forwarding, may be forwarded to jsp, it may be transmitted to other control methods.

  

  2.2 Redirect Redirect    

contrller method provides a return value of type String after, it needs to use the return value in: redirect:
/ ** 
     * Use keywords way forward and redirect 
     * @return 
     * / 
    @ RequestMapping ( "/ testForwardOrRedirect" )
     public String testForwardOrRedirect () {
         // forward the request
 //         return "Forward: / the WEB-INF / Pages and the / success.jsp ";
         // redirect 
        return " the redirect: /response.jsp " ; 
    }

  It is equivalent to "response.sendRedirect (url)". If you are redirected to a jsp page, the page can not be in WEB-INF  

 

3. ResponseBody response data json

  3.1 instructions

  Effect: This method returns the Controller object annotation by HttpMessageConverter interface into data in a specified format. Such as: json, xml, etc., through the Response to the client in response.

  3.2 Example of use

  The controller implemented using @ResponseBody annotation method returns the object is converted into json response to the client.

  SpringMVC default data converted to json MappingJacksonHttpMessageConverter, need to be added dependent.

  pom.xml:

  

 <!--jackson-->
    <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>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>
  </dependencies>

  controller Code:

//     / *
 //      * emulate asynchronous request-response
 @      * @param body
 //      * /
 //     @RequestMapping ( "/ testAjax")
 //     public void testAjax (@RequestBody String body) {
 //         the System.out. the println (body);
 //     }
 //
 
    / ** 
     * analog asynchronous request-response 
     * @param User
      * / 
    @RequestMapping ( "/ testAjax" )
     public @ResponseBody the User testAjax (@RequestBody the User User) { 
        System.out.println ( the User); 
        //         do respond 
        user.setUsername ( "Monkey King" );
        user.setSex("男");
        user.setAge(18);
        return user;
    }

  ajax request:

< Head > 
    < title > the Title </ title > 
    <% - < Script the src = " JS / jquery.min.js " > </ Script > - %> 
    < Script the src = "HTTPS: //code.jquery. COM / jQuery-3.0.0.min.js " > </ Script > 
    < Script > 
        // page is loaded, bind click event 
        $ ( function () { 
           $ ( " #btn " ).click(function () {
               // alert("hello");
               // 发送ajax请求
               $.ajax({
                   url:"user/testAjax",
                   contentType:"application/json;charset=UTF-8",
                   data:'{"username":"张三","age":"19","sex":"女"}',
                   dataType:"json",
                   type:"post",
                   success:function (data) {
                       alert(data);
                       alert(data.username);
                       alert(data.age);
                       alert(data.sex);
                   }
               });
           });
        });
    </script>
</head>
<body>
<button id="btn">发送ajax</button>

Source: GitHub

 

Guess you like

Origin www.cnblogs.com/liulebin/p/11386896.html