复习 Struts 2(Day0920)[S标签OGNL表达式/文件上传]

2.Struts 2默认的表达式语言是OGNL(Object-Graph Navigation Language),不支持el表达式

1)常用struts2标签:

jsp页面引入<%@ taglib uri="/struts-tags"prefix="s" %>

控制标签

if:用于控制选择输出的标签。

elseIf/elseifif标签结合使用,用于控制选择输出的标签。

else:if标签结合使用,用于控制选择输出的标签。

append:用于将多个集合拼接成一个新的集合。

generator:它是一个字符串解析器,用于将一个字符串解析成一个集合。

iterator:这是一个迭代器,用于将集合迭代输出。

merge:用于将多个集合拼接成一个新的集合。但与append的拼接方式有所不同。

sort:这个标签用于对集合进行排序。

subset:这个标签用于截取集合的部分元素,形成新的子集合。

数据标签

action:该标签用于在JSP页面直接调用一个Action,通过指定executeResult参数,还可将该Action的处理结果包含到本页面中来。

bean:该标签用于创建一个JavaBean实例。如果指定了var属性,则可以将创建的JavaBean实例放入Stack Context中。

date:用于格式化输出一个日期。

debug:用于在页面上生成一个调试链接,当单击该链接时,可以看到当前ValueStackStack Context中的内容。

i18n:用于指定国际化资源文件的baseName。

include:用于在JSP页面中包含其他的JSPServlet资源。

param用于设置一个参数,通常是用做bean标签、url标签的子标签。

push:用于将某个值放入ValueStack的栈顶。

set:用于设置一个新变量,并可以将新变量放入指定的范围内。

text:用于输出国际化消息。

url用于生成一个URL地址。

property:用于输出某个值。

表单标签

checkbox - 生成复选框。

checkboxlist  - 生成一组复选框。

combobox    -跨浏览器效果差!

doubleselect  - 生成两个具有级联效果的列表框。

head  - 根据主题,引入相应的CSS样式和JS代码库。

file - 文件域

form - 表单

hidden - 隐藏域

label - 标签

optiontransferselect - 两个updownselect的组合。

optgroup - 必须select里使用。生成一组列表项。

password - 密码框。

radio -生成一组单选框。

reset -重置按钮。

select - 生成一个包括多个列表项的列表框。例如:

<s:select list="list" value="emp.mgr" hraderValue="--请选择--" listValue="ename" listKey="empno"/>

submit - 提交按钮

textarea - 多行文本区

textfield - 多行文本区,例如:

<s:textfield name="emp.job"/>

token - 防止重复提交。

updownselect - - 与select很像。可当成增强版的select

2) 值栈和非值栈
      Action的属性是保存于值栈中
      非值栈中的数据:获取非值栈数据要在前加"#"
      非值栈对象               访问方式                                           等价代码
         request                  #request.loginName               request.getAttribute("loginName")
         session                  #session.loginName              session.getAttribute("loginName")
         application             #application.loginName         application.getAttribute("loginName")
         parameters            #parameters.loginName        request.getParameter("loginName")
         attr                         #attr.loginName                     按pageContext->request->session->appplication顺序查找

3、文件上传与下载
   1) 文件上传
      1.1) 导包
          commons-fileupload-xx.jar
          commons-io-xx.jar
      1.2) 编写jsp文件
          <form action="" method="post" enctype="multipart/form-data" >
               <input type="file" name="uploads" />
          </form>
      1.3) 编写Action类的Action属性的规则:
          如果上传1个文件:
              File uploads;//文件对象名必须与上传控件的name属性值一致
              String uploadsContentType;//文件类型:属性名=uploads+ContentType
              String uploadsFileName;//文件名: 属性名=uploads+FileName

