Need to analyze:
a login interface login.jsp, if the login is successful, jump to main.jsp, if the login is unsuccessful, redirect the login page.
In addition, main.jsp cannot be accessed when not logged in, and can be accessed directly after login
specific methods:
- First there is a login.jsp
- User (id, username, password), mapper, service, etc. will not be mentioned (Impl provides a method to query user based on username and password)
- In order that main.jsp cannot be accessed directly when it is not logged in, only JSP can operate on JSP requests through servlet, so write a restful-style controller method to make all requests pass (don’t worry about request conflicts, springmvc will choose the most accurate method)
- When the interceptor intercepts the request, let go of all non-jsp requests (such as login, by judging req.geturi), and then the rest are all jsp requests. If there is a value in the session, return true, and if there is no value, it will be repeated. Directional return false
- For the login request, if it succeeds, it redirects main, and if it fails, it redirects login
login.jsp
<form action="login" method="post">
用户名:<input type="text" name="username">
密码:<input type="password" name="password">
<input type="submit" value="登录">
controller
@Controller
public class LoginController {
@Resource
private LoginService loginServiceImpl;
//restful风格+视图解析器
@RequestMapping("{page}")
public String demo(@PathVariable("page")String page) {
return page;
}
@RequestMapping("login")
public String login(User user,HttpSession session){
User u = loginServiceImpl.selLogin(user);
if(u!=null){
//跳转到main.jsp
session.setAttribute("user", u);
return "main";
}else{
return "redirect:/login.jsp";
}
}
}
interceptor
public class LoginInterceptor implements HandlerInterceptor{
@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object arg2) throws Exception {
// TODO Auto-generated method stub
String uri = req.getRequestURI();
if(uri.equals("/springmvc/login")){
return true;
}
else{
Object object = req.getSession().getAttribute("user");
if(object!=null){
return true;
}
res.sendRedirect("/springmvc/login.jsp");
return false;
}
}
//jsp之前
@Override
public void postHandle(HttpServletRequest req, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest req, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
}