关于SpringMVC重定向和Json字符串

在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值