风中叶之struts2学习笔记四

1,        进行文件上传时,必须将表单的method属性设置为post,将enctype属性设置为multipart/form-data

2,       http://apache.etoak.com//commons/fileupload/binaries/commons-fileupload-1.2.2-bin.zip:文件上传组件到apache官网下的顶级项目commons的子项目FileUpload去下载。FileUpload依赖于commons-io,因此还要下载它。我们只需要将commons-fileupload-1.2.2.jarcommons-io-2.4.jar加入到项目的/WebRoot/WEB-INF/lib目录下。

3,       struts2实现文件上传,实际上是两步完成的

1)            首先将客户端上传的文件保存到struts.multipart.saveDir键所指定的目录中,如果该键对应的目录不存在,那么就保存到javax.servlet.context.tempdir环境变量所指定的目录中;

2)            Action中所定义的File类型的成员变量实际上指向的是临时目录的临时文件,然后在服务器端通过IO的方式将临时文件写入到指定服务器目录中。

文件上传:

风中叶之struts2学习笔记四_第1张图片

风中叶之struts2学习笔记四_第2张图片

4,        一个页面上传多个文件

风中叶之struts2学习笔记四_第3张图片

5,       Struts2默认最大上传文件大小是2M,我们可以在src目录下新建一个名为struts.properties的文件覆盖struts2-core-2.3.4.jar/org.apache.struts2/default.properties文件中的相关属性值。

文件大小处理:在struts.properties中设置struts.multipart.maxSize=A    A设置的尽量大一些,这样上传就不会出错,然后在程序中进行判断处理。

也可以在struts.xml中以常量的形式指定相关的属性值。

6,        文件下载

风中叶之struts2学习笔记四_第4张图片

风中叶之struts2学习笔记四_第5张图片

7,文件下载2

 

风中叶之struts2学习笔记四_第6张图片

风中叶之struts2学习笔记四_第7张图片

 

风中叶之struts2学习笔记四_第8张图片

8,        struts2可以使用struts2-convention-plugin-2.2.1.1.jar插件实现基于注解的配置

 风中叶之struts2学习笔记四_第9张图片

9,        异步处理请求返回XML,需要用到dom4j.jar         struts2整合jquery

