Servlet 过滤器Filter判断用户是否登陆(jsp页面)

原创 2014年06月25日 09:10:38

过滤器Servlet类:

package servlet;

import java.io.IOException;
//import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


	public class LoginFilter implements Filter {

		 private static final String LOGON_URI = "LOGON_URI";

		 private static final String REGISTER_URI = "REGISTER_URI";

		 private String logon_page;

		 private String register_page;

		 public void destroy() {
		 }

		 public void doFilter(ServletRequest request, ServletResponse response,
		   FilterChain chain) throws IOException, ServletException {
		  HttpServletRequest req = (HttpServletRequest) request;
		  HttpServletResponse resp = (HttpServletResponse) response;
		  resp.setContentType("text/html;");
		  resp.setCharacterEncoding("utf-8");
		  HttpSession session = req.getSession();
		 // PrintWriter out = resp.getWriter();
		  // 得到用户请求的URI
		  String request_uri = req.getRequestURI();
		  // 得到web应用程序的上下文路径
		  String ctxPath = req.getContextPath();
		  // 去除上下文路径,得到剩余部分的路径
		  String uri = request_uri.substring(ctxPath.length());
		  // 判断用户访问的是否是登录页面
		  if (uri.equals(logon_page) || uri.equals(register_page)) {
		   chain.doFilter(request, response);
		   return;
		  } else {
		   // 如果访问的不是登录页面,则判断用户是否已经登录
		   if (null != session.getAttribute("curUser")
		     && "" != session.getAttribute("curUser"))

		{
		    chain.doFilter(request, response);
		    return;
		   } 
		   else {
			   String   msg = "您未登录!";
	           String  url = "Errorer";
	             req.setAttribute("err", msg);
	             RequestDispatcher dis = req.getRequestDispatcher(url);
	  		     dis.forward(req, resp);
		   }
		    //out.println("<script language=/"javaScript/">"
		     // + "parent.location.href='" +

		//ctxPath + logon_page + "'"
		    //  + "</script>");
		   // return;
		  // }
		  }
		 }

		 public void init(FilterConfig config) throws ServletException {
		  // TODO Auto-generated method stub
		  // 从部署描述符中获取登录页面和首页的URI
		  logon_page = config.getInitParameter(LOGON_URI);
		  register_page = config.getInitParameter(REGISTER_URI);
		  // System.out.println(logon_page);
		  if (null == logon_page || null == register_page) {
		   throw new ServletException("没有找到登录页面或主页");
		  }
		 }

	}
修改Web核心配置文件:

注:保存后需要重启tomcat服务器

 <filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>servlet.LoginFilter</filter-class>
    <init-param>
          <param-name>LOGON_URI</param-name>
          <param-value>/login.jsp</param-value>
    </init-param>
    <init-param>
          <param-name>REGISTER_URI</param-name>
          <param-value>/register.jsp</param-value>
    </init-param>
  </filter>
<filter-mapping>
	<filter-name>charseterEncodingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
 <filter-mapping>
   <filter-name>loginFilter</filter-name>
   <url-pattern>*.jsp</url-pattern>
  </filter-mapping>
Errorer错误信息处理类:
package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Error
 */
public class Errorer extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)
			    throws ServletException, IOException {
			        response.setContentType("text/html;charset=UTF-8");
			        PrintWriter out = response.getWriter();
			        String url="login.jsp";
			        try {

			            out.println("<html>");
			            out.println("<head>");
			            out.println("<title>Servlet Error</title>");
			            out.println("</head>");
			            out.println("<body>");
			            out.println("<h2 align=center>" + request.getAttribute("err") + "</h2>");
			            response.setHeader("refresh", "2;url='login.jsp'");
			            response.setContentType("text/html;charset=UTF-8");
			            response.getWriter().write("请登录!页面将在3秒后自动跳转,如果没有,请点击<a href='login.jsp'>回到登录页面</a>");
			            out.println("</body>");
			            out.println("</html>");

			        } finally {
			            out.close();
			 		   RequestDispatcher dis = request.getRequestDispatcher(url);
					   dis.forward(request, response);
			        }
			    }

			    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
			    /** 
			     * Handles the HTTP <code>GET</code> method.
			     * @param request servlet request
			     * @param response servlet response
			     * @throws ServletException if a servlet-specific error occurs
			     * @throws IOException if an I/O error occurs
			     */
			    @Override
			    protected void doGet(HttpServletRequest request, HttpServletResponse response)
			    throws ServletException, IOException {
			        processRequest(request, response);
			    } 

			    /** 
			     * Handles the HTTP <code>POST</code> method.
			     * @param request servlet request
			     * @param response servlet response
			     * @throws ServletException if a servlet-specific error occurs
			     * @throws IOException if an I/O error occurs
			     */
			    @Override
			    protected void doPost(HttpServletRequest request, HttpServletResponse response)
			    throws ServletException, IOException {
			        processRequest(request, response);
			    }

			    /** 
			     * Returns a short description of the servlet.
			     * @return a String containing servlet description
			     */
			    @Override
			    public String getServletInfo() {
			        return "Short description";
			    }// </editor-fold>
}

效果展示:



相关文章推荐

使用servlet实现用户登录

关于使用servlet实现用户登录初探

Servlet——简单用户登录实例+http协议解析

本文写了一个简单的用户登录,并且介绍了http协议,主要介绍了http消息头和响应头。最后介绍了几个使用http响应头的例子。...
  • ggGavin
  • ggGavin
  • 2016年04月22日 13:54
  • 4871

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

过滤器检验用户是否登录

过滤器可以实现用户身份验证的功能,如果用户没有登录,则跳转到登陆页面: 本例实现:   过滤器类:   package com.start.util; import...

servlet+jsp实现过滤器,防止用户未登录访问

我们可能经常会用到这一功能,比如有时,我们不希望用户没有进行登录访问后台的操作页面,而且这样的非法访问会让系统极为的不安全,所以我们常常需要进行登录才授权访问其它页面,否则只会出现登录页面,当然我的思...

servlet初步,简单的登录验证并显示用户名称

编写3个servlet,分别为LogIn、CheckUser、Welcome,在LogIn中输入用户名和密码,点击“提交”按钮,提交到CheckUser中进行验证,验证成功显示Welcome,失败则重...
  • js0001
  • js0001
  • 2013年12月27日 15:28
  • 1476

Servlet用户登陆过滤器,编码校验过滤器

实现功能 用户访问login.jsp页面登陆时,要实现登陆成功跳转到success.jsp页面,登陆失败跳转到fail.jsp页面。用户直接访问success.jsp页面,跳转到login.jsp页...

servlet登陆过滤器

1.Servlet 过滤器是什么?      Servlet 过滤器是小型的 Web 组件,它们拦截请求和响应,以便查看、提取或以某种方式操作正在客户机和服务器之间交换的数据。过滤器是通常封装了一些功...
  • lwnbjz
  • lwnbjz
  • 2009年08月21日 15:09
  • 387

servlet和jsp页面过滤器Filter详解

servlet API中最重要的一个功能就是能够为servlet和JSP页面定义过滤器。过滤器提供了某些早期服务器所支持的非标准“servlet链接”的一种功能强大且标准的替代品。         ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Servlet 过滤器Filter判断用户是否登陆(jsp页面)
举报原因:
原因补充:

(最多只允许输入30个字)