springMVC - 响应 - 跳转页面

jsp部分:页面为success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java"  isELIgnored="false" %>
<html>
<head>
    <title>success</title>
</head>
<body>
<div>
    <div>
        <h1>用户信息</h1>
    </div>
    <div>
        姓名: ${user.name}
    </div>
    <div>
        年龄: ${requestScope.user.age}
    </div>
</div>



</body>
</html>

1. 利用字符串

    //返回String
    @RequestMapping(path = "/stringTest")
    public String stringTest(Model model){
        //从数据库中查询到需要显示的值
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        model.addAttribute("user", user);

        return "success";
    }

2. void

2.1. 使用request 用request域传值,

2.2. 用response重定向,

2.3. response.getWriter()  用输出流直接往网页里写内容

//void 如果没任何跳转操作,则会跳转到/response/voidTest
    @RequestMapping(path = "/voidTest")
    public void voidTest(HttpServletRequest request, HttpServletResponse response, String type){ //取到请求的api
        //从数据库中查询到需要显示的值
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        request.setAttribute("user", user);

        System.out.println("type = " + type);

        //这里是手动跳转,spring不会自动帮忙处理,所以需要写具体页面的全部路径,而且Model是spring中的类,所以这里用Model传值也不行了,只能利用request
        try {
            //利用request跳转
            if(type.equals("request")) {
                request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
            }

            //利用response重定向,跳转到这个方法后再发送请求跳转一次
            if(type.equals("response")) {
                response.sendRedirect(request.getContextPath() + "/response/stringTest"); //跳转到其他方法,可以跨项目,路径要写全。
                System.out.println(request.getContextPath() + "/response/stringTest");
            }

            //利用输出流直接打印内容
            if(type.equals("writer")){
                response.setContentType("text/html; charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().println("<html>\n" +
                        "<head>\n" +
                        "    <title>success</title>\n" +
                        "</head>\n" +
                        "<body>\n" +
                        "<div>\n" +
                        "    <div>\n" +
                        "        <h1>用户信息</h1>\n" +
                        "    </div>\n" +
                        "    <div>\n" +
                        "        姓名: " + user.getName() + "\n" +
                        "    </div>\n" +
                        "    <div>\n" +
                        "        年龄: " + user.getAge() + "\n" +
                        "    </div>\n" +
                        "</div>\n" +
                        "</body>\n" +
                        "</html>");
            }

        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

3.  利用responseBody 用json格式传值。

3.1配置环境

3.1.1 jquery:

导入jquery包 (直接粘贴进文件夹就行)

springMVC 配置文件中,一般都会拦截所有请求并交由spring处理,所以js包也会被拦截,因此需要修改springmvc.xml

 代码:

    <!-- 配置前端控制器不要拦截静态资源-->
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>

3.1.2 json

在pom.xml中的dependencies中添加spring处理json的依赖

    <!-- 转化json时使用的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>

3.2 代码

jsp部分

<div>
    <!-- 测试异步请求 --> <input type="button" value="测试ajax请求json和响应json" id="testJson"/>
</div>

<script type="text/javascript" src="/js/jquery.min.js"></script> 
<script type="text/javascript">
    //测试异步请求 代码
    $(function(){
        $("#testJson").click(function(){
            alert("发送请求");
            $.ajax({
                type:"post",                                                              //请求类型
                url:"${pageContext.request.contextPath}/response/responseJsonTest",   //请求地址
                contentType:"application/json;charset=utf-8",                        //防止中文乱码
                data:'{"name":"张三","age":20}',                                       //data里面是json格式的键值对
                dataType:"json",                                                         //返回的数据类型
                success:function(data){                                                   //这个是请求成功后执行的方法,data是接收的对象
                    alert("姓名:" + data.name + " 年龄:" + data.age);                     //弹窗显示返回的值,可以取到返回对象的属性
                }
            });
        });
    })
</script>

java的controller部分:

    //测试响应json数据
    @RequestMapping("/responseJsonTest")
    @ResponseBody   //把返回的对象转化为ajax,数据变为json格式传到前台
    public User responseJsonTest(@RequestBody User user) {   //获得请求体(json格式), 把json转成user对象, User中有name和age两个属性
        System.out.println("异步请求:" + user);
        user.setName("李四");
        user.setAge(31);
        System.out.println("返回请求:" + user);
        return user;
    }

猜你喜欢

转载自www.cnblogs.com/clamp7724/p/11727852.html