首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java Web开发 >

帮帮忙 兑现struts上传

2011-12-15 
帮帮忙 实现struts上传原来的代码如下:AActionForm.javapackagecom.sql.strutsimportorg.apache.struts.a

帮帮忙 实现struts上传
原来的代码如下:
AActionForm.java

package   com.sql.struts;

import   org.apache.struts.action.ActionForm;

public   class   AActionForm   extends   ActionForm{
        String   id=null;
        String   name=null;
        String   password=null;
        public   String   getId()   {
              return   id;
        }
        public   void   setId(String   id)   {
            this.id   =   id;
        }
        public   String   getName()   {
              return   name;
        }
        public   void   setName(String   name)   {
              this.name   =   name;
        }
        public   String   getPassword()   {
              return   password;
        }
        public   void   setPassword(String   password)   {
              this.password   =   password;

        }

}

DBConn.java
package   com.sql.struts;

import   java.sql.*;

public   class   DBConn{

        String   sDBDriver= "org.gjt.mm.mysql.Driver ";
String   sConnStr= "jdbc:mysql://127.0.0.1:3306/strutsdatabase?user=root&password=123456&useUnicode=true&characterEncoding=ISO-8859-1 ";

        Connection   conn=null;

        ResultSet   rs=null;
        public   DBConn(){

              try{
            Class.forName(sDBDriver);

                }

                catch(java.lang.ClassNotFoundException   e){

                        System.out.println( "Jdbc_conn(): "+e.getMessage());
      }

        }

  public   void   executeUpdate(String   sql)throws   Exception{
//sql=new   String(sql.getBytes( "GBK "), "ISO8859_1 ");
  try{
  conn=DriverManager.getConnection(sConnStr);
  Statement   stmt=conn.createStatement();
  stmt.executeUpdate(sql);
conn.close();
stmt.close();
}
catch(SQLException   ex){
  System.out.println( "sql.executeUpdate: "+ex.getMessage());
  }
  }
  public   ResultSet   executeQuery(String   sql)throws   Exception{
    rs=null;
  try{
sql=new   String(sql.getBytes( "ISO-8859-1 "));
conn=DriverManager.getConnection(sConnStr);
  Statement   stmt=conn.createStatement();
    rs=stmt.executeQuery(sql);

                }


    catch(SQLException   ex){
  System.out.println( "sql.executeQuery: "+ex.getMessage());
}

  return   rs;
}

  public   void   CloseConn()  
  throws   Exception   {
  try
  {
    if   (rs!=null)

rs.close();
  if   (conn!=null)

    conn.close();

  }

  catch(SQLException   ex)

    {
  System.out.println   ( "closeConn:   "   +   ex);
  }
  }

}


DisplayAction.java
package   com.sql.struts;
import   java.sql.ResultSet;
import   java.sql.SQLException;
import   javax.servlet.http.HttpServletRequest;
import   javax.servlet.http.HttpServletResponse;
import   org.apache.struts.action.Action;
import   org.apache.struts.action.ActionForm;
import   org.apache.struts.action.ActionForward;
import   org.apache.struts.action.ActionMapping;

import   com.sql.struts.AActionForm;
import   com.sql.struts.DBConn;

public   class   DisplayAction   extends   Action   {
        public   ActionForward   execute(ActionMapping   mapping,   ActionForm   form,
                      HttpServletRequest   request,   HttpServletResponse   response)   throws   Exception   {

        AActionForm   pForm   =   (AActionForm   )   form;
if   (pForm     ==   null);

            DBConn   db   =   new   DBConn();
              boolean   okFlag   =   false;
              try   {
                    String   SQLStr   =   "INSERT   INTO   test   SET   ID= ' "+pForm.getId()+ " ',   name= ' "+pForm.getName()+ " ',   password= ' "+pForm.getPassword()+ " '   ";
                   
                    db.executeUpdate(SQLStr);
              }   catch   (SQLException   ex)   {
                    System.out.print( "Logon   Error£º "   +   ex.getMessage());
              }   finally   {
                  db.CloseConn();
                  okFlag   =   true;
              }
              if(okFlag){
                    return   (mapping.findForward( "success "));
              }else{
                    return   (mapping.findForward( "failure "));
              }
        }
}




