struts2 上传下载文件,异常处理,数据类型转换

一,web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- 404页面,全局 --><!--
  <error-page>
  	<error-code>404</error-code>
  	<location>/404.jsp</location>
  </error-page>
  -->
  </web-app>

 二,action

PointAction 
package com.direct.action;

import java.util.Date;

import com.direct.model.Point;
import com.opensymphony.xwork2.ActionSupport;

public class PointAction extends ActionSupport{

	public String getpoint(){
		//   使用配置文件连接两个类,实现相应的类型转换
		System.out.println(point);
		System.out.println(birthday);
		System.out.println(salary);
		System.out.println("数据类型uname:"+uname.getClass().getName());
		return "point";
	}
	
	private String uname;
	private Point point;
	private Date birthday;
	private double salary;
	public String getUname() {
		return uname;
	}
	public void setUname(String name) {
		this.uname = name;
	}
	public Point getPoint() {
		return point;
	}
	public void setPoint(Point point) {
		this.point = point;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	
}

 CarAction 

package com.direct.action;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.direct.model.Car;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class CarAction extends ActionSupport{

	private Car car;
	public String getcar(){
		
	//	System.out.println(car.getCarid()+"---"+car.getCarname()+"---"+car.getCarsize()+"----"+car.getPrice());
		ActionContext.getContext().put("car", car);//  一次请求
		ActionContext.getContext().getSession().put("id", 2);//一次会话
		ActionContext.getContext().getApplication().put("name", "小白");//application
		
		//  原生态
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("address", "重庆");
		HttpSession session = request.getSession();
		session.setAttribute("sex", "女");
		ServletContext application = ServletActionContext.getServletContext();
		application.setAttribute("hobby", "sleep");
		
		return "getcar";
	}
	public Car getCar() {
		return car;
	}
	public void setCar(Car car) {
		this.car = car;
	}
	
}

  GoodsAction

package com.direct.action;

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

public class GoodsAction extends ActionSupport{
	
	private String goodsname;
	private String goodsprice;
	
	public String addgoods(){
		ActionContext.getContext().put("goodsname", goodsname);
		ActionContext.getContext().put("goodsprce", goodsprice);
		System.out.println(goodsname+"----"+goodsprice);
		return "addgoods";
	}
	public String getGoodsname() {
		return goodsname;
	}
	public void setGoodsname(String goodsname) {
		this.goodsname = goodsname;
	}
	public String getGoodsprice() {
		return goodsprice;
	}
	public void setGoodsprice(String goodsprice) {
		this.goodsprice = goodsprice;
	}

	
}

  FileupAction 文件上传与下载

package com.direct.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;


import org.apache.struts2.ServletActionContext;

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

public class FileupAction extends ActionSupport{

	private File[] upload;//上传的文件
	private String[] uploadFileName;//文件名
	private String[] uploadContentType;//文件类型
	private String filename;
	
	//多个文件上传
	public String upload() throws IOException{
		
		String path = ServletActionContext.getServletContext().getRealPath("/");
		File file = new File(path+"upfile/");
		if (! file.exists() && !( file.isDirectory())) {
			file.mkdir();
		}
		//   循环上传多个文件
		for (int i = 0; i < uploadFileName.length; i++) {
			//  输出流,放在服务器的目录下
			FileOutputStream fos = new FileOutputStream(file+"/"+uploadFileName[i]);
				//   输入流
			FileInputStream fis = new FileInputStream(upload[i]);
			byte[]  bt = new byte[1024];
			int len = 0;
			while((len=fis.read(bt))>0){
				fos.write(bt,0,len);
			}
		}
		showlist();
		return "upload";
	}
	
	//  下载文件,在xml中配置
	public InputStream  getTfile(){
		return ServletActionContext.getServletContext().getResourceAsStream("upfile/"+filename);
	}
	
	public String showlist(){
		String path = ServletActionContext.getServletContext().getRealPath("/");
		File file = new File(path+"upfile/");
		File[] files = file.listFiles();
		ArrayList<String> listfile = new ArrayList<String>(); 
  		for (File f : files) {
			listfile.add(f.getName());//  存入文件名
		}
  		ActionContext.getContext().put("listfile", listfile);
  		return "listfile";
	}
	
	
	//   限制上传文件类型
	public void validateUpload(){
		for (int i = 0; i < uploadFileName.length; i++) {
			if ("text/plain".equals(uploadContentType[i])) {
				addFieldError("fileerror", "上传文件类型不支持");
			}
		}
		
	}

