Version: Next
AJAX验证用户名
login.jsp
- 先把页面画好
<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script><script>function validName() {}function validPassword() {}</script></head><body><p>用户名 : <input type="text" id="nameId" onblur="validName()"><span id="userInfo"></span></p><p>密 码 : <input type="password" id="passwordId" onblur="validPassword()"><span id="passwordInfo"></span></p></body></html>Controller
@RequestMapping("/a3")@ResponseBodypublic String a3(String name, String password) {String msg = "";if (name != null) {if ("jack".equals(name)) {msg = "用户名已被注册";} else {msg = "恭喜您,用户名可用";}}if (password != null) {if ("123456".equals(password)) {msg = "密码符合要求";} else {msg = "抱歉,密码必须为纯数字";}}return msg;}在页面添加AJAX
<script>function validName() {$.post("${pageContext.request.contextPath}/a3", {name: $("#nameId").val()},function(data) {if (data==='恭喜您,用户名可用'){$("#userInfo").css("color","green");}else{$("#userInfo").css("color","red");}$("#userInfo").html(data);})}function validPassword() {$.post("${pageContext.request.contextPath}/a3", {password: $("#passwordId").val()},function(data) {if (data==='密码符合要求'){$("#passwordInfo").css("color","green");}else{$("#passwordInfo").css("color","red");}$("#passwordInfo").html(data);})}</script>修改springmvc_servlet.xml解决Json中文乱码问题
<mvc:annotation-driven><mvc:message-converters register-defaults="true"><bean class="org.springframework.http.converter.StringHttpMessageConverter"><constructor-arg value="UTF-8"/></bean><beanclass="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"><property name="objectMapper"><beanclass="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"><property name="failOnEmptyBeans" value="false"/></bean></property></bean></mvc:message-converters></mvc:annotation-driven>