Struts知识点概况(二)

一、文件上传
实现原理:struts的文件上传拦截器

1.文件上传jsp页面

	<form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">
  		用户名:<input type="text" name="userName"><br/>
  		文件:<input type="file" name="file1"><br/>
  		<input type="submit" value="上传">
  	</form>

2.文件上传代码

package cn.itcast.e_fileupload;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUpload extends ActionSupport {
	// 对应表单:<input type="file" name="file1">
	private File file1; 
	// 文件名
	private String file1FileName;
	// 文件的类型(MIME)
	private String file1ContentType;
	public void setFile1(File file1) {
		this.file1 = file1;
	}
	public void setFile1FileName(String file1FileName) {
		this.file1FileName = file1FileName;
	}
	public void setFile1ContentType(String file1ContentType) {
		this.file1ContentType = file1ContentType;
	}
	
	@Override
	public String execute() throws Exception {
		/******拿到上传的文件,进行处理******/
		// 把文件上传到upload目录	
		// 获取上传的目录路径
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		// 创建目标文件对象
		File destFile = new File(path,file1FileName);
		// 把上传的文件,拷贝到目标文件中
		FileUtils.copyFile(file1, destFile);		
		return SUCCESS;
	}
}
3.配置struts.xml
<package name="upload_" extends="struts-default">
		<!-- 注意: action 的名称不能用关键字"fileUpload" -->
		<action name="fileUploadAction" class="cn.itcast.e_fileupload.FileUpload">
			<!-- 限制运行上传的文件的类型 -->
			<interceptor-ref name="defaultStack">
				<!-- 限制运行的文件的扩展名 -->
				<param name="fileUpload.allowedExtensions">txt,jpg,jar</param>
				<!-- 限制运行的类型   【与上面同时使用,取交集】
				<param name="fileUpload.allowedTypes">text/plain</param>
				-->			
				<!-- 修改上传文件的最大大小为30M -->
				<constant name="struts.multipart.maxSize" value="31457280"/>
			</interceptor-ref>
			<result name="success">/e/success.jsp</result>
			<!-- 配置错误视图 -->
			<result name="input">/e/error.jsp</result>
		</action>
</package>
二、文件下载

1.编写下载代码


import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 文件下载
 * 1. 显示所有要下载文件的列表
 * 2. 文件下载
 * @author Jie.Yuan
 *
 */
public class DownAction extends ActionSupport {
	
	
	/*************1. 显示所有要下载文件的列表*********************/
	public String list() throws Exception {
		
		//得到upload目录路径
		String path = ServletActionContext.getServletContext().getRealPath("/upload");
		// 目录对象
		File file  = new File(path);
		// 得到所有要下载的文件的文件名
		String[] fileNames =  file.list();
		// 保存
		ActionContext ac = ActionContext.getContext();
		// 得到代表request的map (第二种方式)
		Map<String,Object> request= (Map<String, Object>) ac.get("request");
		request.put("fileNames", fileNames);
		return "list";
	}
	
	
	/*************2. 文件下载*********************/
	
	// 1. 获取要下载的文件的文件名
	private String fileName;
	public void setFileName(String fileName) {
		// 处理传入的参数中问题(get提交)
		try {
			fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		// 把处理好的文件名,赋值
		this.fileName = fileName;
	}
	
	//2. 下载提交的业务方法 (在struts.xml中配置返回stream)
	public String down() throws Exception {
		return "download";
	}
	
	// 3. 返回文件流的方法
	public InputStream getAttrInputStream(){
		return ServletActionContext.getServletContext().getResourceAsStream("/upload/" + fileName);
	}
	
	// 4. 下载显示的文件名(浏览器显示的文件名)
	public String getDownFileName() {
		// 需要进行中文编码
		try {
			fileName = URLEncoder.encode(fileName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
		return fileName;
	}

	
}










2.配置struts.xml

<package name="upload_" extends="struts-default">
		<action name="down_*" class="DownAction"
			method="{1}">
			<!-- 列表展示 -->
			<result name="list">/list.jsp</result>
			<!-- 下载操作 -->
			<result name="download" type="stream">

				<!-- 运行下载的文件的类型:指定为所有的二进制文件类型 -->
				<param name="contentType">application/octet-stream</param>

				<!-- 对应的是Action中属性: 返回流的属性【其实就是getAttrInputStream()】 -->
				<param name="inputName">attrInputStream</param>

				<!-- 下载头,包括:浏览器显示的文件名 -->
				<param name="contentDisposition">attachment;filename=${downFileName}</param>

				<!-- 缓冲区大小设置 -->
				<param name="bufferSize">1024</param>
			</result>
		</action>
	</package>
3.新建jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>下载列表</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  
  <body>
  	<table border="1" align="center">
  		<tr>
  			<td>编号</td>
  			<td>文件名</td>
  			<td>操作</td>
  		</tr>
  		<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  		<c:forEach var="fileName" items="${fileNames}" varStatus="vs">
  			<tr>
  				<td>${vs.count }</td>
  				<td>${fileName }</td>
  				<td>
  					<!-- 构建一个url -->
  					<c:url var="url" value="down_down">
  						<c:param name="fileName" value="${fileName}"></c:param>
  					</c:url>
  					
  					<a href="${url }">下载</a>
  				</td>
  			</tr>
  		</c:forEach>
  	</table>
  </body>
</html>






需要注意的是下载的文件要存在名为upload的文件夹下才会在列表页面显示

三、拦截器

1.概述:

Intercetor, 即为拦截器。

1)在Struts2中,把每一个功能都用一个个的拦截器实现;用户想用struts的哪个功能的时候,可以自由组装使用。

2)Struts2中,为了方法用户对拦截器的引用,提供了拦截器栈的定义,里面可以包含多个拦截器。   文件夹(文件, 文件2)  拦截器         栈(拦截器,拦截器2)

3)Struts2中,如果用户没有指定执行哪些拦截器,struts2有一个默认执行的栈,defaultStack;

      一旦如果用户有指定执行哪些拦截器,默认的拦截器栈就不会被执行

