

package com.imooc.controller;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.imooc.bean.AdminUser;
import com.imooc.utils.IMoocJSONResult;
@Controller
@RequestMapping("/users")
public class UserController {
@GetMapping("/login")
public String login() {
return "login";
}
@PostMapping("/login")
public IMoocJSONResult login(String username, String password,
HttpServletRequest request, HttpServletResponse response) {
if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return IMoocJSONResult.errorMsg("用户名或密码不能为空!");
}else if(username.equals("lee") && password.equals("lee")) {
String userToken = UUID.randomUUID().toString();
AdminUser user = new AdminUser(userToken, username);
request.getSession().setAttribute("sessionUser", user);
return IMoocJSONResult.ok();
}
return IMoocJSONResult.errorMsg("登录失败,请重试!");
}
@GetMapping("/logout")
public String logout(HttpServletRequest request) {
request.getSession().removeAttribute("sessionUser");
return "login";
}
}
这是login.js中的部分代码
submitHandler: function(form) {
var loginForm = $('.login-form');
var hdnContextPath = $("#hdnContextPath").val();
$.ajax({
type: "post", // 提交方式 get/post
url: hdnContextPath + '/users/login.action', // 需要提交的 url
data: loginForm.serialize(),
dataType: "json",
success: function(res) {
debugger
// 登录成功或者失败的提示信息
if (res.status == 200 && res.msg == "OK") {
window.location.href = hdnContextPath + "/center.action";
} else {
// SweetAlert.error(data.msg);
alert(res.msg);
}
}
});
}