说明:过滤器有什么功能?过滤器起到一个过滤作用,即用户只有在登录的情况下才能看到主界面,否则是不允许对主界面进行访问的。首先,创建Filter类,类中有init方法,构造方法,destroy方法等,执行顺序为先构造,再执行init方法,之后处理请求doGet或doPost,当关闭浏览器时执行销毁方法。当给某个页面设置过滤器后,先执行过滤器,然后执行servlet。首先创建包filter,在包中创建Filter命名为LoginFilter,同时需要在创建工程时所创建的web.xml文件中进行过滤器配置。代码如下
a.LoginFilter代码:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
HttpSession session=req.getSession();
String[] allows={"login.jsp","login1.jsp","login2.jsp","UserServlet","css/","images/","js/"};
//通过req拿到访问路径
String uri=req.getRequestURI();
boolean flag=false;
for(String allow:allows){
if(uri.contains(allow)){
chain.doFilter(req, res);
flag=true;
}
}
if(!flag){
//判断用户能否登录
User user=(User)session.getAttribute("user");
if(user!=null){
//只有执行了该语句,被过滤的Servlet才可以处理请求与响应,否则被阻挡
chain.doFilter(req, res);
}else{
res.sendRedirect("login.jsp");
}
}
}
b.web.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>StudentProject</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>loginServlet</filter-name>
<!--过滤器路径-->
<filter-class>com.hyxy.product.filter.LoginFilter</filter-class>
</filter>
<!--配置映射过滤器-->
<filter-mapping>
<filter-name>loginServlet</filter-name>
<!--*代表所有路径-->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
总结:至此,所有的关于jsp的操作都已经完成,通过本次的学习,了解了java的web编程的过程以及一些新的技术,例如ajax等,也对java这门语言有了更加深入的了解,不再像刚刚接触java时满篇的编译错误,最简单的分号都会忘记。大数据的第一部分java部分已经完成,接下来将要进行第二部分,希望在以后的学习中仍然能够保持那份最初学习java语言时的信念,为了能够有更加美好的明天,我将更加的拼命,以心为舟,信念为奖,击破巨浪,冲向远方!