1.我的项目采用的是springboot框架和thymeleaf模板引擎,前端的逻辑控制用的是jquery,并用ajax进行异步请求
2.为了保持会话登录状态,我采用了拦截器来实现session判别
3.首先,定义我们自己的拦截器,这个拦截器要实现HandlerInterceptor接口,代码如下:
package server.demo.configure;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import server.demo.entity.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
//获取当前的session
HttpSession session=request.getSession();
//从session中寻求cur_user变量
Object obj=session.getAttribute("cur_user");
//判断是否存在用户变量
//不存在则跳转到登录界面
if(obj==null||!(obj instanceof User)){
response.sendRedirect("/login");
}else{
//存在则再次注入session
session.setAttribute("cur_user",(User)obj);
System.out.println(((User) obj).getName()+((User) obj).getPassword());
}
return true;// 只有返回true才会继续向下执行,返回false取消当前请求
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}
4.然后,就要将拦截器进行注册,代码如下:
package server.demo.configure;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
@Autowired
MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 多个拦截器组成一个拦截器链
// addPathPatterns 用于添加拦截规则
// excludePathPatterns 用户排除拦截
List list=new ArrayList<>();
list.add("/myPub");
list.add("/myRec");
registry.addInterceptor(myInterceptor).addPathPatterns(list);
super.addInterceptors(registry);
}
}
5.编写登录验证函数
@RequestMapping(value = "/check" ,method = RequestMethod.POST)
@ResponseBody
public String check(@RequestBody JSONObject json ){
System.out.println("收到前端ajax请求");
String name=json.getString("name");
String password=json.getString("password");
User user=new User();
user.setName(name);
user.setPassword(password);
//向后台数据库查询用户id
int id=userService.login(user);
//如果id争取,则传回信息
if(id>0){
//
user.setId(id);
session.setAttribute("cur_user",user);
System.out.println("传回正确信息");
return "1";
}else{
System.out.println("传回错误信息");
return "0";
}
}
6.对应的ajax为:
function login() {
var name=$("#name").val();
var password=$("#password").val();
var info={"name":name,"password":password};
$.ajax({
url:"/check",
type:"post",
data:JSON.stringify(info),
dataType:"json",
contentType:"application/json",
error: function (data) {
alert(data);
},
success:function (data) {
alert("登录成功");
window.location.href="/main";
}
});
}
7.这样每次访问页面,拦截器都会查看这些页面是否是注册要拦截的,如果是,就执行拦截器,也即是判断session中是否有用户的状态信息,如果有,则进行正确访问,如果没有,则跳转到登录页面让用户进行登录