一开始是做 获取表单请求的试验 但是我发现我一用struts,读取的内容就读不出来,如果仅仅是request.getParameter("XX")还可以读取到参数,但是getInputStream()就读不出来里面的信息,页面上显示的也是白板,部署时没问题,也没抛异常。但是如果不用struts的话,就一切正常。一开始我还以为是没导那些上传文件用的包的原因,后来发现其实是有的。请问各位大大到底什么原因?
解决方案 »
- 一些JS脚本错误的解决途径
- webservice 错误!
- 关于WebSphere解析request.getRequestURL()的问题
- 如何改变form里面,text和button的长度,宽度,字体?
- 怎么样定义一个空的Statement (在线等结)
- 常用日期处理方法SingTel-iWEB
- J2EE的工作轮廓是怎样的?
- 为什么总出现‘style’is null or not an object(急)
- 请问怎样在html或jsp中调用servlet?
- Product.jsp调用ProductServlet,ProductServlet查询数据库输出WEB页面给(如:表格)Product.jsp显示。代码该怎么写?
- 文件上传问题。
- 通过按钮获得div 的id
一开始InputStream是通过request.getInputStream()得到的,那么要clear()是new 一个InputStream出来吗?还是其他的什么?
不过我觉得这应该不是重点,因为在不用struts的时候,是可以很好的使用的之后我在网上查找解决方案时,看到了一个帖子,说是不用getInputStream()方法,用其他的方法从而达到上传的目的。然后我发现他提供的方法俺这里也不好使,他的方法是:commonUpload.jsp<%@ page language="java" import="java.util.*,org.apache.commons.fileupload.disk.*,java.io.*,
org.apache.commons.fileupload.servlet.*,org.apache.commons.fileupload.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><%
DiskFileItemFactory factory=new DiskFileItemFactory();
//设置上传工厂的限制
factory.setSizeThreshold(1024*1024*20);
factory.setRepository(new File(request.getRealPath("/")));
//创建一个上传文件的ServletFileUpload对象
ServletFileUpload upload=new ServletFileUpload(factory);
//设置上传文件最大接收20M
upload.setSizeMax(20*1024*1024);
//处理http请求,items是所有的表单项
List items=upload.parseRequest(request);
//遍历所有的表单项
for(Iterator it=items.iterator();it.hasNext();){
FileItem item=(FileItem)it.next();
if(item.isFormField()){
String name=item.getFieldName();
String value=item.getString("GBK");
out.println("表单域的name=value对为:"+name+"="+value+"<br/>");
}else{
//取得文件域的表单名
String fieldName=item.getFieldName();
//取得文件名
String fileName=item.getName();
//取得文件的类型
String cotentType=item.getContentType();
//以当前时间来生成文件的文件名
FileOutputStream fos=new FileOutputStream(request.getRealPath("/")+System.currentTimeMillis()
+fileName.substring(fileName.lastIndexOf("."),fileName.length()));
//如果上传文件域对应文件的内容已经在内存中
if(item.isInMemory()){
fos.write(item.get());
}else{
//如果文件内容不存在在内存中
//获取上传文件的输入流
InputStream is=item.getInputStream();
byte[] buffer=new byte[1024];
int len;
//读取上传文件的内容,并将其写入服务器的文件中
while((len=is.read(buffer))>0){
fos.write(buffer,0,len);
}
is.close();
fos.close();
}
}
}
%>
用了他的方法最后输出依旧是没有完成上传效果,然后我在
List items=upload.parseRequest(request);
代码后加上了一句out.println(items);
显示的结果是[]
也就是说在表单提交到页面的过程中还是什么都没取到我的表单页面application.jsp代码是:<%@ page language="java" import="java.util.*" contentType="text/html;charset=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 'application.jsp' starting page</title>
</head>
<body>
<form id="form1" name="form1" enctype="multipart/form-data" method="post" action="Login">
上传文件:<input type="file" name="file"/><br/>
请求参数:<input type="text" name="wawa"/><br/>
<input name="dd" type="submit" value="提交"/>
</form>
</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="devMode" value="true"></constant>
<package name="lee" namespace="/" extends="struts-default">
<action name="Login" class="lee.LoginAction">
<result name="success">/commonUpload.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
然后是LoginAction.javapackage lee;import com.opensymphony.xwork2.ActionSupport;public class LoginAction extends ActionSupport{ @Override
public String execute() throws Exception{
return SUCCESS;
}
最后是使用时的log:
2011-10-28 16:07:56,091 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@cb9c42], property=struts]
2011-10-28 16:07:56,092 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@cb9c42], property=org]
2011-10-28 16:07:59,161 INFO org.apache.struts2.dispatcher.Dispatcher.info:42 - Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir
2011-10-28 16:07:59,162 DEBUG org.apache.struts2.dispatcher.Dispatcher.debug:68 - saveDir=D:\JavaUseTools\apache-tomcat-7.0.11\apache-tomcat-7.0.11\work\Catalina\localhost\struts2_test_0800
2011-10-28 16:07:59,271 DEBUG org.apache.struts2.dispatcher.multipart.MultiPartRequest.debug:68 - Found item file
2011-10-28 16:07:59,271 DEBUG org.apache.struts2.dispatcher.multipart.MultiPartRequest.debug:68 - Item is a file upload
2011-10-28 16:07:59,272 DEBUG org.apache.struts2.dispatcher.multipart.MultiPartRequest.debug:68 - Found item wawa
2011-10-28 16:07:59,273 DEBUG org.apache.struts2.dispatcher.multipart.MultiPartRequest.debug:68 - Item is a normal form field
2011-10-28 16:07:59,273 DEBUG org.apache.struts2.dispatcher.multipart.MultiPartRequest.debug:68 - Found item dd
2011-10-28 16:07:59,274 DEBUG org.apache.struts2.dispatcher.multipart.MultiPartRequest.debug:68 - Item is a normal form field
2011-10-28 16:07:59,275 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@cb9c42], property=struts]
2011-10-28 16:07:59,276 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[com.opensymphony.xwork2.DefaultTextProvider@cb9c42], property=struts]
2011-10-28 16:07:59,276 DEBUG com.opensymphony.xwork2.DefaultActionProxy.debug:68 - Creating an DefaultActionProxy for namespace / and action name Login
2011-10-28 16:07:59,277 DEBUG com.opensymphony.xwork2.interceptor.I18nInterceptor.debug:68 - intercept '//Login' {
2011-10-28 16:07:59,279 DEBUG com.opensymphony.xwork2.interceptor.I18nInterceptor.debug:68 - applied invocation context locale=en
2011-10-28 16:07:59,280 DEBUG com.opensymphony.xwork2.interceptor.I18nInterceptor.debug:68 - before Locale=en
2011-10-28 16:07:59,280 DEBUG com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.debug:68 - Setting static parameters {}
2011-10-28 16:07:59,281 DEBUG com.opensymphony.xwork2.interceptor.ParametersInterceptor.debug:68 - Setting params NONE
2011-10-28 16:07:59,281 DEBUG com.opensymphony.xwork2.interceptor.ParametersInterceptor.debug:68 - Setting params dd => [ 提交 ] file => [ D:\JavaUseTools\apache-tomcat-7.0.11\apache-tomcat-7.0.11\work\Catalina\localhost\struts2_test_0800\upload__7f40b9a_1334992381b__8000_00000000.tmp ] fileContentType => [ text/plain ] fileFileName => [ eclipse快捷键.txt ] wawa => [ ]
2011-10-28 16:07:59,288 DEBUG org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.debug:68 - Validating //Login with method execute.
2011-10-28 16:07:59,289 DEBUG com.opensymphony.xwork2.validator.ValidationInterceptor.debug:68 - Invoking validate() on action lee.LoginAction@ebf121
2011-10-28 16:07:59,289 DEBUG com.opensymphony.xwork2.interceptor.PrefixMethodInvocationUtil.debug:68 - cannot find method [validateExecute] in action [lee.LoginAction@ebf121]
2011-10-28 16:07:59,290 DEBUG com.opensymphony.xwork2.interceptor.PrefixMethodInvocationUtil.debug:68 - cannot find method [validateDoExecute] in action [lee.LoginAction@ebf121]
2011-10-28 16:07:59,291 DEBUG com.opensymphony.xwork2.DefaultActionInvocation.debug:68 - Executing action method = null
2011-10-28 16:07:59,292 DEBUG org.apache.struts2.dispatcher.ServletDispatcherResult.debug:68 - Forwarding to location /commonUpload.jsp
2011-10-28 16:07:59,292 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[lee.LoginAction@ebf121, com.opensymphony.xwork2.DefaultTextProvider@cb9c42], property=struts]
2011-10-28 16:07:59,298 DEBUG com.opensymphony.xwork2.conversion.impl.InstantiatingNullHandler.debug:68 - Entering nullPropertyValue [target=[lee.LoginAction@ebf121, com.opensymphony.xwork2.DefaultTextProvider@cb9c42], property=org]
2011-10-28 16:07:59,301 DEBUG com.opensymphony.xwork2.interceptor.I18nInterceptor.debug:68 - after Locale=en
2011-10-28 16:07:59,302 DEBUG com.opensymphony.xwork2.interceptor.I18nInterceptor.debug:68 - intercept }那位大哥 行行好 帮俺分析一下 ~~~~~~~~实在是郁闷了很久了
我的enctype属性设置的是multipart/form-data
就算enctype属性用的是默认值,也是应该能够取到文件域file,文本域wawa,提交按钮bb,这三个参数才对
然后你说的那个去配置文件里找InputStream跟的参数 应该去哪里找呢?
先不说流怎么获取,我感觉你把struts1的方式用在struts2上了
我说下思路,不知道能不能帮你解决,我是先学用struts2,然后才学用struts1的
表单type="file" name="upload"
struts2获取jsp传过来的数据,不需要request.get这个方法。从action传到jsp页面也是不用request.set这个方法,都是对应着javabean 在action方法中做set get 的方法就可以获取到数据或传出数据
要想获取file这个文件,在对应的action方法中
定义3个private file upload ,String uploadFileName;String uploadContentType 后面2个是必须这么写的,set get 一下
然后就可以获取file upload 整个文件了
附加点代码比较明了
public class GiftAction {
private static final int BUFFER_SIZE = 16 * 1024;
private IntfInfoService intfService; private List<GiftInfo>giftinfolist;
private GiftInfo giftInfo;
private int currentPage = 1;// 当前页
private int rsCount=0; //总记录数
private int giftid;
private String savePath;//常量,由struts.xml中的action节点的param子节点获得
private File upload; // 上传文件域对象
private String uploadFileName; // 上传文件名
private String uploadContentType; // 上传文件类型
public String getSavePath() {
return savePath;
} public void setSavePath(String savePath) {
this.savePath = savePath;
} 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 addGiftinfo(){//添加礼品
String realpath=ServletActionContext.getServletContext().getRealPath(savePath);
String newFileName=getnewFileName(uploadFileName);
File target=new File(realpath+"/"+newFileName);
try {
copy(upload, target);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
giftInfo.setImage(newFileName);
intfService.addgift(giftInfo);
try {
HttpServletResponse response = ServletActionContext.getResponse(); PrintWriter out;
out = response.getWriter();
String message = new String("填加成功!是否继续添加?".getBytes(), "ISO-8859-1");
out.print("<script>if(window.confirm('"+message+"')){window.history.back();}else{location.href='INTF/GiftAction!selectGiftinfo'}</script>");
out.flush();
out.close();
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private String getnewFileName(String uploadFileName) {//编辑上传文件的名字
String name=System.currentTimeMillis+uploadFileName.substring (uploadFileName.lastIndexOf(".",
uploadFileName.length()));
return name;
}
public void copy(File src, File target) throws Exception {//上传到文件夹中
InputStream in = new BufferedInputStream(new FileInputStream(src));
OutputStream out = new BufferedOutputStream(
new FileOutputStream(target));
int len = 0;
byte[] b = new byte[BUFFER_SIZE];
while ((len = in.read(b)) > 0) {
out.write(b, 0, len);
out.flush();
}
in.close();
out.close();
}
Why is parseRequest() returning no items? This most commonly happens when the request has already been parsed, or processed in some other way. Since the input stream has aleady been consumed by that earlier process, it is no longer available for parsing by Commons FileUpload. I'm using FileUpload in an Action, but it's not working. Why? Struts 1 recognises multipart requests, and parses them automatically, presenting the request parameters to your code in the same manner as if they were regular request parameters. Since Struts has already processed the request, and made it available in your form bean, the input stream is no longer available for parsing, so attempting to do so with FileUpload will fail. But I need to parse the request myself. How can I do that?
Struts 1 parses multipart a request as a part of the process of populating your form bean from that request. If, for some reason, you need to have full control over the multipart parsing, you can do so by configuring your action mapping without an associated form bean. (A better way of doing this, however, is to replace the default multipart handler with your own. See the Struts 1 documentation for details.) 其实也就是request已经被解析过了,
在之后再用request.getInputStream()也好,
parseRequest(request)也罢,就都什么也取不出来了然后我就想已经被解析过了的东西都去哪了?然后再看了下别人关于struts文件上传的视频,
才发现根本就不是我这样用的,就是设置几个变量及其get set方法就行了而我的这段代码呢,只是别人想说明底层实现用的
后来我新建了个web项目,没有用Action,没有用struts.xml,
在lib文件夹下只放了commons-io-2.1.jar,commons-fileupload-1.2.2.jar
然后程序就正常运行了,不过如果上传的是有中文路径的会有点问题,当然这是以后要解决的问题了总得来说,我只所以会以为用了struts 取不到东西,只是 request已经被解析过了,它有自己的处理方式,要自己来就还要特殊的处理好歹解决了心中的一个疑惑,非常感谢楼上诸君的热心帮助那么在下就此结贴了