登录功能(spring 的拦截器)
select * from t_user where uername=? and password=?
1.0 登录的功能
1.获取前台传过来的用户名和密码
2.根据用户名密码在数据库中查询当前登录用户
3.查询成功返回一个User对象->存入session中(HttpSession session),跳转到主页面
如果没成功->跳转到登录页面,并返回错误的用户名和密码
1.1 登录的拦截
创建一个和controller平级的包,里面创建一个class(LoginInterceptor)实现HeadlerInterceptor接口
LoginInterceptor.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.itsource.cms.domain.User;
public class LoginInterceptor<T> implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
// 拦截时要完成的功能
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
// 拦截完要完成的功能
}
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object arg2) throws Exception {
// TODO Auto-generated method stub
//拦截前
HttpSession session = req.getSession();
T loginUser = (T) session.getAttribute("loginUser");
if (loginUser == null) {
resp.sendRedirect("/login");
return false;
}
return true;
}
}
UserControler.java
@RequestMapping("/login")
public String loginUser(User user, HttpSession session,Model model) {
User us = userService.login(user);
session.setAttribute("loginUser", us);
if(us!=null){
return "redirect:/images/index";
}
model.addAttribute("user",user);
return "forward:/login";
}
拦截器
<mvc:interceptors>
<mvc:interceptor>
<!--拦截哪些請求-->
<mvc:mapping path="/**"/>
<bean class="cn.itsource.cms.web.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>