后台登陆后 将用户名存入session
@Action(value = "denglu", results = { @Result(name = "success", type="chain", location = "denglu2",params={"admintity","%{admintity}"}), @Result(name = "error", location = "/admin/login.jsp") })
public String denglu(){
try {
//获取用户名密码,调用登陆的service
admintity = adminService.denglu(username,password);
if(admintity.getId() != 0){
//账号没问题,将用户名存入session
ActionContext ctx =ActionContext.getContext();
ctx.getSession().put("username", username);
return "success";
}else {
return "error";
}
} catch (Exception e) {
e.printStackTrace();
return FAIL;
}
}
后台每次调用方法前先进行请求拦截
用户存在 则继续 不存在则跳转登陆页
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.shareideals.domain.Admin;
public class AuthFilter implements Filter{
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse resp = (HttpServletResponse)response;
HttpServletRequest req = (HttpServletRequest)request;
HttpSession session = req.getSession();
String username = (String)session.getAttribute("username");
String uri = req.getRequestURI();
//简单判断缓存中是否有用户
System.out.println("开始过滤"+uri);
if(username==null){
//没有用户
System.out.println("用户未登录......");
//判断用户是否是选择跳到登录界面
/*if(uri.endsWith("/admin/login.jsp")||uri.endsWith("login.do")){
chain.doFilter(request, response);
}else{*/
//重定向跳转到登陆页
resp.sendRedirect(req.getContextPath()+"/admin/login.jsp");
}else{//有用户
System.out.println("用户已经登录......");
chain.doFilter(request, response);
}
// }
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
配置web.xml
<!-- 登录认证过滤器 -->
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.shareideals.action.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
//拦截三个控制器
<url-pattern>/products.action</url-pattern>
<url-pattern>/catalog.action</url-pattern>
<url-pattern>/selnews.action</url-pattern>
</filter-mapping>