拦截器的设计,就是基于组件设计的应用!

2. 拦截器配置举例

struts-default.xml文件中,定义了struts提供的所有拦截器!

//1. 定义拦截器以及拦截器栈
<interceptors>
    1.1 拦截器定义
    <interceptor name="" class="" /> 
    
    1.2 拦截器栈的定义
    <interceptor-stack name="defaultStack">
	引用了上面拦截器(1.1)
    </interceptor-stack>
</interceptors>

2. 默认执行的拦截器(栈)
<default-interceptor-ref name="defaultStack"/>
3.自定义拦截器举例

/**
 * 自定义拦截器
 * @author Jie.Yuan
 *
 */
public class HelloInterceptor implements Interceptor{
	
	// 启动时候执行
	public HelloInterceptor(){
		System.out.println("创建了拦截器对象");
	}

	// 启动时候执行
	@Override
	public void init() {
		System.out.println("执行了拦截器的初始化方法");
	}

	// 拦截器业务处理方法 (在访问action时候执行? 在execute之前执行?)
	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		System.out.println("2. 拦截器,业务处理-开始");
		
		// 调用下一个拦截器或执行Action  (相当于chain.doFilter(..)
		// 获取的是: execute方法的返回值
		String resultFlag = invocation.invoke();
		
		System.out.println("4. 拦截器,业务处理-结束");
		
		return resultFlag;
	}

	@Override
	public void destroy() {
		System.out.println("销毁....");
	}
}
配置拦截器
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<package name="hello" extends="struts-default">
		<!-- 【拦截器配置】 -->
		<interceptors>
			<!-- 配置用户自定义的拦截器 -->
			<interceptor name="helloInterceptor" class="cn.itcast.a_interceptor.HelloInterceptor"></interceptor>
			
			<!-- 自定义一个栈: 要引用默认栈、自定义的拦截器 -->
			<interceptor-stack name="helloStack">
				<!-- 引用默认栈 (一定要放到第一行)-->
				<interceptor-ref name="defaultStack"></interceptor-ref>
				<!-- 引用自定义拦截器 -->
				<interceptor-ref name="helloInterceptor"></interceptor-ref>
			</interceptor-stack>		

</interceptors>

     <!-- 【执行拦截器】 -->

     <default-interceptor-ref name="helloStack"></default-interceptor-ref>

     <!-- Action配置 -->

     <action name="hello"class="cn.itcast.a_interceptor.HelloAction">

        <result name="success"></result>

     </action>

   </package>

</struts>

4.拦截器的生命周期:



5.拦截器案例:http://blog.csdn.net/zbq857143497/article/details/54018161

四、Struts2中的国际化

Servlet 中国际化:
1. 写资源文件
基础名.properties  【默认的语言环境的配置】  
基础名_语言简称_国家简称.properties
2. 读取资源文件,再使用
程序:ResourceBundle
Jsp:   jstl提供的格式化与国际化标签库。

Struts2中国际化:
1. 写资源文件  (同servlet)
2. 读资源文件
程序:ResourceBundle   (同servlet)
JSP:  
1)jstl (同servlet)
2)struts标签获取资源文件内容
区别:
Struts2加载资源文件更加简单!通过常量加载即可!再在jsp页面直接使用!

à1.  写资源文件

Msg.properties   默认的语言环境; 找不到配置就找它

Msg_en_US.properties  美国

-à2.  加载

<constant name="struts.custom.i18n.resources" value="cn.itcast.config.msg"></constant>

à3. 使用: 标签name值直接写配置文件中的key

<s:text name="title"></s:text>

另外一点,(推荐)加载资源文件通过常量加载,还可以在页面加载, 这样用:

                  <s:i18nname="cn.itcast.config.msg">

                          <s:text>  标签必须放到标签体中。

</s:i18n>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值