• springMvc 系列 5-响应数据和结果视图


    返回值分类

    1. 返回字符串
      - Controller方法返回字符串可以指定逻辑视图的名称,根据视图解析器解析为页面的地址。
        <a href="hello">Hello</a>
    
        @RequestMapping(path="/hello")
        public String sayHello(){
            System.out.println("Hello StringMVC");
            return "success";
        }
    
    当点击“Hello”按钮,则跳转到“success.jsp”文件中。
    
    1. 返回值是void
      - 如果控制器的方法返回值是void,执行程序报404的异常,没有找到jsp页面。这时候可以使用请求转发或者重定向跳转到指定的页面
        @RequestMapping(value="/initAdd") 
        public void initAdd(HttpServletRequest request,HttpServletResponse response) throws Exception {
            System.out.println("请求转发或者重定向");
            // 请求转发 
            // request.getRequestDispatcher("/WEB-INF/pages/add.jsp").forward(request, response);
            // 重定向 
            // response.sendRedirect(request.getContextPath()+"/add2.jsp"); 
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            // 直接响应数据 
            response.getWriter().print("你好");
            return;
        }
    
    1. 返回值是ModelAndView对象
      ModelAndView对象是Spring提交的,用来调整具体的jsp视图
        @RequestMapping("/findAll")
        public ModelAndView findAll() throws Exception{
            ModelAndView mv = new ModelAndView();
            //跳转到list.jsp页面
            mv.setViewName("list");
    
            List<User> users = new ArrayList<>();
            User user1 = new User();
            user1.setUsername("张三");
            user1.setPassword("123456");
    
            User user2 = new User();
            user2.setUsername("李四");
            user2.setPassword("1111");
            users.add(user1);
            users.add(user2);
    
            //添加对象
            mv.addObject("users", users);
            return mv;
        }
    
    <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <head>
        <title>Title</title>
    </head>
    <body>
        <c:forEach items="${ users }" var="user">
            ${ user.username }
        </c:forEach>
    </body>
    
          需要引入jstl包
          <dependency>
              <groupId>javax.servlet</groupId>
              <artifactId>jstl</artifactId>
              <version>1.2</version>
          </dependency>
    

    springMvc提供的转发和重定向

    • forward请求转发
        /**
         * springmvc转发
         * 使用forward关键字进行请求转发
         * forward:转发的jsp路径,不走视图解析器,需要编写完整的路径
         * @return
         * @throws Exception
         */
        @RequestMapping("/delete")
        public String delete() throws Exception{
            return "forward:/user/findAll";
        }
    
    • redirect重定向
        /**
         * springmvc的重定向
         * @return
         * @throws Exception
         */
        @RequestMapping("/count")
        public String count() throws  Exception{
            return "redirect:/user/findAll";
        }
    

    ResponseBody响应json数据

    1. DispatcherServlet会拦截所有资源,导致静态资源(css,js)也被拦截,从而不能被使用。解决的办法就是配置不对静态资源进行拦截,在springmvc.xml配置文件中添加如下配置:
      - mvc:resources标签配置不过滤
      • location元素表示webapp目录下的所有文件
      • mapping元素表示以/static开头的所有请求路径,如/static/a
    
        <!--前端控制器,哪些静态资源不拦截-->
        <mvc:resources location="/css/" mapping="/css/**"/>
        <mvc:resources location="/images/" mapping="/images/**"/>
        <mvc:resources location="/js/" mapping="/js/**"/>
    
    1. 使用@RequestBody获取请求体数据
            $(function(){
                $('.btn').click(function(){
                    $.ajax({
                        url:'user/testJson',
                        contentType:'application/json;charset=UTF-8',
                        data:'{"address":"南京","addressNum":"010"}',
                        dataType:'json',
                        type:'post',
                        success: function(data){
                            console.log(data)
                            console.log(data.address)
                        }
                    })
                })
            })
    
        @RequestMapping("/testJson")
        public void testJson(@RequestBody String body){
            System.out.println(body);
        }
    
    1. 使用@RequestBody注解把json字符串转换成JavaBean对象
        @RequestMapping("/testJson")
        public void testJson(@RequestBody Address addr){
            System.out.println(addr);
        }
    
    1. 使用@ResponseBody注解把JavaBean对象转换成json字符串
        @RequestMapping("/testJson")
        public @ResponseBody Address testJson(@RequestBody Address addr){
            System.out.println(addr);
            return addr;
        }
    
        json字符串和JavaBean对象互相转换过程中,需要用到jackson的jar包:
        <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>
    
  • 相关阅读:
    操作系统---学习笔记00
    操作系统---学习笔记0
    2015/07/16入园啦!
    1-1 console的用法
    2.3 js基础--DOM
    1.2 js基础
    1.1 js基础
    信息收集(1)
    Android概述
    从一次失败的比赛经历引发的思考
  • 原文地址:https://www.cnblogs.com/mantishell/p/12878665.html
Copyright © 2020-2023  润新知