spring2.5 mvc 以及spring3.0 mvc ajax+json

闲来无事学习了一下spring mvc 以及2.5、3.0  json使用的差异

spring 2.5 json传输方式

@RequestMapping(value="/judge.do",method=RequestMethod.POST)
	public   void judge(String username,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String name = request.getParameter("username");
		PrintWriter pwPrintWriter;
		UserInfo user=null;
		 user = new UserInfo();
			user.setUsername(name);
			JSONObject jsonObject = new JSONObject();
			//user是key-value方式
			//前台获取的时候采用msg.user.username
			jsonObject.put("user", user);
		try {
			pwPrintWriter=response.getWriter();
			if("upxiaofeng".equals(name)){
				pwPrintWriter.print(jsonObject.toString());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

前台代码:

function judge(){
  		var name = document.getElementById("username").value;
    		$.ajax({
			type:"POST",//提交方式
			cache:false,//不适用cookies
			dataType:"json",
			url:"/SpringMvc/judge.do", 
			data:{username:name},//传入到servlet的值
			//如果成功就执行下面的代码
			success:function(msg){
				var html="<font color='red'>";
					if("y"==msg){
						html+=msg.user.username+"*用户名已存在,该用户名不可用";
					}else{
						html+=msg.user.username+"*用户名可用";
					}
				html=html+"</font>";
				$("#judge").html(html);//将生成的html显示到页面上   等价  document.getElementById("dataid").innerHTML=html;
			},
			error:function(){
				alert("找不到URL");
			}
		});
  	}

spring 3.0相对要简单多而且也很方便

<pre class="html" name="code">@RequestMapping(value="/judge.do",method=RequestMethod.POST)
	public @ResponseBody  UserInfo judge(String username,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		String name = request.getParameter("username");
		UserInfo user=new UserInfo();		
		user.setUsername(name);
	return user;
	}

function judge(){
  		var name = document.getElementById("username").value;
  		alert(name);
  		$.ajax({
			type:"POST",//提交方式
			cache:false,//不适用cookies
			dataType:"json",
			url:"/SpringMvc/judge.do", 
			data:{username:name},//传入到servlet的值
			//如果成功就执行下面的代码
			success:function(msg){
				var html="<font color='red'>";
					html+=msg.username+"*用户名已存在,该用户名不可用";
					html=html+"</font>";
				$("#judge").html(html);//将生成的html显示到页面上   等价  document.getElementById("dataid").innerHTML=html;
			},
			error:function(){
				alert("找不到URL");
			}
		});
  	}





 

你可能感兴趣的:(Ajax,json,springMVC)