项目包链接:https://pan.baidu.com/s/1qRgXl2rVlgpEZ9z2V1Mjrg 提取码:bk8z
1.登录实现
mapper接口:
Employee login (@Param("username")String username,@Param("password")String password);
mapper.xml:
<select id="login" resultMap="BaseResultMap">
select id, username, admain from employee where username=#{username} and password=#{password}
</select>
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";
}
}
页面:
<body>
<form action="/login.do">
<span style="color:red">${errorMsg}</span>
<table>
<tr>
<td>用户名:<input type="text" name="username" /></td>
</tr>
<tr>
<td>密 码:<input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" name="登录" /></td>
</tr>
</table>
</form>
</body>
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配置
<!-- 注册拦截器 -->
<mvc:interceptors>
<!-- 注册1个拦截器 -->
<mvc:interceptor>
<!-- 对哪些资源起拦截作用 -->
<mvc:mapping path="/**" />
<!-- 对哪些资源不起拦截作用 -->
<mvc:exclude-mapping path="/login.do" />
<!-- 哪个Bean是拦截器 -->
<bean class="cn.wolfcode.ssm.web.interceptor.CheckLoginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>