SpringMVC跳转页面和响应数据

2,442 阅读2分钟

跳转页面

无返回值方法

对于无返回值方法,我们可以使用HttpServletResponse和HttpServletRequest中的重定向和转发来实现页面跳转。

转发示例

@Controller
@RequestMapping(path = "/testReturn")
public class ResoponseAndResController {
    @RequestMapping(path = "/returnVoid")
    public void testReturnVoid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        req.getRequestDispatcher("/WEB-INF/views/success.jsp").forward(req, resp);
    }
}

放在day2.jsp中的请求链接

 <a href="testReturn/returnVoid">无返回方法跳转</a>

点击请求后的链接变为:

重定向示例

@Controller
@RequestMapping(path = "/testReturn")
public class ResoponseAndResController {
    @RequestMapping(path = "/returnVoid")
    public void testReturnVoid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
//        重定向无法跳到WEB-INF里的页面,即无法跳到/WEB-INF/views/success.jsp
        resp.sendRedirect(req.getContextPath() + "/AnoSuccess.jsp");
    }
}

请求连接不变,点击请求后URL变为:

上述示例的视图结构为:

ModelAndView

ModelAndView是Spring MVC为我们提供的一个类,它有两个方法:

public ModelAndView addObject(Object attributeValue) {
        this.getModelMap().addAttribute(attributeValue);
        return this;
}

public void setViewName(@Nullable String viewName) {
        this.view = viewName;
}

示例

@Controller
@RequestMapping(path = "/testReturn")
public class ResoponseAndResController {
    @RequestMapping(path = "/testModelAndView")
    public ModelAndView testModelAndView() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("uname", "on1");
        mav.setViewName("success");
        return mav;
    }
}

放在day2.jsp中的请求链接:

<a href="testReturn/testModelAndView">测试ModelAndView</a><br>

跳转到的success页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>成功</title>
</head>
<body>
    <h3>成功跳转到此页面</h3>
    ${requestScope.uname}
</body>
</html>

输出:

有返回值方法

除了前面提到的通过方法参数的Servlet来实现重定向和转发,我们还可以通过返回字符串来实现重定向和转发。

示例

@Controller
@RequestMapping(path = "/testReturn")
public class ResoponseAndResController {

    @RequestMapping(path = "/testRedirect")
    public String testRedirect() {
        System.out.println("testRedirect方法执行");
        return "redirect:testModelAndView";     //上例中的ModelAndView
    }

    @RequestMapping(path = "testForward")
    public String testForward() {
        System.out.println("testForward方法执行");
        return "forward:/WEB-INF/views/success.jsp";
    }

放在day2.jsp中的请求链接:

<a href="testReturn/testForward">带返回值的转发</a><br>
<a href="testReturn/testRedirect">带返回值的重定向</a><br>

输出:

响应数据

响应json数据

示例

@Controller
@RequestMapping(path = "/testReturn")
public class ResoponseAndResController {
    @RequestMapping(path = "/testAjax")
    public void testAjax(@RequestBody String body) {
        System.out.println(body);
    }
}

day2.jsp

<html>
<head>
    <title>第二章</title>
    <script src="js/jquery.min.js"></script>
    <script>
        //页面加载,绑定点击事件
        $(function () {
            $("#btn").click(function () {
                //发送ajax请求
                $.ajax({
                    //编写json格式数据
                    url:"testReturn/testAjax",
                    contentType:"application/json;charset=UTF-8",
                    data:'{"id":11, "uname": "on1","age":"20",}',
                    dataType:"json",
                    type:"post",
                    success:function (data) {
                        //data是服务器响应的json的数据
                    }
                })
            });
        });
    </script>
</head>
<body>
    <button id="btn">发送ajax请求</button>

</body>
</html>

在springmvc.xml添加配置:

<!--    设置哪些静态资源不会被前端控制器拦截-->
    <mvc:resources location="/css/" mapping="/css/**"/> <!-- 样式 -->
    <mvc:resources location="/images/" mapping="/images/**"/> <!-- 图片 -->
    <mvc:resources location="/js/" mapping="/js/**"/> <!-- javascript -->

运行后点击按钮即可看到运行台上的输出

返回json数据

导入依赖:

    <!--    SprngMVC解析和封装json-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.10.2</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.10.2</version>
    </dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.10.2</version>
    </dependency>
@Controller
@RequestMapping(path = "/testReturn")
public class ResoponseAndResController {

    @RequestMapping(path = "/returnJson")
    public @ResponseBody User returnJson(@RequestBody User user) {
        System.out.println(user);
//        修改数据
        user.setUname("C2y");
        user.setAge(18);
        return user;
    }
}

添加day2.jsp中的部分:

success:function (data) {
    //data是服务器响应的json的数据
    alert(data.toString());
    alert(data.id);
    alert(data.uname);
    alert(data.age);
}