<%@ 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 'getXML.jsp' starting page</title>

		<script type="text/javascript" src="scripts/jquery-1.4.4.js"></script>

		<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">
	-->

		<script type="text/javascript">
	function getInfo() {
		$
				.post(
						"getXMLAction.action",
						{
							name : $("#name").val()
						},
						function(returnedData, status) {
							var id = $(returnedData).find("id").text();
							var name = $(returnedData).find("name").text();
							var age = $(returnedData).find("age").text();
							var address = $(returnedData).find("address")
									.text();

							var html = "<table width='60%' border='1' align='center'>__tag_39$60_<th>id__tag_39$70_<th>name__tag_39$83_<th>age__tag_39$95_<th>address__tag_39$111_<tr align='center'>__tag_39$135_"
									+ id
									+ "__tag_39$149_<td>"
									+ name
									+ "__tag_39$170_<td>"
									+ age
									+ "__tag_39$190_<td>"
									+ address
									+ "__tag_39$214_</tr>__tag_39$224_";

							$("#theBody
</script>

	</head>

	<body id="theBody">

		<select id="name">

			<option value="zhangsan">
				zhangsan
			</option>
			<option value="lisi">
				lisi
			</option>

		</select>

		<input type="button" value="get information" onclick=
	getInfo();;
>


	</body>
</html>


GetXMLAction.java

package com.shengsiyuan.action.xml;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import com.opensymphony.xwork2.ActionSupport;

public class GetXMLAction extends ActionSupport
{
	private String name;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	
	@Override
	public String execute() throws Exception
	{
		//zhang san
		People people1 = new People();
		
		people1.setId(1);
		people1.setName("zhangsan");
		people1.setAge(30);
		people1.setAddress("beijing");
		
		People people2 = new People();
		
		people2.setId(2);
		people2.setName("lisi");
		people2.setAge(50);
		people2.setAddress("tianjin");
		
		Document document = DocumentHelper.createDocument();
		
		Element rootElement = document.addElement("persons");
		
		rootElement.addComment("This is comment!!");
		
		Element e = rootElement.addElement("person");
		
		Element idElement = e.addElement("id");
		Element nameElement = e.addElement("name");
		Element ageElement = e.addElement("age");
		Element addressElement = e.addElement("address");
		
		if("zhangsan".equals(name))
		{
			idElement.setText(people1.getId() + "");
			nameElement.setText(people1.getName());
			ageElement.setText(people1.getAge() + "");
			addressElement.setText(people1.getAddress());
		}
		else
		{
			idElement.setText(people2.getId() + "");
			nameElement.setText(people2.getName());
			ageElement.setText(people2.getAge() + "");
			addressElement.setText(people2.getAddress());
		}
		
		HttpServletResponse response = ServletActionContext.getResponse();
		
		response.setContentType("text/xml; charset=utf-8");
		response.setHeader("cache-control", "no-cache"); 
		
		PrintWriter out = response.getWriter();
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		
		XMLWriter writer = new XMLWriter(out, format);
		
		writer.write(document);
		
		out.flush();
		out.close();
		
		return null;
	}
}


struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
<struts>
	 
	<package name="struts2_ajax" extends="json-default">
	
		<action name="getXMLAction" class="com.shengsiyuan.action.xml.GetXMLAction">
		
		</action>
	
		<action name="getJsonAction" class="com.shengsiyuan.action.json.GetJsonAction">
		
		</action>
		
		<action name="getJsonAction2" class="com.shengsiyuan.action.json.GetJsonAction2">
			<result name="success" type="json">
				
				<param name="excludeProperties">address</param>
			
			</result>
		</action>
	
	</package>
	
	
</struts>


 

10,        异步处理请求返回JSON,需要用到json.jar,下面列出的代码是与xml不同的地方。

Struts2提供了struts2-json-plugin-2.3.4.jar插件,我们可以以另外的方式处理

 

<%@ 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 'json.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">
	-->
	<script type="text/javascript" src="scripts/jquery-1.4.4.js"></script>
	
	<script type="text/javascript">
	
	$(function()
	{
		$("#button1").click(function()
		{
			$.post("getJsonAction2.action",{name: $("#name").val()}, 
				function(returnedData, status)
			{
				var people = returnedData;
				
				var id = people.id;
				var name = people.name;
				var age = people.myAge;
				var address = people.address;
					
				var html = "<table width='60%' border='1' align='center'><tr><th>id</th><th>name</th><th>age</th><th>address</th><tr align='center'><td>" + id + "</td><td>" + name + "</td><td>" + age + "</td><td>" + address + "</td></tr></table>";
		
				$("#theBody table:eq(0)").remove();
			
				$("#theBody").append(html);
				
			});			
		});
	});
	
	</script>
	
	
  </head>
  
  <body id="theBody">
    
   <select id="name">

	<option value="zhangsan">zhangsan</option>
	<option value="lisi">lisi</option>

   </select>  
    
    
    <input type="button" value="get json content from server" id="button1">
    
  </body>
</html>


 GetJsonAction.java

package com.shengsiyuan.action.json;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.shengsiyuan.action.xml.People;

public class GetJsonAction extends ActionSupport
{
	private String name;
	
	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	@Override
	public String execute() throws Exception
	{
		People people = new People();
		
		people.setId(1);
		people.setName(name);
		people.setAge(30);
		people.setAddress("beijing");
		
		Gson gson = new Gson();
		
		String result = gson.toJson(people);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		
		response.setContentType("application/json; charset=utf-8");
		response.setHeader("cache-control", "no-cache"); 
		
		PrintWriter out = response.getWriter();
		
		out.print(result);
		
		out.flush();
		out.close();
		
		return null;
	}
}


GetJsonAction2.java

package com.shengsiyuan.action.json;

import org.apache.struts2.json.annotations.JSON;

import com.opensymphony.xwork2.ActionSupport;

public class GetJsonAction2 extends ActionSupport
{
	private String name;
	
	private int id;
	
	private int age;
	
	private String address;

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public int getId()
	{
		return id;
	}

	public void setId(int id)
	{
		this.id = id;
	}

	@JSON(name="myAge")
	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}

	public String getAddress()
	{
		return address;
	}

	public void setAddress(String address)
	{
		this.address = address;
	}
	
	@Override
	public String execute() throws Exception
	{
		this.id = 1;
		this.age = 30;
		this.address = "beijing";
		
		return SUCCESS;
	}
}


struts.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
    
<struts>
	 
	<package name="struts2_ajax" extends="json-default">
	
		<action name="getXMLAction" class="com.shengsiyuan.action.xml.GetXMLAction">
		
		</action>
	
		<action name="getJsonAction" class="com.shengsiyuan.action.json.GetJsonAction">
		
		</action>
		
		<action name="getJsonAction2" class="com.shengsiyuan.action.json.GetJsonAction2">
			<result name="success" type="json">
				
				<param name="excludeProperties">address</param>
			
			</result>
		</action>
	
	</package>
	
	
</struts>


 

你可能感兴趣的:(struts2)