现在的位置: 首页 > 综合 > 正文

Struts2学习笔记13:Struts2的文件上传和下载

2013年08月09日 ⁄ 综合 ⁄ 共 2248字 ⁄ 字号 评论关闭

Struts2学习笔记13:Struts2的文件上传和下载

第十一讲

学习内容

1)通过一个例子复习拦截器知识。

2)简单的文件上传小实例

 拦截器的应用,所要实现的功能:

1.通过login.jsp页面登陆,成功跳转到register2.jsp页面

2.如果直接在地址栏中输入register.jsp的URL,当输入地址进行页面跳转的时候,

  跳转login.jsp页面

 步骤:

1.在interceptor包中建议一个名为 AuthInterceptor.java的文件,继承与

 AbstractInteceptor,代码如下:

package interceptor;

import java.util.Map;

import com.opensymphony.xwork2.Action;

import com.opensymphony.xwork2.ActionInvocation;

import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class AuthInterceptor extends AbstractInterceptor {

private static final long serialVersionUID = 

-5114658085937727056L;

@Override

@SuppressWarnings("unchecked")

public String intercept(ActionInvocation invocation) throws Exception {

Map map = invocation.getInvocationContext().getSession();

if ( map.get("user") == null ){

return Action.LOGIN;

else {

return invocation.invoke();

}

}

}

2.在struts.xml文件中声明拦截器:

 <interceptor name="auth" class="interceptor.AuthInterceptor">

 </interceptor>

3.将auth拦截器添加到register2.jsp对应的action中,并加入默认的拦截器栈:

 <interceptor-ref name="auth"></interceptor-ref>

 <interceptor-ref name="defaultStack"></interceptor-ref>

4.在login.java文件中,return "success";的代码前添加代码:

 Map map = ActionContext.getContext().getSession();

 map.put( "user" , "abcd" );

注:"abcd"可以随便填写,只要不为空即可。

5.修改login2.jsp对应action:

 <result name="success">/register2.jsp</result>

6.添加全局的result,在struts.xml文件package标签内,

 (好像不能直接写于package标签下,而是要间隔几个元素)

<global-results>

<result name="login">/login2.jsp</result>

</global-results>

7.运行

URL编码:

URLEncoder.encode(s, enc);

URL解码:

URLDecoder.decode(s, enc);

对于文件的上传,form表单中

method属性必须为"post",

entype属性必须为"multipart/form-data"

PreResultListener对于该接口,This callback method will be called after the Action execution and before the Result execution.

一个小例子,演示它的使用:

 1)建议一个文件RegisterListener.java实现PreResultListener接口,实现方法打印一句话

         System.out.println("result :" + resultCode );

 2)修改 RegisterInterceptor3.java文件中 doIntercept方法代码

protected String doIntercept(ActionInvocation invocation)

 throws Exception {

invocation.addPreResultListener(new RegisterListener());

System.out.println("MethodFilterInterceptor");

String result = invocation.invoke();

System.out.println("after RegisterInterceptor2");

return result;

}

 3)运行tomcat,会在两个println语句见打印一句

        result:success或者 input

总结:

本节知识,基本是复习内容,以及对文件的上传和下载的基本认识。没有太多的新内容。

抱歉!评论已关闭.