javaweb项目开发案例 java项目开发案例经典( 二 )


{
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user=request.getSession().getAttribute(“loginUser”);
if(user==null)
{
//未登陆,返回登陆页面
request.setAttribute(“msg”,“没有权限请先登陆”);
request.getRequestDispatcher(“/index.html”).forward(request,response);
return false;
}
else
{
//已登陆,放行请求
return true;
}
}
@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 {
//登陆后,将之前存储在session里面的登录凭证销毁,无论是否存在凭证,都执行销毁操作
request.getSession().removeAttribute(“loginUser”);
}
}
2.如果登录成功,那么往session中存放一个username作为登录凭证【javaweb项目开发案例 java项目开发案例经典】@Controller
public class LoginController
{
@PostMapping(“/user/login”)
public String Login(@RequestParam(“username”)String username,
@RequestParam(“password”)String password
, Map map, HttpSession session)
{
if(username.equals(“大忽悠”)&&“123456”.equals(password))
{
session.setAttribute(“loginUser”,username);
//登录成功
return “redirect:/main.html”;
}
//登录失败
map.put(“msg”,“用户名或密码错误”);
return “index”;
}
}
3.在springmvc扩展类中将自定义的拦截器进行注册//使用WebMvcConfigurerAdapter可以来扩展SpringMvc的功能
@Configuration
public class myConfig extends WebMvcConfigurerAdapter
{
//所有的WebMvcConfigurerAdapter组件都会一起起作用
@Bean//将容器注册在容器中
public WebMvcConfigurerAdapter addViewControllers()
{
WebMvcConfigurerAdapter adapter=new WebMvcConfigurerAdapter() {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController(“/”).setViewName(“index”);
registry.addViewController(“/index.html”).setViewName(“index”);
registry.addViewController(“/main.html”).setViewName(“success”);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHanlderIntercept()).addPathPatterns(“/**”)//拦截任意多层路径下的所有请求
.excludePathPatterns(“/index.html”,”/”,”/user/login”);//某些请求不进行拦截
}
};
return adapter;
}
@Bean
//在SpringMVC扩展类中,将刚才写的区域信息解析器放到容器中
public LocaleResolver localeResolver()
{
return new MyLocaleResolver();
}
}
小细节:如果已经登录成功了,那么session域中就会存在已经登录的凭证,如果此时回退到登录页面,那么就可以不登录直接访问对应网页,这个的解决方法如下:使用下面这个解决方法的前提是拦截器只拦截登录页面,而不是所有请求,不然当登录成功后,点击当前页面的任何请求,都会回到登录页面@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//登陆后,将之前存储在session里面的登录凭证销毁,无论是否存在凭证,都执行销毁操作
request.getSession().removeAttribute(“loginUser”);
}
拦截器如果拦截所有请求,静态资源也会被拦截,因此注意排除掉对应的静态资源访问路径CRUD—员工列表

推荐阅读