SpringMVC中的ajax异步请求处理
控制类
package com.mvc.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@Scope("prototype")
@RequestMapping("aj")
public class AjaxController {
@RequestMapping("/t1")
@ResponseBody //这个一定要写,不能省略
**********************************************************************
@responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,
写入到response对象的body区,通常用来返回JSON数据或者是XML数据,需要注意的呢,
在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
注意:在使用此注解之后不会再走视图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
**********************************************************************
public void test1(HttpServletRequest request,HttpServletResponse response) throws IOException{
String userName=request.getParameter("userName");
//输出中文流
response.setCharacterEncoding("utf-8");
//判断数据是否合法
if(userName!=null && userName!="" && userName.matches("[a-z0-9A-Z]{3,}")){
response.getWriter().print("用户名【"+userName+"】合法");
}else{
response.getWriter().print("用户名【"+userName+"】不合法");
}
}
}
ajax异步请求
<script type="text/javascript">
$(function(){
$('#form1').submit(function(){
$.ajax({
url:'aj/t1',
type:'post',
data:'userName='+$('#userName').val(),
dataType:'text',
success:function(ret){
alert(ret)
}
})
})
})
</script>