赞
踩
创建一个 Filter , class类: 其继承于 接口 Filte(接口导包:import javax.servlet.Filter;)
在 web.xml 文件中配置并映射该 Filter. 其中 url-pattern 指定该 Filter 可以拦截哪些资源, 即可以通过哪些 url 访问到该 Filter,并进行拦截;
案例:username=Tom,password=1234,设计Filter类,及jsp页面实现,输入username和password是否等于Tom和1234,不等拦截index.jsp页面跳转到hello.jsp页面,等的或,在在hello,显示;
1.建立UserNameFilter类:继承于接口Filter(接口导包:import javax.servlet.Filter;)
packagecom.lanqiao.javatest;importjava.io.IOException;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importorg.apache.catalina.connector.Request;public class UserNameFilter implementsFilter{//构造方法
publicUserNameFilter(){
}public voiddestroy() {
}
@Overridepublic voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {
String initUser=filterConfig.getInitParameter("username");
String username=request.getParameter("username");if(!initUser.equals(username)){
request.setAttribute("message", "用户名不正确!!!");
request.getRequestDispatcher("/login.jsp").forward(request, response);return;
}
chain.doFilter(request, response);
}privateFilterConfig filterConfig;
@Overridepublic void init(FilterConfig filterConfig) throwsServletException {this.filterConfig=filterConfig;
}
}
2.建立PasswordFilter类:继承于接口Filter(接口导包:import javax.servlet.Filter;)
packagecom.lanqiao.javatest;importjava.io.IOException;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;public class PasswordFilter implementsFilter {publicPasswordFilter() {//TODO Auto-generated constructor stub
}
@Overridepublic voiddestroy() {
}
@Overridepublic voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {
String initPassword=filterConfig.getServletContext().getInitParameter("password");
String password=request.getParameter("password");if(!initPassword.equals(password)){
request.setAttribute("message", "密码不正确!!!");
request.getRequestDispatcher("/login.jsp").forward(request, response);return;
}
chain.doFilter(request, response);
}privateFilterConfig filterConfig;
@Overridepublic void init(FilterConfig filterConfig) throwsServletException {this.filterConfig=filterConfig;
}
}
3.在WEB-FIN下的web.xml文件下的配置和映射:
day-12
UserNameFilter
com.lanqiao.javatest.UserNameFilter
username
Tom
UserNameFilter
/hello.jsp
password
com.lanqiao.javatest.PasswordFilter
password
/hello.jsp
password
1234
4.index.jsp页面:输入username和password;
Insert title here${message }
username:5.hello.jsp页面:
Insert title hereCopyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。