1.controller层
//注册检查用户名是否存在
@RequestMapping("/checkregister")
public void checkregister(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
Map<String, Object> map = new HashMap<String, Object>();
User user = userService.queryUser(username);
if (user != null) {
map.put("userExist", true);
map.put("msgInfo", "用户名已存在");
} else {
map.put("userExist", false);
map.put("msgInfo", "用户名可以使用");
}
ObjectMapper om = new ObjectMapper();
om.writeValue(response.getWriter(), map);
}
2.mapper层
@Select("select * from user where username=#{username}")
public User queryUser(String username);
3.service层
//查询数据库中该用户是否存在
public User queryUser(String username);
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public User queryUser(String username) {
return userMapper.queryUser(username);
}
}
4.jsp页面
<form method="post" action="<%=path%>/houseWeb/register">
<h2>立即注册</h2>
<label>
<span>用户名</span>
<input type="text" id="u_loginName" name="username" required>
<span id="msg0"></span>
</label>
<label>
<span>密码</span>
<input type="password" id="password" name="password" required>
</label>
<label>
<span>再次输入密码</span>
<input type="password" id="newPassword" name="newPassword" required onkeyup="checkPassword()">
</label>
<div id="msg3"></div>
<button type="submit" class="submit" id="btn">注 册</button>
<span style="color: red">${msg1}</span>
</form>
<script>
function checkPassword() {
var password = document.getElementById("password").value; //js语法
var newPassword=document.getElementById("newPassword").value;
// var password = $("#password").value;//jquery语法
// var newPassword = $("#newPassword").value;
if (password != newPassword) {
document.getElementById("msg3").innerHTML = "<span style='color: red'>两次密码不一致</span>";
document.getElementById("btn").disabled = true;
} else {
document.getElementById("msg3").innerHTML = "<span style='color: green'>两次密码一致</span>";
document.getElementById("btn").disabled = false;
}
}
$(function () {
//id为usernameTag的输入框失去焦点后触发
$("#u_loginName").blur(function () {
var username = $(this).val();
var msg = $("#msg0");
//如果用户名为空则不判断,并清空之前判断的提示信息
if(username == ''){
msg.html(null);
return false;
}
//data里存放的是后台返回给前端的数据
$.post("checkregister",{"username":username},function (data) {
if(data.userExist){
msg.html(data.msgInfo);
msg.css("color","red");
//若用户名存在则提交按钮禁止点击
document.getElementById("button").disabled = true;
}else {
msg.html(data.msgInfo);
msg.css("color","green");
//若用户名不存在则提交按钮可以点击
document.getElementById("button").disabled = false;
}
},"json");
});
});
</script>