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;
}
struts2 上传下载文件,异常处理,数据类型转换的更多相关文章
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- 初级版python登录验证,上传下载文件加MD5文件校验
服务器端程序 import socket import json import struct import hashlib import os def md5_code(usr, pwd): ret ...
- 向linux服务器上传下载文件方式收集
向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...
- python实现socket上传下载文件-进度条显示
在python的socket编程中,可以实现上传下载文件,并且在下载的时候,显示进度条,具体的流程如下图所示: 1. 服务器端代码如下: [root@python 519]# cat server.p ...
- 【WCF】利用WCF实现上传下载文件服务
引言 前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...
- java web service 上传下载文件
1.新建动态web工程youmeFileServer,新建包com,里面新建类FileProgress package com; import java.io.FileInputStream; imp ...
- WebSSH画龙点睛之lrzsz上传下载文件
本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...
- Jmeter 上传下载文件
最近很多同学都在问jmeter上传.下载文件的脚本怎么做,要压测上传.下载文件的功能,脚本怎么做,网上查了都说的很含糊,这次呢,咱们就好好的把jmeter的上传下载文件好好缕缕,都整明白了,怎么个过程 ...
- rz和sz上传下载文件工具lrzsz
######################### rz和sz上传下载文件工具lrzsz ####################################################### ...
随机推荐
- Smarty的原理_面试
Smarty是一个模板引擎,使用smarty主要是为了实现逻辑和外在内容的分离,如果不使用模板的话,通常的做法就是php代码和html代码混编.使用了模板后,则可以将业务逻辑放到php文件中,而负责显 ...
- cas单点登陆系统-casServer搭建
最近工作比较忙,空闲的时间在搞单点登陆系统,自己写了一套SSO在GitHub上,过程走通了.通过这个例子,自己熟悉了流程,而且破天荒的使用了抽象设计模式,并且熟悉了cookies和session的使用 ...
- Java Web之Servlet中response、request乱码问题解决
Java Web之Servlet中response.request乱码问题解决 一.request请求参数出现的乱码问题 get请求: get请求的参数是在url后面提交过来的,也就是在请求行中, ...
- D11——C语言基础学PYTHON
C语言基础学习PYTHON——基础学习D11 20180908内容纲要: 1.RabbitMQ消息队列 (1)RabbitMQ安装 (2)Rabbits示例 模式一:fanout 模式二:direct ...
- LeetCode题解-147 对链表进行插入排序 Medium
对链表进行插入排序. 插入排序的动画演示如上.从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示). 每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中. 插 ...
- Windows平台下Git服务器搭建--------gitblit
Windows(server)平台下Git服务器搭建 第一步:下载Java,安装,配置环境变量. 第二步:下载Gitblit.下载地址:http://www.gitblit.com/ 第三步:解压缩下 ...
- PHP查找与搜索数组元素
in_array()函数 in_array()函数在一个数组汇总搜索一个特定值,如果找到这个值返回true,否则返回false.其形式如下: boolean in_array(mixed needle ...
- Vue.js系列之二Vue实例
每个Vue应用都是通过Vue函数创建一个新的Vue实例开始,代码如下: var vm=new Vue({}); {}是创建Vue应用时的参数对象 1.Vue实例的data属性 当一个Vue对象被创建时 ...
- Filter应用之2-设置某些页面缓存或是不缓存
要想让所有浏览器不缓存页面,需要在每个jsp上加上: <% response.setHeader("expires","-1"); response.se ...
- puppet的使用:puppet的hello world
这个例子完成将master节点上的一个文件放至agent节点上的功能 创建要传输的文件 echo "helloWorld" > /etc/puppet/modules/pup ...