SSM之功能 登录功能 + 拦截器 实现登陆校验

项目包链接:https://pan.baidu.com/s/1qRgXl2rVlgpEZ9z2V1Mjrg 提取码:bk8z

1.登录实现

mapper接口:

Employee login (@Param("username")String username,@Param("password")String password);

mapper.xml:


service 接口:

void login (String username,String password);

service实现:

@Override
	public void login(String username, String password) {
		Employee employee=mapper.login(username, password);
		if(employee==null){
			throw new RuntimeException("用户名或密码错误");
		} 
		//登陆成功 将用户信息存入session 这里通过使用一个工具类实现将用户信息放入session,这样做的目的是解耦
		UserContext.setCurrentUser(employee);
	}	

工具类

public class UserContext {
	private UserContext(){};

	public static final String EMP_IN_SESSION="EMP_IN_SESSION";
	
	public static void setCurrentUser(Employee emp){
		getSession().setAttribute("EMP_IN_SESSION", emp);
	    
	}
	
	public static Employee getCurrentUser(){
		return (Employee) getSession().getAttribute(EMP_IN_SESSION);
	    
	}
	
	
	public static HttpSession getSession(){
		ServletRequestAttributes attrs=(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return attrs.getRequest().getSession();
	}
}

controller层:

@Controller
public class LoginController {
	@Autowired
	private IEmployeeService service;
	@RequestMapping("/login")//登录
	public String login(String username,String password,Model model){
		String viewName="redirect:/employee/findAll.do";
		try {
			service.login(username, password);
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("errorMsg", e.getMessage());
			viewName="forward:/login.jsp";
		}
		return viewName;
	}
	@RequestMapping("/loginOut")//退出登录实现
	public String loginOut(HttpSession session){
	//銷毀session
	session.invalidate();
	return "redirect:/login.jsp";
}
}

页面:


	
${errorMsg}
用户名:
密 码:

2.登录拦截实现

拦截器:用户在没有登录的情况下不允许访问主页

CheckLoginInterceptor

//    一个类继承了HandlerInterceptorAdapter类或是实现了HandlerInterceptor接口就成为了一个拦截器
public class CheckLoginInterceptor extends HandlerInterceptorAdapter{
    	public boolean  preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
    		//判断当前用户是否登录,已登录则放行,没登录则不放行,并且回到登录界面
    		//session中无对象表示未登录
    		if (UserContext.getCurrentUser() == null) {
    			//没有登录则不放行,并且回到登录界面
    			response.sendRedirect("/login.jsp");
    			return false;
    		}
    		return true; //已登录则放行
    	}
    }

applicationContext.xml配置



	
	
		
		
		
		
		
		
	

你可能感兴趣的:(ssm)