- 浏览: 80230 次
- 性别:
- 来自: 上海
文章分类
最新评论
-
jspc:
过滤器 Filter -
moistrot:
主要是oop
合格的java程序员(转) -
sunliao_first:
很好,很强大。
过滤器Filter配置总结 -
dengkehai:
只是给出一个参考,不是什么通用的,具体项目要具体分析
filter[过滤器]使用大全 -
yangqingran:
登录过滤器是不是写的有点简单?如果在项目中那样写可以吗?
filter[过滤器]使用大全
一.页面编码过滤器
1.开发EncodingFilter.java文件,继承自javax.servlet.Filter:
package bluemoon.crm.systemmanage.struts.Filter;
import java.io.*;
import javax.servlet.*;
public class EncodingFilter implements Filter
{
protected String encoding = null;
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
//从web.xml配置文件中获取编码配置
this.encoding = filterConfig.getInitParameter("Encoding");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
if(request.getCharacterEncoding() == null)
{
String encode = getEncoding();
if(encode != null)
{
//设置request的编码方式
request.setCharacterEncoding(encode);
}
}
chain.doFilter(request,response);
}
public String getEncoding()
{
return encoding;
}
public void destroy()
{
}
}
2. 在web.xml文件中加入如下配置信息:
<!-- 页面请求编码过滤器 注意每个页面的pageEncoding="GB2312" -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>bluemoon.crm.systemmanage.struts.Filter.EncodingFilter</filter-class>
<init-param>
<param-name>Encoding</param-name>
<param-value>GB2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<!-- 对全部的jsp页面有效,比较郁闷的是没有太多的配置方式 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--页面请求编码过滤器结束-->
二.用户是否登陆过滤器:
1.首先增加一个Action、ActionForm & JSP:
login.jsp中为一个登陆表单:
UserActionForm.java为一个Struts的ActionForm。
UserAction.java将用户登陆信息添加到session中。
2. 开发UserLoginedFilter.java:
package bluemoon.crm.systemmanage.struts.Filter;
import java.io.IOException;
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.*;
import bluemoon.crm.systemmanage.struts.forms.UserActionForm;
public class UserLoginedFilter extends HttpServlet implements Filter
{
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
RequestDispatcher dispatcher = request.getRequestDispatcher("userLogin.jsp");
HttpServletRequest userRequest = (HttpServletRequest)request;
UserActionForm userActionForm = (UserActionForm)userRequest.getSession().getAttribute("userActionForm");
if(userActionForm == null || userActionForm.getUser_name() == null || userActionForm.getUser_name().trim().length()<1)
{
System.out.println("用户未登录!");
dispatcher.forward(request,response);
return;
}
System.out.println("用户已登录!");
chain.doFilter(request,response);
}
public void destroy()
{
}
}
3.在web.xml文件中添加如下配置信息:
<!—用户是否登陆过滤器配置 注意只过虑jsp页面,不过虑.do -->
<filter>
<filter-name>userLoginedFilter</filter-name>
<filter-class>bluemoon.crm.systemmanage.struts.Filter.UserLoginedFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>userLoginedFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!—用户是否登陆过滤器配置结束 -->
三.用户是否登陆过滤器在多模块中的应用:
1.修改上面的过滤器代码:
package bluemoon.crm.systemmanage.filter;
import java.io.IOException;
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.*;
import bluemoon.crm.systemmanage.struts.forms.UserForm;
//用户未登陆过滤器
public class UserNoLoginedFilter extends HttpServlet implements Filter
{
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
//首先预定义到要转向的页面,由此带来的问题就是userLogin.jsp页面的图片必须要使用绝对路径,方法见userLogin.jsp页面
RequestDispatcher dispatcher = request.getRequestDispatcher("/toLogin.do?prefix=&page=/userLogin.jsp");
//注意在struts-config.xml中增加一个Action,如下:
/*
*<action
* attribute="userForm"
* name="userForm"
* path="/toLogin"
* scope="request"
* type="org.apache.struts.actions.SwitchAction" />
*/
// 从session中获取用户form
HttpServletRequest userRequest = (HttpServletRequest)request;
UserForm userForm = (UserForm)userRequest.getSession().getAttribute("userForm");
//如果未登陆则没有userFrom信息
if(userForm == null || userForm.getUser_name() == null || userForm.getUser_name().trim().length()<1)
{
System.out.println("用户未登录!");
//分发到登陆页面
dispatcher.forward(request,response);
//((HttpServletResponse)response).sendRedirect("toModule.do?prefix=&page=/userLogin.jsp");
return;
}
System.out.println("用户"+userForm.getUser_name()+"已登录!");
chain.doFilter(request,response);
}
public void destroy()
{
}
}
四.关闭Session过滤器
1.相关的HibernateUtil.java源码:
package com.worklog.util;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static
{
try
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static final ThreadLocal<Session> threadLocalSession = new ThreadLocal<Session>();
public static final ThreadLocal<Transaction> threadLocalTransaction = new ThreadLocal<Transaction>();
public static Session currentSession()
{
Session session = threadLocalSession.get();
try
{
if(session == null || !session.isOpen())
{
session = openSession();
threadLocalSession.set(session);
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("获取Session失败");
}
return session;
}
public static Session openSession() throws Exception
{
return getSessionFactory().openSession();
}
public static SessionFactory getSessionFactory() throws Exception
{
return sessionFactory;
}
public static void closeSession()
{
Session session = (Session)threadLocalSession.get();
threadLocalSession.set(null);
try
{
if(session != null && session.isOpen())
{
//System.out.println("HibernateUtil.java--line59,关闭Session!");
session.close();
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("关闭Session失败");
}
}
public static void beginTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
if(tx == null)
{
tx = currentSession().beginTransaction();
threadLocalTransaction.set(tx);
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("开始事务失败");
}
}
public static void commitTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
if(tx !=null && !tx.wasCommitted() && !tx.wasRolledBack())
{
tx.commit();
}
threadLocalTransaction.set(null);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("提交失败");
}
}
public static void rollbackTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
threadLocalTransaction.set(null);
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
tx.rollback();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("回滚失败");
}
}
}
2.CloseSessionFilter.java源码:
package com.worklog.filter;
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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.worklog.util.HibernateUtil;
public class CloseSessionFilter implements Filter{
Log log = LogFactory.getLog(this.getClass());
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException
{
this.config = config;
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException,ServletException
{
try
{
//让后面的Filter链处理请求,这个Filter仅仅拦截响应处理Hibernate操作
chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
}
finally
{
try
{
//一直没有合适的关闭session的方法
HibernateUtil.closeSession();
//System.out.println("close session success");
log.debug("close session success");
}
catch(Exception e)
{
HibernateUtil.rollbackTransaction();
System.out.println("can not close session!\nerrors:"+e.getMessage());
log.debug("can not close session!\nerrors:"+e.getMessage());
}
finally
{
HibernateUtil.closeSession();
}
}
}
public void destroy()
{
}
}
3.web.xml配置
<?xml version="1.0" encoding="GB2312"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 关闭Session过滤器 -->
<filter>
<filter-name>closeSessionFilter</filter-name>
<filter-class>com.worklog.filter.CloseSessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>closeSessionFilter</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<!-- 关闭Session过滤器结束 -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
//使用filter过滤器实现登陆权限验证
1.首先写一个权限过滤filter类,实现Filter接口
public class RightFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException { }
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(true);
String path = req.getRequestURI();
// 从session里取的用户名信息
String userid= (String) session.getAttribute("userid");
for (int i = 0; i < Constants.NoFilter_Pages.length; i++) {
if (path.indexOf(Constants.NoFilter_Pages[i]) > -1) {
chain.doFilter(req, res);
return;
}
}
if (username == null || "".equals(username)) {
// 跳转到登陆页面
res.sendRedirect("http://"+req.getHeader("Host")+"/task/login.jsp");;
} else {
// 已经登陆,继续此次请求
chain.doFilter(request, response);
}
}
public void destroy() { }
}
public class Constants {
public Constants() {
}
public static String[] NoFilter_Pages = {
"/index.jsp",
"/login.jsp",
};
}
2.然后在web.xml里配置需要登陆权限验证的JSP文件:
a.如果是某个具体的JSP文件(如a.jsp)需要登陆验证
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.dayou.util.RightFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/a.jsp</url-pattern>
</filter-mapping>
...
</web-app>
b.如果是某一个目录(如pages/目录)整个目录下的文件都需要登陆验证:
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.dayou.util.RightFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/pages/*</url-pattern>
</filter-mapping>
...
</web-app>
-----------------------------------------------
最简单判断用户是否登陆验证:
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
String uri = request.getRequestURI();
if(uri.indexOf( "/assessTeamE/login.jsp ") != -1 ||
uri.equals( "/assessTeamE/login.do ")){
arg2.doFilter(arg0, arg1);
}else if(request.getSession().getAttribute( "uid ") != null){
arg2.doFilter(arg0, arg1);
}else{
response.sendRedirect(login);
}
}
1.开发EncodingFilter.java文件,继承自javax.servlet.Filter:
package bluemoon.crm.systemmanage.struts.Filter;
import java.io.*;
import javax.servlet.*;
public class EncodingFilter implements Filter
{
protected String encoding = null;
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
//从web.xml配置文件中获取编码配置
this.encoding = filterConfig.getInitParameter("Encoding");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
if(request.getCharacterEncoding() == null)
{
String encode = getEncoding();
if(encode != null)
{
//设置request的编码方式
request.setCharacterEncoding(encode);
}
}
chain.doFilter(request,response);
}
public String getEncoding()
{
return encoding;
}
public void destroy()
{
}
}
2. 在web.xml文件中加入如下配置信息:
<!-- 页面请求编码过滤器 注意每个页面的pageEncoding="GB2312" -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>bluemoon.crm.systemmanage.struts.Filter.EncodingFilter</filter-class>
<init-param>
<param-name>Encoding</param-name>
<param-value>GB2312</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<!-- 对全部的jsp页面有效,比较郁闷的是没有太多的配置方式 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--页面请求编码过滤器结束-->
二.用户是否登陆过滤器:
1.首先增加一个Action、ActionForm & JSP:
login.jsp中为一个登陆表单:
UserActionForm.java为一个Struts的ActionForm。
UserAction.java将用户登陆信息添加到session中。
2. 开发UserLoginedFilter.java:
package bluemoon.crm.systemmanage.struts.Filter;
import java.io.IOException;
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.*;
import bluemoon.crm.systemmanage.struts.forms.UserActionForm;
public class UserLoginedFilter extends HttpServlet implements Filter
{
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
RequestDispatcher dispatcher = request.getRequestDispatcher("userLogin.jsp");
HttpServletRequest userRequest = (HttpServletRequest)request;
UserActionForm userActionForm = (UserActionForm)userRequest.getSession().getAttribute("userActionForm");
if(userActionForm == null || userActionForm.getUser_name() == null || userActionForm.getUser_name().trim().length()<1)
{
System.out.println("用户未登录!");
dispatcher.forward(request,response);
return;
}
System.out.println("用户已登录!");
chain.doFilter(request,response);
}
public void destroy()
{
}
}
3.在web.xml文件中添加如下配置信息:
<!—用户是否登陆过滤器配置 注意只过虑jsp页面,不过虑.do -->
<filter>
<filter-name>userLoginedFilter</filter-name>
<filter-class>bluemoon.crm.systemmanage.struts.Filter.UserLoginedFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>userLoginedFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!—用户是否登陆过滤器配置结束 -->
三.用户是否登陆过滤器在多模块中的应用:
1.修改上面的过滤器代码:
package bluemoon.crm.systemmanage.filter;
import java.io.IOException;
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.*;
import bluemoon.crm.systemmanage.struts.forms.UserForm;
//用户未登陆过滤器
public class UserNoLoginedFilter extends HttpServlet implements Filter
{
protected FilterConfig config;
public void init(FilterConfig filterConfig) throws ServletException
{
this.config = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
//首先预定义到要转向的页面,由此带来的问题就是userLogin.jsp页面的图片必须要使用绝对路径,方法见userLogin.jsp页面
RequestDispatcher dispatcher = request.getRequestDispatcher("/toLogin.do?prefix=&page=/userLogin.jsp");
//注意在struts-config.xml中增加一个Action,如下:
/*
*<action
* attribute="userForm"
* name="userForm"
* path="/toLogin"
* scope="request"
* type="org.apache.struts.actions.SwitchAction" />
*/
// 从session中获取用户form
HttpServletRequest userRequest = (HttpServletRequest)request;
UserForm userForm = (UserForm)userRequest.getSession().getAttribute("userForm");
//如果未登陆则没有userFrom信息
if(userForm == null || userForm.getUser_name() == null || userForm.getUser_name().trim().length()<1)
{
System.out.println("用户未登录!");
//分发到登陆页面
dispatcher.forward(request,response);
//((HttpServletResponse)response).sendRedirect("toModule.do?prefix=&page=/userLogin.jsp");
return;
}
System.out.println("用户"+userForm.getUser_name()+"已登录!");
chain.doFilter(request,response);
}
public void destroy()
{
}
}
四.关闭Session过滤器
1.相关的HibernateUtil.java源码:
package com.worklog.util;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static
{
try
{
sessionFactory = new Configuration().configure().buildSessionFactory();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public static final ThreadLocal<Session> threadLocalSession = new ThreadLocal<Session>();
public static final ThreadLocal<Transaction> threadLocalTransaction = new ThreadLocal<Transaction>();
public static Session currentSession()
{
Session session = threadLocalSession.get();
try
{
if(session == null || !session.isOpen())
{
session = openSession();
threadLocalSession.set(session);
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("获取Session失败");
}
return session;
}
public static Session openSession() throws Exception
{
return getSessionFactory().openSession();
}
public static SessionFactory getSessionFactory() throws Exception
{
return sessionFactory;
}
public static void closeSession()
{
Session session = (Session)threadLocalSession.get();
threadLocalSession.set(null);
try
{
if(session != null && session.isOpen())
{
//System.out.println("HibernateUtil.java--line59,关闭Session!");
session.close();
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("关闭Session失败");
}
}
public static void beginTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
if(tx == null)
{
tx = currentSession().beginTransaction();
threadLocalTransaction.set(tx);
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("开始事务失败");
}
}
public static void commitTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
if(tx !=null && !tx.wasCommitted() && !tx.wasRolledBack())
{
tx.commit();
}
threadLocalTransaction.set(null);
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("提交失败");
}
}
public static void rollbackTransaction()
{
Transaction tx = (Transaction)threadLocalTransaction.get();
try
{
threadLocalTransaction.set(null);
if(tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
tx.rollback();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("回滚失败");
}
}
}
2.CloseSessionFilter.java源码:
package com.worklog.filter;
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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.worklog.util.HibernateUtil;
public class CloseSessionFilter implements Filter{
Log log = LogFactory.getLog(this.getClass());
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException
{
this.config = config;
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException,ServletException
{
try
{
//让后面的Filter链处理请求,这个Filter仅仅拦截响应处理Hibernate操作
chain.doFilter((HttpServletRequest)request, (HttpServletResponse)response);
}
finally
{
try
{
//一直没有合适的关闭session的方法
HibernateUtil.closeSession();
//System.out.println("close session success");
log.debug("close session success");
}
catch(Exception e)
{
HibernateUtil.rollbackTransaction();
System.out.println("can not close session!\nerrors:"+e.getMessage());
log.debug("can not close session!\nerrors:"+e.getMessage());
}
finally
{
HibernateUtil.closeSession();
}
}
}
public void destroy()
{
}
}
3.web.xml配置
<?xml version="1.0" encoding="GB2312"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- 关闭Session过滤器 -->
<filter>
<filter-name>closeSessionFilter</filter-name>
<filter-class>com.worklog.filter.CloseSessionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>closeSessionFilter</filter-name>
<servlet-name>action</servlet-name>
</filter-mapping>
<!-- 关闭Session过滤器结束 -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
//使用filter过滤器实现登陆权限验证
1.首先写一个权限过滤filter类,实现Filter接口
public class RightFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException { }
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(true);
String path = req.getRequestURI();
// 从session里取的用户名信息
String userid= (String) session.getAttribute("userid");
for (int i = 0; i < Constants.NoFilter_Pages.length; i++) {
if (path.indexOf(Constants.NoFilter_Pages[i]) > -1) {
chain.doFilter(req, res);
return;
}
}
if (username == null || "".equals(username)) {
// 跳转到登陆页面
res.sendRedirect("http://"+req.getHeader("Host")+"/task/login.jsp");;
} else {
// 已经登陆,继续此次请求
chain.doFilter(request, response);
}
}
public void destroy() { }
}
public class Constants {
public Constants() {
}
public static String[] NoFilter_Pages = {
"/index.jsp",
"/login.jsp",
};
}
2.然后在web.xml里配置需要登陆权限验证的JSP文件:
a.如果是某个具体的JSP文件(如a.jsp)需要登陆验证
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.dayou.util.RightFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/a.jsp</url-pattern>
</filter-mapping>
...
</web-app>
b.如果是某一个目录(如pages/目录)整个目录下的文件都需要登陆验证:
<web-app>
...
<filter>
<filter-name>right</filter-name>
<filter-class>com.dayou.util.RightFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>right</filter-name>
<url-pattern>/pages/*</url-pattern>
</filter-mapping>
...
</web-app>
-----------------------------------------------
最简单判断用户是否登陆验证:
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
String uri = request.getRequestURI();
if(uri.indexOf( "/assessTeamE/login.jsp ") != -1 ||
uri.equals( "/assessTeamE/login.do ")){
arg2.doFilter(arg0, arg1);
}else if(request.getSession().getAttribute( "uid ") != null){
arg2.doFilter(arg0, arg1);
}else{
response.sendRedirect(login);
}
}
评论
2 楼
dengkehai
2009-07-31
只是给出一个参考,不是什么通用的,具体项目要具体分析
1 楼
yangqingran
2008-09-19
登录过滤器是不是写的有点简单?如果在项目中那样写可以吗?
相关推荐
本文将详细介绍如何在Java中使用Filter过滤器,以及如何配置相关的配置文件,让你一目了然。 ### 1. Filter接口与生命周期 Filter是Servlet API中的一个接口,位于`javax.servlet`包下。它定义了三个关键方法: -...
`Filter创建.exe`可能是一个用于创建过滤器实例或者配置过滤器的工具,而`说明.txt`可能包含了关于如何使用这个工具或者过滤器的详细步骤和注意事项。 过滤器还可以与其他框架集成,比如Spring MVC中的Filter,可以...
在这个方法中,可以释放过滤器使用的资源。 Filter 的应用场景 Filter 可以应用于多种场景,例如: * 认证和授权:可以使用 Filter 来实现认证和授权功能,例如检查用户的登录状态和权限。 * 日志记录:可以使用 ...
除了上述示例外,FFmpeg过滤器的使用还涉及了更多细节,例如filter的结构体和filter_frame调用流程。这些内容通常涉及底层编程,需要开发者具备一定的编程基础和对FFmpeg内部结构的深入理解。 当进行复杂操作时,...
filter 过滤器 解释 MultipartHttpServletRequest表单
SpringBoot的filter过滤器 一、过滤器的作用和概述 1.1 简述 1.2 使用场景 二、自定义过滤的两种方式 2.1 第一种方式 2.1.1 启动类增加注解@ServletComponentScan 2.1.2 定义一个filter类 2.1.3. 测试 2.2 第二种...
解决这个问题的一种常见方法是使用Filter过滤器。以下是配置Filter过滤器处理JSP中文乱码的详细步骤: 1. **配置web.xml文件** 在项目的`web.xml`文件中,你需要添加一个Filter来定义处理乱码的逻辑。首先,声明一...
自Java EE 6开始,除了传统的XML配置,还可以使用Servlet 3.0的注解来配置过滤器,如`@WebFilter`,这样可以简化配置过程。 7. **Filter接口的其他方法**: 过滤器接口还提供了其他方法,如`init(FilterConfig ...
在标题提到的"filter过滤器的简单使用.rar"压缩包中,很显然包含了一个关于如何在Maven项目和Spring Boot项目中使用Filter的示例。下面将详细介绍Filter的基本概念、工作原理以及如何在两种项目环境中应用。 **...
在Java Web开发中,`Filter`过滤器是一个关键的安全组件,用于拦截...总的来说,`URLfilter`展示了如何使用Java过滤器来防止SQL注入攻击的一个基本思路,但在实际应用中,需要结合更全面的安全策略来提高系统的安全性。
本篇文章主要介绍了Java Web开发中Filter过滤器的概念及其使用方法。通过示例代码详细展示了如何编写和配置一个简单的Filter来解决字符集乱码问题。理解Filter的工作机制有助于开发者更好地利用这一功能来增强Web...
下面我们就通过分析一个具体的示例代码来详细了解如何使用JSP Filter过滤器来判断用户是否已经登录。 #### 示例代码分析 首先,我们来看一下示例中的过滤器类`RightFilter`: ```java import javax.servlet....
在Java Web开发中,过滤器(Filter)是一个非常重要的组件,它允许开发者在请求被处理之前或之后执行一些预定义的任务。本篇文章将基于提供的标题和描述,详细讲解过滤器的概念、工作原理以及如何通过源码实现一个...
在本实例中,我们将深入探讨Servlet过滤器(Filter)的使用和实现,以及它在实际应用中的重要性。 一、Servlet过滤器简介 Servlet过滤器遵循Java Servlet规范,通过实现`javax.servlet.Filter`接口来创建自定义过滤...
在探讨“hibernate过滤器使用例子”这一主题时,我们深入分析了如何在Hibernate框架中运用过滤器功能,以及如何结合分页技术优化数据查询效率。以下将详细阐述相关知识点,包括过滤器的基本概念、配置方法、源码解析...
JavaFilter自定义编码过滤器知识点 一、Filter接口和 FilterChain接口 在 Java 中, Filter 接口和 FilterChain 接口是 Servlet 规范中的两个重要组件。 Filter 接口用于定义一个过滤器, FilterChain 接口用于将...
为什么使用PHP Filter过滤器? 在Web应用程序中,数据通常来自各种不可信源,例如用户输入、cookies、服务器变量或外部API。这些数据可能包含错误或恶意内容,因此,对输入进行验证和过滤至关重要,以防止诸如SQL...
【Java Filter过滤器详解】 Java Filter是Java Servlet技术的一部分,它允许开发者在Servlet容器中对HTTP请求和响应进行拦截处理,实现数据过滤、权限控制、日志记录等多种功能。Filter的生命周期包括三个主要方法...
Filter 过滤器 Filter 过滤器是 JavaWeb 的一个重要组件,对请求和响应进行拦截,实现一些特殊的功能。Filter 程序是一个实现 Filter 接口的 Java 类,类似于 Servlet 程序,由 Servlet 容器进行调用和执行。需要在...
filter 理解为管道加工处理, 你扔给我一组数据 经过各种不同类型的管道加工 产出新的数据 但是又不会影响修改原数据, 最终展示给用户. 现有前端框架filter一般: time | dateTime('yyy-mm-dd') 使用 | 作为管道符 ...