SSM框架完成Ajax简单用户登录验证
一、前端JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Login</title>
</head>
<script type="text/javascript" src="statics/js/jquery-3.3.1.js"></script>
<script type="text/javascript">
function userLogin(){
$.ajax({
type : "post",
url : "checkLogin",
dataType:"json",
data:{
username:$("#username").val(),
password:$("#password").val()
},
success : function(data) {
if(data.code == "0"){
window.location.href = "JSP/welcome.jsp";
}else {
alert(data.errorInfo+"");
$("#showMessage").val(data.errorInfo+"");
}
}
});
}
</script>
<body>
用户名:<input type="text" name="username" id="username"/><br/>
密 码:<input type="password" name="password" id="password"/><br/>
<input type="button" name="login" value="登录" onclick="userLogin()"/><br/>
<textarea id="showMessage" style="border: none;"></textarea>
</body>
</html>
这里使用 window.location.href = "JSP/welcome.jsp" 完成Ajax里的重定向,而没有选择在Controller里返回视图
二、后台Controller
package myProject.Controller; import myProject.Model.User; import myProject.Service.UserService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @Controller public class LoginController { @Resource private UserService userService; @RequestMapping(value = "/checkLogin",method = RequestMethod.POST) @ResponseBody public Map userLoginCheck(HttpServletRequest request){ System.out.println("进入该方法"); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("request.getParameter "+username); System.out.println("request.getParameter "+password); Boolean result = checkLogin(username,password); Map<String, Object> map = new HashMap<>(); if (result) { map.put("code", 0); } else{ map.put("code", 1); map.put("errorInfo","登录失败,请重新登录"); } return map; } public boolean checkLogin(String username,String password){ User user = userService.getUserByName(username); if (user == null || "".equals(user)){ return false; } if (user.getUserPwd().equals(password)){ return true; }else { return false; } } }
三、测试结果
3.1 用户名和密码都正确


3.2 用户名或密码不正确

相关参考:http://www.cnblogs.com/boycelee/p/6243646.html
浙公网安备 33010602011771号