一,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 上传下载文件,异常处理,数据类型转换的更多相关文章

  1. C#实现http协议支持上传下载文件的GET、POST请求

    C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...

  2. 初级版python登录验证,上传下载文件加MD5文件校验

    服务器端程序 import socket import json import struct import hashlib import os def md5_code(usr, pwd): ret ...

  3. 向linux服务器上传下载文件方式收集

    向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...

  4. python实现socket上传下载文件-进度条显示

    在python的socket编程中,可以实现上传下载文件,并且在下载的时候,显示进度条,具体的流程如下图所示: 1. 服务器端代码如下: [root@python 519]# cat server.p ...

  5. 【WCF】利用WCF实现上传下载文件服务

    引言     前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...

  6. java web service 上传下载文件

    1.新建动态web工程youmeFileServer,新建包com,里面新建类FileProgress package com; import java.io.FileInputStream; imp ...

  7. WebSSH画龙点睛之lrzsz上传下载文件

    本篇文章没有太多的源码,主要讲一下实现思路和技术原理 当使用Xshell或者SecureCRT终端工具时,我的所有文件传输工作都是通过lrzsz来完成的,主要是因为其简单方便,不需要额外打开sftp之 ...

  8. Jmeter 上传下载文件

    最近很多同学都在问jmeter上传.下载文件的脚本怎么做,要压测上传.下载文件的功能,脚本怎么做,网上查了都说的很含糊,这次呢,咱们就好好的把jmeter的上传下载文件好好缕缕,都整明白了,怎么个过程 ...

  9. rz和sz上传下载文件工具lrzsz

    ######################### rz和sz上传下载文件工具lrzsz ####################################################### ...

随机推荐

  1. 【python入门】之教你编写自动获取金币脚本

    本文作者:青衫磊落 最近看到个特别全面源码分享网站,刚好有个项目是一直想做但是没有头绪的,就想下载学习一下.注册账号后,发现还需要若干金币.后来发现可以通过每隔一定时间发心情状态来获得金币,就打算写一 ...

  2. Storm Trident详解

    Trident是基于Storm进行实时留处理的高级抽象,提供了对实时流4的聚集,投影,过滤等操作,从而大大减少了开发Storm程序的工作量.Trident还提供了针对数据库或则其他持久化存储的有状态的 ...

  3. JavaScript函数学习总结(一)---函数定义

    博客原文地址:Claiyre的个人博客 如需转载,请在文章开头注明原文地址 在许多传统的OO语言中,对象可以包含数据,还可拥有方法,也就是属于该对象的函数.但在JavaScript中,函数也被认为是一 ...

  4. apt小问题

    安装软件遇到情况,一直等待: root@test-xxx:/opt# apt-get install vsftpdReading package lists... DoneBuilding depen ...

  5. Oracle 数据类型 与C#映射关系

    大部分类型的对应关系:原文:http://2143892.blog.51cto.com/2133892/499353 序号 Oracle数据类型 .NET类型 GetOracleValue类型 DbT ...

  6. 在vue项目中安装使用Mint-UI

    一.Mint UI 是 由饿了么前端团队推出的 一个基于 Vue.js 的移动端组件库,具有以下特性:       使用文档: http://mint-ui.github.io/#!/zh-cn Mi ...

  7. Ubuntu Cannot run program "../SDK/build-tools/xxx/aapt": erro = 2 No such file or directory

    64位ubuntu Android Studio  Gradle编译时出现如下报错: java.io.IOException: Cannot run program "/home/king/ ...

  8. Git&GitHub学习日志

    Git是一个开源的分布式版本控制系统,用以有效.高速的处理从很小到非常大的项目版本管理. Git是Linus Torvalds为了帮助管理Linux内核开发而开发的一个开放源码的版本控制软件.作为一个 ...

  9. win10下用Linux搭建python&nodejs开发环境

    Win10下用自带Linux系统搭建开发环境 Win10下用自带Linux系统搭建开发环境启用Linux老版本(win10 1709之前):新版本(win10 1709之后)卸载linux老版本新版本 ...

  10. SPSS学习系列之SPSS Modeler (简称SPSS)是什么?

    不多说,直接上干货! 推荐博客 SPSS学习系列之SPSS Statistics(简称SPSS)是什么? 官方简介: SPSS Modeler 是全球领先的数据挖掘.预测分析平台软件,拥有简单的图形界 ...