SpringMVC 响应数据和结果视图

1. 返回值分类

返回字符串

  1. Controller方法返回字符串可以指定逻辑视图的名称,根据视图解析器为物理视图的地址。
    ${user}
    <form action="user/testString" method="post">
        姓名:<input type="text" name="username" value="${user.username}"><br>
        密码:<input type="text" name="password" value="${user.password}"><br>
        金额:<input type="text" name="money" value="${user.age}"><br>
        <input type="submit" value="提交">
    </form>
    @RequestMapping("/testString")
    public String testString(Model model){
        System.out.println("testString执行了......");
        //模拟数据库中查询处 把对象存起来 转发到页面
        User user = new User();
        user.setUsername("张三");
        user.setPassword("1111");
        user.setAge(23);
        model.addAttribute("user",user);
        return "success";
    }

返回值是void

  1. 如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到。
    1. 默认会跳转到@RequestMapping(value="/initUpdate") initUpdate的页面。
  2. 可以使用请求转发或者重定向跳转到指定的页面
    /**
     * 返回值类型void
     * 请求转发一次请求,不用写项目名称
     *
     */
    @RequestMapping("/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response)throws Exception{
        System.out.println("testString执行了......");
        //编写请求转发
//        request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        // 重定向
        response.setCharacterEncoding("UTF-8"); 
        response.setContentType("text/html;charset=UTF-8");
        //直接响应
        response.getWriter().write("你好");response.sendRedirect(request.getContextPath()+"/index.jsp");
        return;
    }
  1. 返回值是ModelAndView对象
    1. ModelAndView对象是Spring提供的一个对象,可以用来调整具体的JSP视图
    2. 具体的代码如下
    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        System.out.println("testString执行了......");
        ModelAndView mv = new ModelAndView();
        //模拟数据库中查询处 把对象存起来 转发到页面
        User user = new User();
        user.setUsername("张三");
        user.setPassword("114511");
        user.setAge(23);
        //把User对象存到mv对象中 也就是存入request对象中
        mv.addObject("user",user);
        //跳转到那个界面
        mv.setViewName("success");
        return mv;
    }

SpringMVC框架提供的转发和重定向

  1. forward请求转发
    1. controller方法返回String类型,想进行请求转发也可以编写成
    2. controller方法返回String类型,想进行重定向也可以编写成
    /**
     * 关键字的方式进行转发或者重定向
     * @return
     */
    @RequestMapping("/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        System.out.println("testForwardOrRedirect执行了......");

        //请求的转发 关键字的方式
//        return "forward:/WEB-INF/pages/success.jsp";
        // controller方法返回String类型,想进行重定向也可以编写成
        return "redirect:/index.jsp";
    }

ResponseBody响应json数据

  1. DispatcherServlet会拦截到所有的资源,导致一个问题就是静态资源(img、css、js)也会被拦截到,从而不能被使用。解决问题就是需要配置静态资源不进行拦截,在springmvc.xml配置文件添加如下配置
    1. mvc:resources标签配置不过滤
    2. location元素表示webapp目录下的包下的所有文件
    3. mapping元素表示以/static开头的所有请求路径,如/static/a 或者/static/a/b

springmvc.xml

    <!-- 设置静态资源不过滤 -->
    <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
    <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
    <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->
  1. 使用@RequestBody获取请求体数据
//页面加载 绑定单击时间
        $(function () {
           $("#btn").click(function () {
              // alert("hello btn");
               //发送ajax请求
               $.ajax({
                  //编写json格式 设置属性和值
                   url:"user/testAjax",
                   contentType:"application/json;charset=utf-8",
                   data:'{"username":"张三","password":"1234","age":"12"}',
                   dataType:"json",
                   type:"post",
                   success:function (data) {
                       //data 服务器端响应的json数据, 进行解析
                   }
               });
           });

        });

Controller

 /**
  * 模拟异步请求响应
  */
 @RequestMapping("/testAjax")
 public void testAjax(@RequestBody String body){
     System.out.println("testAjax执行力......");
     System.out.println(body);
 }
  1. 使用@RequestBody注解把json的字符串转换成JavaBean的对象

  2. 使用@ResponseBody注解把JavaBean对象转换成json字符串,直接响应

    1. 要求方法需要返回JavaBean的对象
  3. json字符串和JavaBean对象互相转换的过程中,需要使用jackson的jar包

pom.xml

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

XML

        //页面加载 绑定单击时间
        $(function () {
           $("#btn").click(function () {
              // alert("hello btn");
               //发送ajax请求
               $.ajax({
                  //编写json格式 设置属性和值
                   url:"user/testAjax",
                   contentType:"application/json;charset=utf-8",
                   data:'{"username":"张三","password":"1234","age":"12"}',
                   dataType:"json",
                   type:"post",
                   success:function (data) {
                       //data 服务器端响应的json数据, 进行解析
                       alert(data);
                       alert(data.username);
                   }
               });
           });

        });

Controller类
要导入5.里面的包才可以自动封装到bean

    /**
     * 模拟异步请求响应 封装到JavaBean
     */
    @RequestMapping("/testAjax")
    public @ResponseBodyUser testAjax(@RequestBody User user){
        System.out.println("testAjax执行力......");
        //客户端发送ajax请求 穿的是json字符串 后端把json封装到User
        System.out.println(user);
        //响应 模拟查询数据库
        user.setUsername("哈哈哈");
        user.setPassword("4512");
        user.setAge(11);
        //做响应
        return user;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值