JavaWeb实现过滤器验证登录
**今天正好学到过滤器,就想着用博客记录下来,方便以后查找,也供大家参考,由于刚学,所以不足之处也请大家见谅。**
1、写一个类实现Filter接口:
public class Login implements Filter{
public void init(FilterConfig config) throws ServletException{
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException,ServletException{
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
HttpSession session = req.getSession();
//用来判断是否是从登录页登录,一些文章是直接判断是否有session,但这样如果登录成功后退回登录页重新登录,如果密码错误也会登录成功,因为此时session还在,就直接跳过验证登录成功了,所以这里我采用这种方法,直接判断是否是从登录页登录的。
String loginName = request.getParameter("loginName");//获取登录页的用户名和密码
String password = request.getParameter("password");
if(loginName!=null && password!=null){ //可以取到表单的信息,说明正在登录页验证登录
if("admin".equals(loginName) && "123456".equals(password)){
//验证通过
session.setAttribute("loginUser",loginName);
chain.doFilter(request, response);
}
else{ //用户名或密码错误
request.getRequestDispatcher("/index.html").forward(request, response);
}
}
else if(session.getAttribute("loginUser")!=null){
//不是从登录页进去的,但存在已登录过的标志,所以可以进去
chain.doFilter(request, response);
}
else {
//没有经过登录验证
request.getRequestDispatcher("/index.html").forward(request, response);
}
}
public void destroy() {
// TODO Auto-generated method stub
}
}
**这里需要注意的是,session本身是属于HTTP协议的范畴,但是doFilter()方法中定义的是ServletRequest类型的对象,那么要想取得session,则必须进行向下转型,将ServletRequest变为HttpServletRequest接口对象,才能通过getSession()方法取得session对象。**
2、配置文件web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>过滤器简单验证登录</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Login</filter-name>
<filter-class>cn.login.Login</filter-class><!-- 类所在的位置 -->
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
还没有评论,来说两句吧...