你好,我现在要做个登录界面,有用户的用户名、密码和验证码。验证码暂时不考虑,随便输什么都可以,只考虑用户名和密码两样,如何实现登录。
功能:
1、如果用户名错误,数据库没有用户名,则显示没有该用户
2、如果用户名正确,输入的密码与数据库里的密码不符合,则显示密码输入错误
3、如果用户名和密码都输入正确,则正常登录到index.html页面。
这里用了ajax来传输表单的数据。
那么如何运用SpringBoot和ajax来实现登录功能呢?
这是登录页面的HTML代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<style type="text/css">
#log{
position: absolute;
top: 50%;
left: 50%;
margin-left: -10%;
margin-top: -10%;
}
</style>
</head>
<body>
<div style="width: 30%;height: 30%" id="log">
<img src="/image/saturn.png" height="34%" width="34%"/>
<form id="login" name="login" th:object="${pwd}" method="post"> <!--th:action="@{/loginyanzheng}"-->
<label>用户名</label>
<input type="text" id="username" name="username" style="font-size: 18px"></input><br>
<label>密码</label>
<input type="password" id="passwords" name="passwords" style="font-size: 18px;margin-left: 16px"></input><br>
<label>验证码</label>
<input type="text" id="yanzheng" name="yanzheng" style="font-size: 18px"></input><br>
<div>
<input type="button" id="sub" value="确认" style="font-size: 18px"></input>
<input type="button" id="yz" value="验证码" style="font-size: 18px"></input>
<input type="button" id="exit" value="退出" style="font-size: 18px"></input>
</div>
</form>
</div>
<script type="text/javascript">
$("#sub").click(function (event) {
var a= $("#username").val();
var b=$("#passwords").val();
var c=$("#yanzheng").val();
console.log(a+"#"+b+"#"+c);
$.ajax({
type: 'post',
url: './login1',
async: true,
error: '重新请求',
contentType: "application/json;charset=utf-8",
type: 'json',
data: {
"userName":$("#userName").val(),"passwords":$("#password").val(),"yanzheng":$("#yanzheng").val(),
},
success: function (res) {
},
error: function (res) {
}
})
})
</script>
</body>
</html>
这是后台Controller的代码
@Controller
public class Controller3 {
@RequestMapping("/login")
@ResponseBody
public Model login(Model mp){
//mp.addAttribute("pwd",new Pwd());
//System.out.println(pwd.getUsername());
return mp;
}
@PostMapping("/login1")
@CrossOrigin
@ResponseBody
public String loginresult(@RequestParam("username")String username,@RequestParam("passwords")String passwords,
@RequestParam("yanzheng")String yanzheng){
System.out.println(username+"#"+passwords+"#"+yanzheng);
return "success";
}
}
如何实现这一功能呢?注意,不要跳转到/login1页面,不要跳转。
但问题是后端的信息,就是login1下的System.out.println(username+"#"+passwords+"#"+yanzheng);这个信息,没有执行到,打印不了相应的信息,包括用户名、密码、验证码信息,这是为什么?
另外,如果输入正确,自动跳转到index.html页面,应该怎么办?