简单AJAX实现用户登陆验证
1.配置SpringMVC框架
配置application.xml三要素,以及
<!--json乱码问题配置-->
<context:component-scan base-package="com.lss.Controller"/>
<!--json乱码问题配置-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
2.编写jsp页面代码
<form>
用户:<input type="text" id="name" onblur="a1()">
<span id="username"></span><br>
密码:<input type="password" id="pwd" onblur="a2()">
<span id="userpwd"></span><br>
</form>
3.编写JQuery触发事件函数,编写AJAX
<script src="${pageContext.request.contextPath}/static/js/jquery-1.4.2.js"></script>
<script>
function a1() {
$.ajax({
url:"${pageContext.request.contextPath}/aaa",
data:{"name":$("#name").val()},
success:function(data) {
if (data.toString()==="ok") {
$("#username").css("color","green");
}else {
$("#username").css("color","red");
}
$("#username").html(data);
}
})
}
function a2() {
$.ajax({
url:"${pageContext.request.contextPath}/aaa",
data:{"pwd":$("#pwd").val()},
success:function(data) {
if (data.toString()==="ok") {
$("#userpwd").css("color","green");
}else {
$("#userpwd").css("color","red");
}
$("#userpwd").html(data);
}
})
}
</script>
路径直接返回到Controller层进行数据交互
3.记得添加注解 @ResponseBody,表明不用进行视图解析,直接返回字符串
@RequestMapping("/aaa")
@ResponseBody
public String test3(String name,String pwd){
String msg="";
if (name!=null){
if (name.equals("lss")){
msg="ok";
}else {
msg="用户名有误";
}
}
if (pwd!=null){
if (pwd.equals("666")){
msg="ok";
}else {
msg="密码有误";
}
}
return msg;
}