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 ####################################################### ...
随机推荐
- CDN添加流程
CDN的全称是Content Delivery Network,即内容分发网络.其基本思路是尽可能避开互联网上有可能影响数据传输速度和稳定性的瓶颈和环节,使内容传输的更快.更稳定.通过在网络各处放置节 ...
- Java线程代码实现
线程的Java实现 参考博客:(http://www.importnew.com/20672.html) 1.继承Thread 声明Thread的子类; 这种方法是创建类继承Thread,然后重写Th ...
- 【13】JMicro微服务-ID生成与Redis
如非授权,禁止用于商业用途,转载请注明出处作者:mynewworldyyl 往下看前,建议完成前面1到12小节 1. 微服务中ID地位 如果说前面小节的功能点是微服务的大脑,那么全局唯一ID则是微服务 ...
- 【2018北京集训6】Lcm DFT&FWT
首先我们来看下此题的模数232792561. 232792561=lcm(1,2,3.......20)+1.这个性质将在求值时用到. 我们将n分解质因数,令$m$为$n$的素因子个数,设n=$\Pi ...
- Swift 基本数据类型与运算符表达式
// // main.swift // LessonSwift01 // // Created by lanouhn on 16/1/25. // Copyright © 2016年 齐彦坤. All ...
- apache2.4脚本一键安装(linux环境)
1.下载apache安装包和相关组件 下载地址:https://pan.baidu.com/s/1o85i6Jw 其中包括 apache安装包:httpd-2.4.29.tar.gz apache安装 ...
- <context:component-scan>详解 转发 https://www.cnblogs.com/fightingcoding/p/component-scan.html
<context:component-scan>详解 默认情况下,<context:component-scan>查找使用构造型(stereotype)注解所标注的类,如@ ...
- github的本地配置和项目创建
之前完成了github的安装和账号的注册,接下来要进行项目的创建和本地代码仓库的建立 1.创建项目 2.填写项目相关信息 注意:在给项目起名时,尽量起一些有意义的名字,否则会被管理员删除.因为服务器上 ...
- pthon获取word内容之获取表单
需求:把word里面的表单内容获取 按照规则拼成字符串 转换成类似下面的样子 代码如下: from docx import Document import re def parse_docx(f): ...
- 补间动画Tweened Animations
本例子简单讲一下怎么用补间动画 1.在xml中定义好动画的资源文件,如下(注意把不同的效果放在一起可以一起用,同时起效果) <?xml version="1.0" encod ...