public class UploadAction extends ActionSupport {
	//上传文件的对象:属性名=name的属性值(<input type="type" name="uploads" />)
    private File uploads;
	private String uploadsContentType;//文件类型
	private String uploadsFileName;//文件名
    private String savePath;//保存文件的根路径
    //单文件上传
	public String upload1() throws Exception {
        //1、获得上传文件的根路径在tomcat下的绝对路径
		String rootPath = ServletActionContext.getRequest().getRealPath(savePath);
		 createRootPath(rootPath);//判断根目录是否存在,如果不存在就创建
		//2、将文件写入到服务器上
		try (FileInputStream fis = new FileInputStream(uploads);
				FileOutputStream fos = new FileOutputStream(rootPath+"/"+uploadsFileName);
				) {
			IOUtils.copy(fis, fos);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "input";
	}

	private void createRootPath(String rootPath) {
		File parentFile = new File(rootPath);
		if (!parentFile.exists()) parentFile.mkdirs();
	}

	public File getUploads() {
		return uploads;
	}

	public void setUploads(File uploads) {
		this.uploads = uploads;
	}

	public String getUploadsContentType() {
		return uploadsContentType;
	}

	public void setUploadsContentType(String uploadsContentType) {
		this.uploadsContentType = uploadsContentType;
	}

	public String getUploadsFileName() {
		return uploadsFileName;
	}

	public void setUploadsFileName(String uploadsFileName) {
		this.uploadsFileName = uploadsFileName;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

}

//在spring MVC时,配置扫描controller包,在controller类中的但参数方法,方法签名必须声明HttpSession session

String path = session.getServletContext().getRealPath("upload");

//在struts2中,控制层想获得路径只能用下面api,因为方法不能带参数,如果在方法中带参会报异常

java.lang.NoSuchMethodException: com.action3.UploadAction.upload1()

String path = ServletActionContext.getRequest().getRealPath(savePath);

<?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>
	<!-- 默认的视图主题 -->  
    <constant name="struts.ui.theme" value="simple" /> 
<package name="d2" extends="struts-default">
	<action name="upload1" class="com.action3.UploadAction" method="upload1">
		<param name="savePath">/upload</param>
		<result>/upload_success.jsp</result>
		<result name="input">/upload_success.jsp</result>
	</action>
</package>
</struts>	

访问upload1.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>My JSP 'upload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<form action="upload1.action" method="post" enctype="multipart/form-data" >
        单文件上传文件:<br/>
           <input type="file" name="uploads" /><br/>
        <input type="submit" value="上传" />
    </form>
  </body>
</html>

上传文件以后能看到上传的文件名

<%@ 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:if test="uploadsFileName!=null">
	<a href="download.action?fileName=${uploadsFileName }">${uploadsFileName }</a>
</s:if>
<s:else>
	
</s:else>
</body>
</html>

多文件上传
   

public class UploadAction extends ActionSupport {

	private File[] uploads2;
	private String[] uploads2ContentType;
	private String[] uploads2FileName;
	private String savePath;
	private void createRootPath(String rootPath) {
		File parentFile = new File(rootPath);
		if (!parentFile.exists()) parentFile.mkdirs();
	}
	public String upload2() throws Exception {
	    String rootPath = ServletActionContext.getRequest().getRealPath(savePath);
        createRootPath(rootPath);
		if(uploads2!=null && uploads2.length>0){
		    for(int i=0;i<uploads2.length;i++){
			    try (FileInputStream fis = new FileInputStream(uploads2[i]);
		FileOutputStream fos = new FileOutputStream(rootPath+"/"+uploads2FileName[i]);) 
                {
					IOUtils.copy(fis, fos);
					return "success";
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		 }
		 return "success";
	}

    public File[] getUploads2() {
		return uploads2;
	}
	public void setUploads2(File[] uploads2) {
		this.uploads2 = uploads2;
	}
	public String[] getUploads2ContentType() {
		return uploads2ContentType;
	}
	public void setUploads2ContentType(String[] uploads2ContentType) {
		this.uploads2ContentType = uploads2ContentType;
	}
	public String[] getUploads2FileName() {
		return uploads2FileName;
	}
	public void setUploads2FileName(String[] uploads2FileName) {
		this.uploads2FileName = uploads2FileName;
	}
	public String getSavePath() {
		return savePath;
	}
	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

upload2.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>My JSP 'upload.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
  	<form action="upload2.action" method="post" enctype="multipart/form-data" >
        多文件上传文件:<br/>
           <input type="file" name="uploads2" /><br/>   
           <input type="file" name="uploads2" /><br/>   
           <input type="file" name="uploads2" /><br/>   
        <input type="submit" value="上传" />
    </form>
  </body>
</html>

struts.xml配置如下

<?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>
	<!-- 默认的视图主题 -->  
    <constant name="struts.ui.theme" value="simple" /> 
    <package name="d2" extends="struts-default">
        <action name="upload2" class="com.action3.UploadAction" method="upload2">
		    <param name="savePath">/upload</param>
		    <result>/upload_success.jsp</result>
		    <result name="input">/upload_success.jsp</result>
	</action>
    </package>
</struts>	

upload_success.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:if test="uploadsFileName!=null">
	<a href="download.action?fileName=${uploadsFileName }">${uploadsFileName }</a>
</s:if>
 <s:else>
   	<s:iterator value="uploads2FileName" var="f">
   		<a href="download.action?fileName=${f }">${f }</a><br/>
   	</s:iterator>
</s:else>

</body>
</html>


    2) 文件下载  
      2.1) 创建Action,将获得下载文件的输入流
      2.2) 配置struts.xml文件,返回结果类型是stream
           配置下载的相关参数:
               a) contentType:设置下载文件的MIME类型
                    MIME类型:
                       word:application/msword
                       execl:application/vnd.ms-execl
                       图片:image/gif,image/bmp,image/jpeg
                       文本文件:text/plain
                       html网页:text/html
                       可执行文件:application/octer-stream 
                       
               b) contentDisposition:设置响应的HTTP头信息中的cotent-disposition参数的值
                     参数主要分为两个部分:
                       一个是文件下载的形式(inline:在线打开,attachment:附件) 
                       二个是下载文件时显示的文件名(fileName=文件名)
                       
               c) inputName:配置Action中InputStream类型的属性名     
               d) buffSize:读取和下载文件时的缓冲区大小:配置1024字节    

猜你喜欢

转载自blog.csdn.net/sinat_41897556/article/details/83714716