登录验证代码
package security;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.User;
@WebServlet("/login.do")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String ERROR_VIEW = "admin-login.jsp";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");//从地址栏获取用户名
String password = request.getParameter("password");//从地址栏获取密码
//判断用户名密码是否正确
if(username.equals("user") && password.equals("88888")) {
HttpSession session = request.getSession(true);
//密码正确则设置一个session
session.setAttribute("user", new User(username,password));
putCookie(request,response,username);
//跳转到后台界面
request.getRequestDispatcher("console/admin.jsp").forward(request, response);
}else {
request.getRequestDispatcher(ERROR_VIEW).forward(request, response);
}
}
private void putCookie(HttpServletRequest request, HttpServletResponse response, String username) {
String value = request.getParameter("login");
//设置一个cookie
if ("auto".equals(value)) {
Cookie cookie = new Cookie("user", username);
cookie.setMaxAge(7 * 24 * 60 * 60);
response.addCookie(cookie);
}
}
}
2.过滤器安全验证代码
package security;
/**
* @author 鐜嬭儨鍗?
*/
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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
//过滤以/console/,/admin/开头的请求
@WebFilter(urlPatterns = { "/console/*", "/admin/*" }, initParams = {
@WebInitParam(name = "INDEX_VIEW", value = "/index.jsp") })
public class MemberFilter implements Filter {
private String INDEX_VIEW;
@Override
public void init(FilterConfig config) throws ServletException {
this.INDEX_VIEW = config.getInitParameter("INDEX_VIEW");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (ObjectUtils.anyNotNull(req.getSession().getAttribute("user"))) {
chain.doFilter(request, response);
} else {
HttpServletResponse resp = (HttpServletResponse) response;
resp.sendRedirect(req.getContextPath() + INDEX_VIEW);
}
}
@Override
public void destroy() {
}
}