SpringMVC basics--request response return value, response json data, encapsulation and conversion of json data

response return value

When processing a request, the return value type of the controller's handler function can determine how it responds to the request.

The return value is String type

When the return value is string type, it will search for the specified type of file in the path specified by the view parser according to the return value and display it.

Controller Handling Method

@RequestMapping("/hello")
    public String testJson() {
    
    
        System.out.println("执行了");
        return "success";
    }

View resolver configuration

<!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

When processing /hellothe request, it will go to the path specified by the view resolver classpath/WEB-INT/pages/to find the success.jsp file and display it to the browser.

The return value is void

If the return value is void, and the controller handles the request method without any forwarding and redirection, the file will be searched for the path specified by the view resolver by default 请求名称.类型名.

@RequestMapping("/hello")
    public void testJson() {
    
    
        System.out.println("执行了");
    }

As above, you will look for hello.jspthe file, if you can’t find it, you will report 404 directly.
Generally, when the return value is void type, it will be forwarded and redirected in the controller processing method.
The following code contains three methods

@RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
    
    
        System.out.println("执行了");
        // 第一种:编写请求转发程序
        // httpServletRequest.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(httpServletRequest,httpServletResponse);
        // 第二种:重定向
        // httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/index.jsp");
        //设置中文乱码问题
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("text/html;charset=UTF-8");
        // 第三种:直接会响应。直接打印出以下字符
        httpServletResponse.getWriter().println("你好");
    }

If you don’t know about HttpServletRequest and HttpServletResponse, you can read this blog: Implementation classes of HttpServletRequest and HttpServletResponse

The return value is ModelAndView

Encapsulate the data by creating a ModelAndView object, and then jump to the specified type file in the specified path of the view parsing system. The bottom layer with String as the return value type is implemented by ModelAndView.

@RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView() {
    
    
        System.out.println("执行了");
        User user = new User();
        user.setName("美美");
        user.setPassword("123");
        user.setAge(18);
        ModelAndView mv = new ModelAndView();
        mv.addObject("user",user);
        mv.setViewName("success");
        return mv;
    }

Response JSON data

Send json data to the server on the jsp main page, the controller processing method encapsulates the json data into JavaBean type through @RequestBody, and finally converts the JavaBean type into json data through @ResponseBody.
Springmvc uses MappingJacksonHttpMessageConverter by default to convert json data, which needs to be added to the jackson package.

<dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.2</version>
    </dependency>

First import the jquery.js file and put it in the js folder under the class path
Note: When we create the front controller, we intercept all requests, including these static files.

  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

So we need to filter out these static files in the configuration file of springmvc.

<!-- 设置静态资源不过滤 -->
<mvc:resources location="/js/" mapping="/js/**"/>
<mvc:resources location="/img/" mapping="/img/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>

send json data

<button id="btn">按钮</button>
    <script>
        $(function () {
    
    
            $("#btn").click(function () {
    
    
                $.ajax({
    
    
                    url:"request/testJson",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"name":"aa","password":100}',
                    dataType:"json",
                    type:"post",
                    success:function(data){
    
    
                        alert(data);
                        alert(data.name);
                    }
                });
            })
        })
    </script>

Controller Handling Method

// ResponseBody 将JavaBean对象转换成JSON数据
    @RequestMapping("/testJson")
    public @ResponseBody  User testJson(@RequestBody User user) {
    
    
        System.out.println("执行了");
        System.out.println("user:" + user);
        return user;
    }

Successfully encapsulated into JavaBean type
insert image description here

successfully converted to json data
insert image description here

Guess you like

Origin blog.csdn.net/qq_44660367/article/details/108922109