Spring MVC之响应数据

一、响应数据

响应之返回值是String类型

控制器:

 @RequestMapping("/testString")
    public String testString(ModelMap modelMap){
        System.out.println("testString方法执行了");
        //模拟从数据库中获取对象
        User user=new User();
        user.setUname("浩浩");
        user.setAge(1);
        user.setPwd("123");
        //利用Modelmap 将对象存到request域中
        modelMap.addAttribute("uu",user);

        /*即先取数据,再将数据存入到request域中,再转发到页面,后取出*/

        return "success";
    }

success.jsp中获取数据


    ${uu}
    ${uu.uname}

响应之无返回值

response.jsp


    <a href="user/testVoid">响应返回值是Void</a>
    <br>

控制器

 /*返回值是Void*/
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("testVoid方法执行了");

        /*当返回值是void类型时,它是由自己默认的跳转页面的,即一级目录+二级目录+二级目录名称.jsp
        * 当我们不想让他这样跳转时,就要自己去定义跳转的页面
        *
        * request.getRequestDispatcher,请求转发一次请求,不用编写项目名称
        *
        * 重定向:通常写法:
        * response.sendRedirect(request.getContextPath()+"/xxx.jsp");
        * response.sendRedirect(request.getContextPath()+"/index.jsp");
        *
        *
        * 重定向是重新发了个请求,是不能直接请求/WEB-INF 里面的页面的(转发可以)
        *
        * */

        //设置请求转发
       // request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);

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

        //直接相应设置中文乱码
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charest=UTF-8");

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


    }

知识点:

即路径跳转有三种方式

1、request请求转发

request.getRequestDispatcher,请求转发一次请求,不用编写项目名称

2、重定向

​ 通常写法:

  • response.sendRedirect(request.getContextPath()+"/xxx.jsp");

  • response.sendRedirect(request.getContextPath()+"/index.jsp");

  • 重定向是重新发了个请求,是不能直接请求/WEB-INF 里面的页面的(转发可以)

3、直接响应

response.getWriter().print(“hello浩浩”);

这个要设置中文乱码

​ response.setCharacterEncoding(“utf-8”);
​ response.setContentType(“text/html;charest=UTF-8”);

响应之返回值是ModelAndView

控制器

 /*返回值是ModelAndView*/
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        //创建ModelAndView对象
        ModelAndView mv=new ModelAndView();
        System.out.println("testModelAndView方法执行了");

        //模拟从数据库中获取对象
        User user=new User();
        user.setUname("昊昊");
        user.setAge(20);
        user.setPwd("2222");

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

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

        return mv;
    }

其实返回值String类型的底层就是ModelAndView,ModelAndView它是spring带有的,直接new对象,然后利用里面的方法将要存入的对象和要跳转的页面存入到ModelAndView对象中

转发和重定向

响应使用转发和重定向是用不了视图解析器的,这就需要自己把路径写好

注意:

* 重定向:通常写法:
        * response.sendRedirect(request.getContextPath()+"/xxx.jsp");
        * response.sendRedirect(request.getContextPath()+"/index.jsp");
        *
        *

重定向是重新发了个请求,是不能直接请求/WEB-INF 里面的页面的(转发可以)

控制器

@RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){

        System.out.println("testModelAndView方法执行了");

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

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

    }

响应json数据

过滤静态资源
  1. DispatcherServlet会拦截到所有的资源,导致一个问题就是静态资源(img、css、js)也会被拦截到,从而不能被使用。解决问题就是需要配置静态资源不进行拦截,在springmvc.xml配置文件添加如下配置

    mvc:resources标签配置不过滤

    1. location元素表示webapp目录下的包下的所有文件

    2. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b

    <!-- 设置静态资源不过滤 -->
    <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
    
    <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
    
    <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->
    

    当然你创建的文件夹名称要和上述一样,才会生效

1、引入jquery.js

image-20210724115231281

2、在springmvc中配置那些静态资源不拦截

  <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources mapping="/js/**" location="/js/"/>

3、使用@RequestBody获取请求体数据

发送Ajax的请求

reponse.jsp


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <%--引入jquery--%>
    <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:'{"uname":"哈哈","age":10,"pwd":"111"}',
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                        //data服务器端响应的json的数据,进行解析
                    }

                });

            });
        });

    </script>

</head>
<body>
    <a href="user/testString">响应返回值是String</a>
    <br>

    <a href="user/testVoid">响应返回值是Void</a>
    <br>

    <a href="user/testModelAndView">响应返回值是ModelAndView</a>
    <br>

    <a href="user/testForwardOrRedirect">响应使用转发或者重定向</a>
    <br>

    <button id="btn">发送ajax的请求</button>
</body>
</html>

控制器


    /*模拟异步请求响应*/
    @RequestMapping("/testAjax")
    public void testAjax(@RequestBody String body){
        System.out.println("testAjax方法执行了");
        System.out.println(body);
    }

image-20210724150605241

json的字符串与JavaBean对象相互转换

4、使用@RequestBody注解把json的字符串转换成JavaBean的对象(形参部分)

5、使用@ResponseBody注解把JavaBean对象转换成json字符串,直接响应(返回值部分)

 /*模拟异步请求响应
    * 传过来的json数据串,因为名称和实体类的属性名一样,所以可以直接进行封装,利用注解@RequestBody
    *
    * 因为那边需要返回的数据是json,所以利用注解@ResponseBody,将user中的数据转为json
    * */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax方法执行了");
        user.setUname("haha");
        user.setPwd("999");
        user.setAge(0);
        System.out.println(user);

        return user;
    }

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值