filter

来源:互联网 发布:99家居软件怎么样 编辑:程序博客网 时间:2024/06/03 08:45
1.filter是对客户端访问资源的过滤,符合条件放行,不符合条件不放行,并且可以对目标资源访问前后进行逻辑处理
2.快速入门
步骤:
编写一个过滤器的类实现filter接口
实现接口中尚未实现的方法

在web.xml中进行配置

<filter>    <filter-name>QuickFilter1</filter-name>    <filter-class>com.QuickFilter1</filter-class>    <init-param>    <param-name>aaa</param-name>    <param-value>AAAA</param-value>    </init-param>  </filter>  <filter-mapping>    <filter-name>QuickFilter1</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping>
3.filter的API详解
(1)filter生命周期及其生命周期的相关的方法
filter接口有三个方法,并且这个三个都是与filter的生命相关的方法
init(Filterconfig):代表filter对象初始化方法filter对象创建时执行
doFilter(ServletRequest,ServletResponse,FilterCha):代表filter执行过滤的核心方法,如果某资源在已经被配置到这个filter进行过滤的话,那么每次访问这个资源都会执行doFilter方法
destory():代表是filter销毁方法,当对象销毁时执行该方法
(2)dispatcher:访问的方式,在web.xml中配置
REQUEST:默认值,代表直接访问某个资源时执行filter
FORWARD:转发时才执行filter
INCLUDE:包含资源时才执行filter
ERROR:发生错误时,进行跳转是执行filter

<filter-mapping>    <filter-name>QuickFilter1</filter-name>    <url-pattern>/*</url-pattern>     <dispatcher>REQUEST</dispatcher>   <!--  <servlet-name>Servlet1</servlet-name> -->  </filter-mapping>
(3)filter作用
公共代码的提取
可以对request 和response中的方法进行增强(装饰着模式/动态代理)
进行权限控制
总结:
filter生命周期:过滤器从创建到销毁的过程
服务器启动的时候,服务器就会创建过滤器对象,每次访问被拦截目标资源,过滤器中的dofilter的方法就会执行,当服务器关闭的时候,服务器就会销毁filter对象
GET和POST统一编码

public class EncodingFilter implements Filter{@Overridepublic void destroy() {}@Overridepublic void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)throws IOException, ServletException {HttpServletRequest request=(HttpServletRequest)req;HttpServletResponse response=(HttpServletResponse)resp;//设置编码request.setCharacterEncoding("utf-8");MyRequest myRequest=new MyRequest(request);chain.doFilter(myRequest, response);}@Overridepublic void init(FilterConfig arg0) throws ServletException {}}web.xml配置过滤器<filter>  <filter-name>EncodingFilter</filter-name>  <filter-class>com.EncodingFilter</filter-class>  </filter>  <filter-mapping>  <filter-name>EncodingFilter</filter-name>  <url-pattern>/*</url-pattern>  </filter-mapping>使用装饰者设计模式,编写自定义request对象,主要解决GET提交方式编码问题public class MyRequest extends HttpServletRequestWrapper{public MyRequest(HttpServletRequest request) {super(request);}//获得指定名称的第一个参数public String getParameter(String name){String value=super.getParameter(name);try{if("GET".equalsIgnoreCase(super.getMethod())){value=new String(value.getBytes("ISO-8859-1") ,"UTF-8");}}catch(Exception e){e.printStackTrace();}return value;}}
自动登录的案例
创建javaBean
public class User {private String id;private String username;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}private String password;public User(String username,String password){this.username=username;this.password=password;}}
编写jsp表单
<body><form class="form-horizontal" action="${pageContext.request.contextPath }/login" method="post">用户名:<input type="text" class="form-control" id="username" name="username"><br/>密码:<input type="password" id="password" name="password"><br/><input type="submit" name="提交"><input type="checkbox" name="autoLogin">自动登录</form></body>
编写servlet实现类,完成登录

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String username=request.getParameter("username"); String password=request.getParameter("password"); String autoLogin=request.getParameter("autoLogin"); if(autoLogin!=null){ //使用Cookie记录用户信息使用@拼接 Cookie cookie=new Cookie("autoLoginCookie",username+"@"+password); cookie.setPath("/"); cookie.setMaxAge(60*60); response.addCookie(cookie); } User user=new User(username,password); //用户登录 UserService userService=new UserService(); User loginUser=null;try {loginUser = userService.login(user);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} //处理信息 if(loginUser!=null){ //用户登录成功,将用户信息保存在session作用域记录登记状态 request.getSession().setAttribute("loginUser",loginUser);response.sendRedirect(request.getContextPath()+"/index.jsp"); }else{ request.setAttribute("msg","用户名和密码不匹配"); request.getRequestDispatcher("/login.jsp").forward(request, response); }}service层public class UserService {private UserDao userDao=new UserDao();public User login(User user) throws SQLException{return userDao.find(user.getUsername(),user.getPassword());}}
DAO层
public class UserDao {public User find(String username,String password) throws SQLException{//try{QueryRunner queryRunner=new QueryRunner(C3P0ConfigUtils.getDataSource());String sql="select * from user where username=? and password=?";Object[] params={username,password};return queryRunner.query(sql, new BeanHandler<User>(User.class),params);//}catch(Exception e){//e.printStackTrace();//}}}
链接数据库的工具类public class C3P0ConfigUtils {private static DataSource dataSource=new ComboPooledDataSource();private static ThreadLocal<Connection>t1=new ThreadLocal<Connection>();public static DataSource getDataSource(){return dataSource;}public static Connection getConnection()throws SQLException{return dataSource.getConnection();}public static Connection getCurrentConnection() throws SQLException{Connection con=t1.get();if(con==null){con=dataSource.getConnection();t1.set(con);}return con;}public static void startTransaction()throws SQLException{Connection con=getCurrentConnection();if(con!=null){con.setAutoCommit(false);}}public static void rollback()throws SQLException{Connection con=getCurrentConnection();if(con!=null){con.rollback();}}//提交并且关闭资源public static void commitAndRelease()throws SQLException{Connection con=getCurrentConnection();if(con!=null){con.commit();//事务提交con.close();t1.remove();}}public static void closeConnection()throws SQLException{Connection con=getCurrentConnection();if(con!=null){con.close();}}public static void closeStatement(Statement st)throws SQLException{if(st!=null){st.close();}}public static void closeResultSet(ResultSet rs)throws SQLException{if(rs!=null){rs.close();}}}一个配置文件<?xml version="1.0" encoding="UTF-8"?><c3p0-config><default-config><property name="user">root</property><property name="password">root</property><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql:///web13</property></default-config> </c3p0-config>






原创粉丝点击