	public File[] getUpload() {
		return upload;
	}
	public void setUpload(File[] upload) {
		this.upload = upload;
	}
	public String[] getUploadFileName() {
		return uploadFileName;
	}
	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}
	public String[] getUploadContentType() {
		return uploadContentType;
	}
	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		try {
			filename = new String(filename.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.filename = filename;
	}
	
	
}

  

三,interceptor

package com.direct.interceptor;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class Myinterceptor  extends AbstractInterceptor{

	/*
	 *继承AbstrctInterceptor 的拦截器会拦截所有的action类
	 *继承MethodFilterInterceptor  只会拦截需要拦截的方法
	 * 拦截类(non-Javadoc)
	 * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
	 */
	@Override
	public String intercept(ActionInvocation arg0) throws Exception {
		String actionName = arg0.getProxy().getActionName();
		String method = arg0.getProxy().getMethod();
		System.out.println("拦截器的:"+actionName+"---->"+method);
		
		String invoke = arg0.invoke();
		return invoke;
	}

	
}

四,converter

从页面获取字符串,由逗号隔开。把这个有两个数字的字符串类型转换为 点对象‘

package com.direct.converter;

import java.util.Map;

import com.direct.model.Point;

import ognl.DefaultTypeConverter;

public class PointConverter extends DefaultTypeConverter{

	@Override
	public Object convertValue(Map context, Object value, Class toType) {
		if (toType==Point.class) {
			String[] param =  (String[])value;
			String[] split = param[0].split(",");
			int int1 = Integer.parseInt(split[0]);
			int int2 = Integer.parseInt(split[1]);
			Point point = new Point(int1, int2);
			
			return point;
		}
		
		return null;
	}
}

 PointAction-conversion.properties 转换的配置文件,放在与action同级目录下

取名与转换的action名一致

point=com.direct.converter.PointConverter

五,jsp

 index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s"  uri="/struts-tags"%>
<%
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 'index.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>

<br/>
  <hr/>
  <form action="${pageContext.request.contextPath }/goods_addgoods.action" method="post"> 
  <s:token></s:token>
  	商品名称:<input  type="text"  name="goodsname" value=""/><br/>
  商品价格:<input type="text"  name="goodsprice"   value=""/>
  <input type="submit" value="提交">
</form>
  <hr/>
  
  <form action="${pageContext.request.contextPath }/point_getpoint.action" method="post">
  	姓名:<input type="text" name="uname" /><br/>
  	生日:<input type="text" name="birthday"/><br/>
  	月薪:<input type="text" name="salary"/><br/>
  	<hr/>
   一个点的坐标:<input type="text" name="point"/><br/>
  <input type="submit" value="提交">
  </form>
  </body>
</html>

 fileup.jsp 

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@  taglib  uri="/struts-tags" prefix="s"%>
<%
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 'fileup.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> 
  上传的文件:<br/>
  <form   action="${pageContext.request.contextPath }/upfile_upload.action" enctype="multipart/form-data" method="post"> 
  	文件一:<input type="file" name="upload" /><br/>
  	文件二:<input type="file" name="upload" /><br/>
  		文件三:<input type="file" name="upload" /><br/>
 <input type="submit" value="提交"/>
  </form>
  <s:fielderror></s:fielderror>
  <s:fielderror fieldName="fileerror"></s:fielderror>
  <a href="${pageContext.request.contextPath }/upfile_showlist.action">前往下载</a>

  </body>
</html>

  downfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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 'downfile.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> 
    
    显示下载的文件名:<br/>
    <c:forEach items="${listfile}" var="item">
    <a href="${pageContext.request.contextPath }/filedownload.action?filename=${item}" >${item }</a><br/>
    </c:forEach>
    <hr/>
    
  </body>
</html>

  main.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 'main.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>
    <br/>
    <form action="${pageContext.request.contextPath }/car_getcar.action"  method="post">
    	车编号:<input type="text" name="car.carid" value=""/><br/>
    	车名称:<input type="text" name="car.carname" value=""/><br/>
    	车型号:<input type="text" name="car.carsize" value=""/><br/>
    	价格:<input type="text" name="car.price" value=""/><br/>
    	<input type="submit" value="提交"/>
    </form>
  </body>
</html>

