关于SpringMVC重定向和Json字符串

来源:互联网 发布:淘宝店铺怎么改地址 编辑:程序博客网 时间:2024/06/06 08:38

在SpringMVC的使用中我们有时候需要重定向,该怎么设置呢?

控制器对视图的处理方式默认是请求跳转,如果要重定向的话,需要在返回的字符串里修改。

比如跳转:

return "list";
重定向则是:

return "redirect:list.jsp";

Web开发中经常用到Ajax技术,SpringMVC要怎么处理返回的json数据呢?

SpringMVC中提供了@ResponseBody注解,让我们很方便的返回json数据

例:

package demo.controller;import java.util.ArrayList;import java.util.List;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;@Controller//注册bean@RequestMapping("/")//通过此注解来为这个类映射一个URL,具体请求方法也配置路径则映射的路径为两者路径的叠加public class ProvinceAnnotationController {@ResponseBody@RequestMapping("/find.do")public List<String> find(){    List<String> list = new ArrayList<String>();       list.add("1111111");    list.add("2222");    list.add("3333333");    list.add("44444444");    list.add("55555");    return list;}}


另外,使用注解需要在配置文件中加入<mvc:annotation-driven />这句,它提供了读取jason的支持,还需要相应的两个包:



新建测试页面find.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>        <title>My JSP 'find.jsp' starting page</title><script type="text/javascript" src="js/jquery-1.8.1.js"></script><script type="text/javascript">$(function(){$.ajax({dataType:"json",success:function(data){for(var i in data){$("#pro").append("<li>"+data[i]+"</li>");}},type:"post",url:"find.do"});});</script>  </head>    <body>    <ul id="pro"></ul>  </body></html>

接着就是访问地址了:http://localhost:8080/TestSpringMVC/find.jsp

结果




0 0
原创粉丝点击