1.前台js:
var name = $("#name").val();
var pwd = $("#pwd").val();
$.ajax({
url:"login?name="+name+"&pwd="+pwd+"",
type:"post",
success:function(result){
if(result=="false"){
$("#error_msg").html("用户名或密码输入有误");
$('#error_msg').show();
return false;
}
if(result=="true"){
document.loginform.submit();
}
}
});
2.Controller:
@RequestMapping(value = "/login")
public String Verification(HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
User us = userService.findUserByname(name, pwd);
if (us.getName() == null && us.getPassword() == null){
out.print("false");
return null;
}else {
session.setAttribute("us", us);
out.print("true");
return null;
}
}
3. 后台service
public User findUserByname(String name, String pwd) {
String sql = "select * from user where name=? and password = ?";
User us = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), name,pwd);
return us;
}
注: 意思大家代码一看都明白了,就只是登陆ajax验证了。 问题在第3步,我输入的用户名密码错误,执行sql查不到数据就报错,可以怎样改一下,执行完第3步都返回到Controller,在第2步进行判断返回页面呢?(是不是我的方法有错呢,勿喷,学习Sping mvc ing.....)
try catch