  userinfo.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 'userinfo.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>
   userinfo.jsp
   <br/>
   汽车信息:${car.carid }/${car.carname }/${car.carsize }/${car.price }<br/>
   人员信息:${id }/${name }/${sex }/${address }/${hobby }
   <hr/>
   商品信息:<br/>
   商品名称:${goodsname }<br/>
   商品价格:${goodsprice }
  </body>
</html>

 六,struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.i18n.encoding" value="utf-8"></constant>
	<package name="pk" namespace="/" extends="struts-default">
	<!-- 自定义拦截器 -->
	<interceptors>
		<interceptor name="myinterceptor" class="com.direct.interceptor.Myinterceptor">
			<param name="includeMethods">selete_*,add_*</param><!-- 需要拦截的方法 -->
			<param name="excludeMethods">query_*</param><!-- 不需要拦截的方法 -->
		</interceptor>
		<interceptor-stack name="mystack">
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<interceptor-ref name="myinterceptor"></interceptor-ref>
		</interceptor-stack>
	</interceptors>
	
	<default-interceptor-ref name="mystack"></default-interceptor-ref>
	
	<!-- 全局异常处理,在局部找不到在找全局 -->
		<!--<global-results>
			<result name="gex">/exception.jsp</result>
		</global-results>
		<global-exception-mappings>
			<exception-mapping result="gex" exception="java.lang.Exception"></exception-mapping>
		</global-exception-mappings>
	
	   -->
	
		<action name="user_*" method="{1}" class="com.direct.action.UserAction" >
			<!-- UserAction类,局部异常处理,必须放在action前面 -->
			<result name="ex">/exception.jsp</result>
			<exception-mapping result="ex" exception="java.lang.Exception"></exception-mapping>
			
			<result name="success">/main.jsp</result>  <!-- 返回值为success,跳转页面 -->
			<result name="query" type="dispatcher">/userinfo.jsp</result>  <!-- 默认是dispatcher -->
			<result name="three" type="redirect">http://www.baidu.com</result>
			<result name="one"  type="redirect">user_select.action?userid=20&usersex=nv</result>
			<result name="two" type="redirectAction">
				<param name="actionName">/user_two.action</param>
				<param name="username">张三</param>
			</result>
			<result name="twouser" type="chain">user_login</result><!-- 只能chain跳转到方法 -->
			
			<result name="select" type="dispatcher">
				<param name="location">/main.jsp</param>
			</result>
			<!-- plainText 输出页面源码 -->
			<result name="text" type="plainText">/main.jsp</result>
		</action> 
		
		<action name="car_*" class="com.direct.action.CarAction"  method="{1}">
			<result name="getcar">/userinfo.jsp</result>
		</action>
		
		<action name="goods_*" class="com.direct.action.GoodsAction" method="{1}">
		<!-- token拦截,当表单提交后,再次没刷新页面重新提交不会进入action,就跳入错误提示页面invalid.token -->
			<interceptor-ref name="token">
				<param name="includeMethods">add*</param>
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<result name="addgoods">/userinfo.jsp</result>
			<result name="invalid.token">/error.jsp</result>
		</action>
		<action name="point_*" class="com.direct.action.PointAction" method="{1}">
			<result name="point">/userinfo.jsp</result>
		</action>
		
		<action  name="upfile_*"  class="com.direct.action.FileupAction" method="{1}">
			<interceptor-ref name="fileUpload"><!-- 自带的文件过滤器 -->
				<param name="allowedType">jpg,png,excel</param><!-- 允许上传的文件类型 -->
				<param name="maximumSize">5000</param><!-- 文件大小 -->
			</interceptor-ref>
			<interceptor-ref name="defaultStack"></interceptor-ref>
			<result name="upload">/downfile.jsp</result>
			<result name="input">/fileup.jsp</result>
			<result name="listfile" >/downfile.jsp</result>
		</action>
		<!-- 文件下载配置 -->
		<action name="filedownload" class="com.direct.action.FileupAction">
			<result name="success" type="stream">
				<param name="inputName">tfile</param>
				<param name="contentDisposition">attachment;fileName="${filename}"</param>
				<param name="bufferSize">4096</param>
			</result>
		</action>
		
	</package>


</struts>    

  七,两个实体类 Car  和 Point

    必须有get 和 set 方法 ,action就是先执行对象的get , set 方法进行传值。我在这简写了

package com.direct.model;

public class Car {

    private int carid;
    private String carname;
    private String carsize;
    private String price;
}
package com.direct.model;

public class Point {

    private int x;
    private int y;
    
}
原文地址:https://www.cnblogs.com/nn369/p/8057640.html