display_all.jsp
<%@   page   contentType= "text/html;charset=gb2312 "   language= "java "%>

<%@   taglib   uri= "/WEB-INF/struts-bean.tld "   prefix= "bean "%>

<%@   taglib   uri= "/WEB-INF/struts-html.tld "   prefix= "html "%>

<%@   taglib   uri= "/WEB-INF/struts-logic.tld "   prefix= "logic "%>

<!DOCTYPE   HTML   PUBLIC   "-//W3C//DTD   HTML   4.01   Transitional//EN ">

<html:html   locale= "true ">

<head>

        <html:base   />

        <title>
display_all.jsp
</title>

<body>

        <table>

        <logic:present   name= "array "   scope= "request ">

              <logic:iterate   name= "array "   id= "array "   type= "com.sql.struts.AActionForm ">

                      <tr   align= "center ">

                            <td   class= "table2 ">

                                    <bean:write   name= "array "   property= "id "   />

                            </td>

                            <td   class= "table2 ">

                                    <bean:write   name= "array "   property= "name "   />

                            </td>

                            <td   class= "table2 ">
                                    <bean:write   name= "array "   property= "password "   />
                        </td>
                      </tr>

              </logic:iterate>
        </logic:present>
        </table>
</body>
</html:html>

Index01.jsp
<%@   page     contentType= "text/html;charset=gb2312 "   language= "java "   %>

<%@   taglib   uri= "/WEB-INF/struts-bean.tld "   prefix= "bean "   %>
<%@   taglib   uri= "/WEB-INF/struts-html.tld "   prefix= "html "   %>
<%@   taglib   uri= "/WEB-INF/struts-logic.tld "   prefix= "logic "   %>


<!DOCTYPE   HTML   PUBLIC   "-//W3C//DTD   HTML   4.01   Transitional//EN ">
<html:html>
    <head>
        <html:base   />
  <title> submit </title>
</head>
<body>
<html:form   action= "/display.do "   method= "post ">
id: <html:text   property= "id "/>
name: <html:text   property= "name "/>
password: <html:text   property= "password "/>
  <html:submit   value= "添加数据 "/>
</html:form>
</body>
</html:html>

我的代码已经实现了向数据库表中插数据了,怎么能改为上传   各位帮帮忙。

[解决办法]
jsp頁
=========================================
<%@page contentType= "text/html;charset=UTF-8 " language= "java " pageEncoding= "UTF-8 "%>
<%@ taglib uri= "http://struts.apache.org/tags-bean " prefix= "bean " %>
<%@ taglib uri= "http://struts.apache.org/tags-html " prefix= "html " %>
<%@ taglib uri= "http://struts.apache.org/tags-logic " prefix= "logic " %>
<%@ taglib uri= "http://struts.apache.org/tags-tiles " prefix= "tiles " %>
<html:html locale= "true ">
<head>
<title> <bean:message key= "hello.jsp.title "/> </title>
<html:base/>
<script language= "JavaScript ">
function upLoad(){
var str = document.HelloForm.file.value;
var Name = str.split( '\\ ');
HelloForm.fileName.value = Name[Name.length-1];
document.HelloForm.login.disabled = true;
//alert(HelloForm.fileName.value);
HelloForm.submit();
}
</script>
<meta http-equiv= "Content-Type " content= "text/html; charset=UTF-8 ">
</head>
<body bgcolor= "white ">
<center>

<h2> <bean:message key= "hello.jsp.page.heading "/> </h2> <p>


<html:form action= "/HelloWorld.do " focus= "userName " method= "post " enctype= "multipart/form-data ">
<bean:message key= "hello.jsp.prompt.person "/> <br>


