一、拦截器,拦截器栈

1、拦截器的作用

拦截器本质上和servlet的过滤器是一样的。在struts2中,拦截器能够对Action前后进行拦截,拦截器是一个可插拨的,你可以选择使用拦截器,也可以卸载拦截器。

2、拦截器执行顺序

在struts.xml文件中,<intercepto-ref/>中先引用的先执行,后引用的后执行。如果某个拦截器出错或不允许通过,那么下一个拦截器是不允许执行的。

需要拦截哪个Action,就在哪个Action对应的<action>标签中配置即可。

在部署web应用时,拦截器的空参构造方法和init()方法各执行一次,每次请求时intercept()方法都会执行一次。

3、自定义拦截器

  1) 声明一个拦截器

<pacakge >

<interceptors>
            <interceptor name="LoginInterceptor" class="interceptor.LoginInterceptor">
            </interceptor>
</interceptors>

<action ></action>
</package>

注意:这里interceptors与action标签同级。其中class对应拦截器的全路径。name对应拦截器的名称,这个可以自己随便定义,建议与类名相同,此名称要唯一。

2)引用一个拦截器:

<action>                      
<!-- 引用自定义的拦截器 -->
<interceptor-ref name="LoginInterceptor"></interceptor-ref>    
<action>

注意:如何引用一个拦截器?即在Action中<action>标签下配置即可。这里name名称与自定义的名称要一致。

 

4、自定义拦截器栈

1)声明一个拦截器

interceptor-stack标签中进行配置需要引用的拦截器,如下:

<interceptors>
            <interceptor name="LoginInterceptor" class="interceptor.LoginInterceptor"></interceptor>
            
            <interceptor-stack name="amosStack">
                <interceptor-ref name="LoginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
            
        </interceptors>

 

2)引用一个拦截器栈:

<!-- 引用自定义的拦截器栈 -->
<interceptor-ref name="amosStack"></interceptor-ref>

 

二、需求分析

 

java struts2入门学习---拦截器学习

 

如图所示,访问upload.jsp进行上传文件--》LoginInterceptor拦截器进行拦截---》

1、未登录,那么跳转页面到登录页面---》进行登录页面--》登录成功---》可以点击返回到上传文件页面;

2、已登录,登录直接开始上传文件。

 

三、代码分析:

upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <s:form action="UploadAction" enctype="multipart/form-data" method="POST">
        <s:textfield label="上传用户" name="username"/>
        <s:file label="上传文件" name="upload" />
        <s:file label="上传文件" name="upload" />
        <%-- <s:file label="上传文件" name="upload" /> --%>
        
        <s:submit value="提交"/>
    </s:form>
</body>
</html>
View Code

相关文章:

  • 2022-01-02
  • 2022-01-20
  • 2021-11-29
  • 2021-07-26
  • 2021-10-25
  • 2022-12-23
  • 2021-06-11
  • 2021-09-26
猜你喜欢
  • 2022-01-05
  • 2022-12-23
  • 2022-01-07
  • 2021-11-19
  • 2022-12-23
  • 2021-04-07
  • 2021-07-22
相关资源
相似解决方案