SpringMVC学习02:响应数据和结果视图

通过控制器方法返回值指定返回视图

返回值为String

返回值为String时转发到指定的url

	/**
     * 返回值是String
     * @param model
     * @return
     */
    @RequestMapping(path = "/testString")
    public String testString(Model model){
        System.out.println("testString执行了");
        User user = new User();
        user.setUsername("cc");
        user.setPassword("666");
        user.setAge(20);
        model.addAttribute("user",user);
        return "success";
    }

返回值为void

返回值为void时,执行程序会报404的异常,因为默认jsp页面没有找到,也可以使用请求转发或者重定向跳转到指定的页面或者直接在页面上输出

	/**
     * 返回值是Void
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(path = "/testVoid")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception{
        System.out.println("testVoid执行了");
        //1.请求转发
        //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
        //2.重定向
        //response.sendRedirect(request.getContextPath()+"/index.jsp");
        //3.直接进行响应
        //设置解决中文乱码
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println("你好");
    }

返回值为ModelView

ModelView是SpringMVC提供的一个对象,可以用来调整具体的jsp页面

	/**
     * 返回值是ModelAndView
     * @return
     */
    @RequestMapping(path = "/testModelAndView")
    public ModelAndView testModelAndView(){
        ModelAndView mv = new ModelAndView();
        User user = new User();
        user.setUsername("cc");
        user.setPassword("888");
        user.setAge(20);
        //1.把user对象存储到mv中,mv会存到request域中
        mv.addObject("user",user);
        //2.跳转页面
        mv.setViewName("success");
        return mv;
    }

利用SpringMVC提供的关键字进行请求转发或者重定向

	/**
     * 利用关键字进行请求转发或者重定向
     * @return
     */
    @RequestMapping(path = "/testForwardOrRedirect")
    public String testForwardOrRedirect(){
        System.out.println("testForwardOrRedirect执行了");
        //1.请求转发
        //return "forward:/WEB-INF/pages/success.jsp";
        //2.重定向
        return "redirect:/index.jsp";
    }

ResponseBody响应json数据

项目准备

  1. 利用ajax向服务器发送json数据,需要在jsp页面上引入JQuery,而DispatcherServlet会拦截所有的资源,静态资源(js、css、imsges)也会被拦截到,导致不能使用,解决办法是配置静态资源不进行拦截,在resources目录下的SpringMVC.xml中添加配置

    <!--配置前端控制器,哪些静态资源不拦截-->
        <mvc:resources location="/js/" mapping="/js/**"/>
        <mvc:resources mapping="/css/" location="/css/**"/>
        <mvc:resources mapping="/images/" location="/images/**"/>
    
  2. 要将json字符串与实体类对象进行转换,需要导入jackson的jar包,在pom.xml中添加依赖坐标

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.9.0</version>
    </dependency>
    <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>
    

在jsp页面利用ajax发送json数据

<script src="js/jquery-3.4.1.min.js"></script>
    <script>
        $(function () {
           $('#btn').click(function () {
              //发送ajax请求
               $.ajax({
                   url:"user/testAjax",
                   contentType:"application/json;charset=UTF-8",//文件上传类型
                   data:'{"username":"chenpeng","password":"666","age":20}',//json数据
                   dataType:"json",//返回的数据类型
                   type:"post",//请求的方式
                   success:function (data) {//成功后的自调函数
                       //data服务器端响应的json的数据,进行解析
                       alert(data);
                       alert(data.username);
                       alert(data.password);
                       alert(data.age);
                   }
               });
           });
        });
</script>

在控制器类中使用@ResponseBody注解将json字符串转换成实体类对象

@RequestMapping(path = "/testAjax")
    public @ResponseBody User testAjax(@RequestBody User user){
        System.out.println("testAjax执行了");
        System.out.println(user);
        user.setUsername("cc");
        user.setPassword("123456");
        return user;
    }
原文地址:https://www.cnblogs.com/codeDD/p/12699115.html