<table>
<tr>
<td> <bean:message key= "index.jsp.userName "/> : </td>
<td> <html:text property= "userName " size= "10 " maxlength= "10 "/> </td>
<td> <html:errors property= "userName "/> </td>
</tr>
<tr>
<td> <bean:message key= "index.jsp.userId "/> : </td>
<td> <html:text property= "userId " size= "10 " maxlength= "5 " readonly= "true "/> </td>
</tr>
<tr>
<td> <bean:message key= "index.jsp.password "/> : </td>
<td> <html:text property= "userPw " size= "10 " maxlength= "10 "/> </td>
<td> <html:errors property= "userPw "/> </td>
</tr>
<tr>
<td> <bean:message key= "index.jsp.userSex "/> : </td>
<td>
男: <html:radio property= "userSex " value= "0 "/>


女: <html:radio property= "userSex " value= "1 "/>
</td>
<td> <html:errors property= "userSex "/> </td>
</tr>
<tr>
<td> <bean:message key= "index.jsp.type "/> : </td>
<td>
<html:select property= "userType ">
<html:option value= "cos "/>
<html:option value= "test "/>
</html:select>
</td>
</tr>
<tr>
<td colspan= "2 ">
<html:file property= "file "/>
<html:hidden property= "fileName " />
</td>
<td> <html:errors property= "file "/> </td>
</tr>
<tr>
<td> <html:submit property= "login " value= "Submit " onclick= "upLoad(); "/> </td>
<td> <html:reset/> </td>
</tr>
</table>
</html:form>
</center>
</body>
</html:html>

action
==========================================================
package action;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;
import org.apache.struts.validator.DynaValidatorForm;

import dao.GetValue;
import dao.SetValue;

public final class HelloAction extends Action {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {

// MessageResources messages = getResources(request);
// System.out.println(request.getCharacterEncoding());
ActionErrors errors = new ActionErrors();
// 接收传进来的已进行表单验证,并且通过的form
DynaValidatorForm form1 = (DynaValidatorForm) form;
// String userName = form1.getUserName();
String userName = form1.get( "userName ").toString();

int i = new GetValue().getResutSet(userName);
if (i == 1) {
errors.add( "userName ", new ActionMessage(
"hello.username.has.error ", userName));
// saveErrors(request, errors);
addErrors(request, errors);

return (new ActionForward(mapping.getInput()));
} else {

// String badUserName = "Monster ";
//
// if (userName.equalsIgnoreCase(badUserName)) {
// errors.add( "username ", new ActionError(
// "hello.dont.talk.to.monster ", badUserName));
// saveErrors(request,errors);
// return (new ActionForward(mapping.getInput()));
// }
new SetValue().insertMessage(form1.get( "userName ").toString(),
form1.get( "userType ").toString(), form1.get( "userSex ")
.toString(), form1.get( "userPw ").toString());

String dir = servlet.getServletContext().getRealPath( "/upload ");
FormFile file = (FormFile) form1.get( "file ");

// request.setCharacterEncoding( "UTF-8 ");


String fileName = form1.get( "fileName ").toString();

fileName = new String(fileName.getBytes( "ISO-8859-1 "), "UTF-8 ");

// System.out.println(fileName);
if (fileName.equals( " ")) {
} else {

// String size = Integer.toString(file.getFileSize()) + "bytes ";

// System.out.println(dir + "/ " + fileName);
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(dir + "/ "
+ fileName);

int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();

file.destroy();

}

return (mapping.findForward( "SayHello "));
}
}

}
=====================================================
剛學這個的時候仿照孫為琴的書寫的上傳代碼,裏面還有一些其它數據,不需要看,編碼問題業已解決. 孫為琴的書裏(精通struts...那本)的例子也得就很好,感謝孫姐,呵呵。 學struts應該有一本她的書
[解决办法]
不是阿
<html:file property= "file "/> 是上傳文件的控件
[解决办法]
form里要建一个struts file的set\get然后再建一个vo其中那一个bety[]的set/get,最后通过sql把VO对向传入数据库
[解决办法]
其实可以看一下struts html.tga的示例就明白了

热点排行