11.3.2 在Action中指定下载资源
前面的示例在配置文件中指定了下载资源的相关信息,但是这样指定资源是静态的,一般的应用要求系统根据用户不同的需要来动态下载资源。Struts 2框架还允许在Action中动态设置相关的资源下载配置信息,如代码11.10所示。
代码11.10 动态指定下载资源的业务控制器
package
ch11;
import
java.io.InputStream;
import
org.apache.struts2.ServletActionContext;
import
com.opensymphony.xwork2.Action;
import
com.opensymphony.xwork2.ActionSupport;
public
class
Filedownload
extends
ActionSupport
{
private String inputPath;
private String contentType;
private String filename;
//返回一个InputStream类型值
public InputStream getInputStream() throws Exception {
return ServletActionContext.getServletContext().getResourceAsStream(
inputPath);
}
//execute方法
public String execute() throws Exception {
//调用相关业务逻辑方法,动态设置相关下载信息
inputPath = "/upload/struts-power.gif";
filename = "test.gif"; 
contentType = "image/gif";
return SUCCESS;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}

读者可以看到,该Action可以根据用户的不同请求,动态指定不同的下载资源信息,下面的代码是对应的配置文件内容:
<
action
name
="filedownload"
class
="ch11.Filedownload"
>

<
result
name
="success"
type
="stream"
>

<!--
定义相关参数值
-->

<
param
name
="contentType"
>
${contentType}
</
param
>

<
param
name
="inputName"
>
inputStream
</
param
>

<
param
name
="bufferSize"
>
4096
</
param
>

<
param
name
="contentDisposition"
>

filename="${filename}"
</
param
>

</
result
>

</
action
>
读者可以同前面的示例相比较,在浏览器中输入http://localhost:8080/bookcode/ch11/ filedownload.action,返回界面如图11.11所示,同前面示例的结果完全一致。
11.3.3 文件下载的权限控制
读者明白了Struts 2框架文件下载的原理后,就很容易实现文件下载的权限控制,可以在Action的execute方法中加入用户合法身份的验证,如果不合法,则返回一个input逻辑视图,即返回给用户一个登录界面;如果是一个合法用户,则可以返回success逻辑视图,即返回用户想要下载的资源。
(1)增加了权限控制的Action如代码11.11所示。
代码11.11 增加权限检查的业务控制器
package
ch11;
import
java.io.InputStream;
import
org.apache.struts2.ServletActionContext;
import
com.opensymphony.xwork2.Action;
public
class
FileDownloadAction
implements
Action
{
private String username;
private String password;
private String inputPath;
public void setInputPath(String value) {
inputPath = value;
}
public InputStream getInputStream() throws Exception {
return ServletActionContext.getServletContext().getResourceAsStream (inputPath);
}
public String execute() throws Exception {
//权限检查
if(username.equals("pla")&&password.equals("mypassword")){
return SUCCESS; 
}else{
return INPUT; 
}
}
//属性的getter和setter方法
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

本文介绍如何使用Struts2框架实现在Action中动态指定下载资源,并通过权限控制确保只有合法用户才能下载。

1701

被折叠的 条评论
为什么被折叠?



