Mainstream FRAMEWORK: SpringMVC (3) view the response data and results

First, the return value of classification

(1) String

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

指定逻辑视图名,经过视图解析器解析为jsp 物理路径:/WEB-INF/pages/success.jsp
/**
     * 响应字符串为返回值
     * @return
     */
    @RequestMapping("/testString")
    public String testString(Model model) {
        System.out.println("testString()执行了...");

        //模拟从数据库中查询User对象
        User user = new User();
        user.setUsername("哈哈");
        user.setPassword("xmgl0609");
        user.setAge(30);

        //model对象
        model.addAttribute("user",user);
        return "success";
    }

(2)void

We know Servlet API original parameters of the controller can be used as a method. Request or response may be used to specify a response result, for example, request forwarding, redirection, response data

/**
     * 响应void
     * 请求转发一次请求,不用编写项目的名称
     * @param request
     * @param response
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("testVoid()方法执行了...");
        //编写请求转发的程序
        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

        //重定向(request.getContextPath()获得根目录)
        response.sendRedirect(request.getContextPath() + "index.jsp");


        //设置中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //直接会进行响应
        response.getWriter().print("你好");
    }

(3) ModelAndView

ModelAndView SpringMVC is an object to provide us, as the name suggests is a combination of a model and the View , the object may also be used as the return value of the controller.

AddObject stored can be encapsulated () can be selected while the object setViewName () jump page.

/**
     * 返回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("xmgl0609");
        user.setAge(30);

        //将user存储到modelandview中
        mv.addObject("user",user);

        //跳转到什么页面
        mv.setViewName("success");

        return mv;
    }

Here Insert Picture Description
Here Insert Picture Description

Note: mv.addObject ( "user", user ); want to get the objects on the page.
Using requestScope.username taken, so the return ModelAndView type, browser jump only forward the request.

Second, forwarding and redirection

(1) forward forward

controller method provides a return value of type String after, the default is to forward the request.

That return the string, that is, forward: /WEB-INF/pages/success.jsp

/**
     * 使用关键字方法进行转发
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect() {
        System.out.println("testForwardOrRedirect()执行了...");
       //请求的转发
       return "forward:/WEB-INF/pages/success.jsp";
    }

Note that, if the formward: then it must be written in the actual view url , can not write logical view. It is no use trying parser.

It is equivalent to "request.getRequestDispatcher (" url "). Forward (Request, the Response)" . Use request forwarding, may be forwarded to jsp, it may be transmitted to other control methods. (Servlet)

(2) Redirect redirect

/**
     * 使用关键字方法进行重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect() {
        System.out.println("testForwardOrRedirect()执行了...");
        //重定向
        return "redirect:/index.jsp";
    }

It is equivalent to response.sendRedirect (url) . Note that, if it is redirected to a jsp page, the jsp page can not be written in the WEB-INF directory, or can not be found. (Usually written in a webapp, or it following sub-folder)

Three, ResponseBody response data json

Here Insert Picture Description
The annotation for the object of the Controller method returns , by HttpMessageConverter interface to a designated data format such as: json, xml , etc., through the Response to the client in response .

We need to add jackson package

<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>

Jsp in the front end,

<script src="js/jquery.min.js"></script>

    <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>
<!-- 测试异步请求 -->
 <button id="btn">发送ajax的请求</button>

The controller code:

/**
     * 模拟异步请求响应,@ResponseBody 的使用
     * @param user
     * @return
     */
    @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;
    }

Operating results:
1. Console User content format printing json
2. jsp pages, will be acquired json data server response data, analyzing, and displaying the pop-up box .

Published 47 original articles · won praise 18 · views 4866

Guess you like

Origin blog.csdn.net/qq_43605085/article/details/100650952