Struts + spring + hibernate upload/download-one

Source: Internet
Author: User

Upload and download files in J2EE Programming is already a very old topic, and you may immediately be able to snap your fingers to figure out several famous big parts: smartupload, Apache . However, if your project is built in STRUTS + spring + Hibernate (Hereinafter referred to as "ssh") on the framework, these large parts are cumbersome and vicissitudes of life. SSH provides a simple and convenient solution for uploading and downloading files, we only need to configure and add a few Code The problem can be solved in good condition.

This article describes how to develop an SSH-based WebProgram. All SSH frameworks are currently in the latest version:

· Struts 1.2

· Spring 1.2.5

· Hibernate 3.0

The database used in this article isOracle9i, of course, you can port the configuration file to any database with BLOB field types without modifying the Code, suchMySQLAnd sqlserver.

Overall implementation

Upload files to the t_file table. The structure of the t_file table is as follows:


Figure 1 t_file table structure
Where:

· File _ ID: The file ID, which is 32 characters long and uses the UUID. hex of hibernate.AlgorithmGenerate.

· File _ name: file name.

· File _ content: file content, corresponding to the Blob type of oracle.

· Remark: file remarks.

File data is stored in the Blob-type file_content table field. In spring, oraclelobhandler is used to process lob fields (including clob and BLOB ), because the program does not need to reference the specific class of the Oracle Data driver and shields the differences between the lob field processing methods in different databases, the barriers of the Program on multi-database transplantation are removed.

1. First, the Blob field in the data table is declared as the byte [] type in the Java domain object, rather than the java. SQL. Blob type.

2. the type of the Blob field in the hibernate persistent ing file of the data table is Org. springframework. orm. hibernate3.support. blobbytearraytype, that is, the user-defined type provided by spring, rather than Java. SQL. blob.

3. Use org. springframework. JDBC. Support. lob. javaslelobhandler in spring to process BLOB fields in the Oracle database.

With this setting and configuration, we can process BLOB fields like the common field types in the persistent table.

The above is a solution for spring + hibernate to persists the binary data of files to the database. Struts maps the file type component in the form to org In actionform. apache. struts. upload. formfile attribute to obtain the file data submitted by the form.

To sum up, we can use Figure 2 to describe the SSH file upload solution:


Figure 2 SSH file upload processing technical solution
File upload page 3:


Figure 3 file upload page
The object download page 4 is shown below:


Figure 4 File Download Page
The resource structure of the project is shown in Figure 5:


Figure 5 Project Resource Structure

Engineering classes are divided into data persistence layer, business layer and web layer by the SSH hierarchy; applicationcontext under the WEB-INF. XML is the spring configuration file, struts-config.xml is the struts configuration file, file-upload.jsp is the file upload page, file-list.jsp is the file list page.

The subsequent sections of this article will explain the development process of file upload and download layer by layer from the data persistence layer to the service layer to the web layer.


Add Comment
9: 59 | Fixed Link | Reference announcement (0) | Record it |Open-source technology-based project development
fixed link disable
http://lifejava.spaces.msn.com/blog/cns! A666c33543221640! 117. Entry

Build a multi-layer application system based on Struts + spring + hibernate

This article is an introduction to spring-based Web application development.ArticleThe front end adopts struts mVCFramework, the middle layer adopts spring, and the backend adopts hibernate.

This article includes the following content:

· Configure Hibernate and transactions

· Load spring applicationcontext. xmlFile

· Establish dependency between the business layer and Dao

· Apply spring to struts

Introduction

This example is to create a simple web application called myusers to complete user management operations, including simpleDatabaseAdd, delete, and query. This is the crud (new, access, update, and delete) operation. This is a three-tier Web application that uses action (struts) to access the business layer and the business layer to access Dao. Figure 1 briefly describes the overall structure of the application. The numbers in the figure show the Process Order-from the Web (useraction) to the middle layer (usermanager), to the data access layer (userdao), and then return the result.

The real strength of the spring layer lies in its declarative transaction processing, helping to define and support the persistent layer (such as hiberate and ibatis)

Below are the steps to complete this example:

1. Install the Eclipse plug-in

2.DatabaseCreate a table

3. Configure Hibernate and spring

4. Create an implementation class for the hibernate Dao Interface

5. Run the test class to test the CRUD operation of Dao.

6. Create a processing class and declare the transaction

7. Create action and model on the web layer

8. Run the test class test CRUD operation of action

9. Create a JSPFilePerform crud operations in a browser

10. Verify JSP through a browser

Install Eclipse plug-in

1. hibernate plug-in http://www.binamics.com/hibernatesync

2. Spring plugin http://springframework.sourceforge.net/spring-ide/eclipse/updatesite/

3. myeclipse plug-in (cracked version)

4. Tomcat plug-in. tanghan

5. Other plug-ins include XML, JSP,

DatabaseCreate a table

Create Table app_user (ID number not null primary, firstname vchar (32), lastname vchar (32 ));

Create a project

Create a new web project. The new directory structure also containsFileFolder page is used to place JSPFile, And sourceFileFolder test for JUnit TestingFile. At the same time, all the packages, including struts, hibernate, and spring, will be imported to the lib directory.

Create a persistent layer o/R Mapping

1. Use the hibernate plug-in src/COM. Jandar. Model fromDatabaseExport. HBM. xml of app_userFileRenamed user. HBM. xml

<? XML version = "1.0"?>
<! Doctype hibernate-mapping public
"-// Hibernate/hibernate mapping DTD // en"
Http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd>
<Hibernate-mapping package = "com. Jandar. Model">
<Class name = "user" table = "app_user">
<ID
Column = "ID"
Name = "ID"
Type = "integer"
>

<Generator class = "assigned"/>

</ID>

<Property
Column = "lastname"
Length = "10"
Name = "lastname"
Not-null = "false"
Type = "string"
/>

<Property
Column = "firstname"
Length = "10"
Name = "firstname"
Not-null = "true"
Type = "string"
/>

</Class>
</Hibernate-mapping>

2. Use hibernate synchronizer-> synchronizer file to generate a user.JavaFile, The user object correspondsDatabaseApp_user table in

Note: automatically generated objects in eclipseFileNot exactly the same. Each object is the same.FileThe serializable interface must be implemented, and the tostring and hashcode methods must be implemented;

Import Java . Io. serializable;
Import org. Apache. commons. Lang. Builder. equalsbuilder;
Import org. Apache. commons. Lang. Builder. hashcodebuilder;
Import org. Apache. commons. Lang. Builder. tostringbuilder;
Import org. Apache. commons. Lang. Builder. tostringstyle;

Public class baseobject implements serializable {
Public String tostring (){
Return tostringbuilder. reflectiontostring (this,
Tostringstyle. multi_line_style );
}

Public Boolean equals (Object O ){
Return equalsbuilder. reflectionequals (this, O );
}

Public int hashcode (){
Return hashcodebuilder. reflectionhashcode (this );
}
}

Public class user extends baseobject {
Private long ID;
Private string firstname;
Private string lastname;

/**
* @ Return returns the ID.
*/

Public long GETID (){
Return ID;
}

/**
* @ Param ID the ID to set.
*/

Public void setid (long ID ){
This. ID = ID;
}

/**
* @ Return returns the firstname.
*/

Public String getfirstname (){
Return firstname;
}

/**
* @ Param firstname the firstname to set.
*/

Public void setfirstname (string firstname ){
This. firstname = firstname;
}

/**
* @ Return returns the lastname.
*/

Public String getlastname (){
Return lastname;
}

/**
* @ Param lastname the lastname to set.
*/

Public void setlastname (string lastname ){
This. lastname = lastname;
}
}

Create a DaO Access Object

1. Create idao in src/COM. Jandar. Service. Dao.JavaInterface, all DaO inherits this interface

Package com. Jandar. Services. Dao;

Public interface idao {

}

2. Create iuserdao under src/COM. Jandar. Service. Dao.JavaInterface

Public interface iuserdao extends Dao {
List getusers ();
User getuser (integer userid );
Void saveuser (User user );
Void removeuser (integer ID );
}

This interface provides methods to access objects,

3. Create userdaohiberante in src/COM. Jandar. Service. Dao. hibernate.Java

Import Java . Util. List;
Import org. Apache. commons. Logging. log;
Import org. Apache. commons. Logging. logfactory;
Import org. springframework. Orm. hibernate. Support. hibernatedaosupport;
Import com. Jandar. model. user;
Import com. Jandar. Service. Dao. iuserdao;

Public class userdaohibernate extends hibernatedaosupport implements iuserdao {

Private log = logfactory. getlog (userdaohibernate. Class );
/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # getusers ()
*/

Public list getusers (){
Return gethibernatetemplate (). Find ("from user ");
}

/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # getuser (Java. Lang. Long)
*/

Public user getuser (integer ID ){
// Todo automatically generates method stubs
Return (User) gethibernatetemplate (). Get (user. Class, ID );
}

/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # saveuser (COM. Jandar. model. User)
*/

Public void saveuser (User user ){
Log. debug ("xxxxxxx ");
System. Out. println ("YYYY ");
Gethibernatetemplate (). saveorupdate (User );
If (log. isdebugenabled ())
{
Log. debug ("userid set to" + User. GETID ());
}
}

/* (Non-javadoc)
* @ See COM. Jandar. Dao. iuserdao # removeuser (Java. Lang. Long)
*/

Public void removeuser (integer ID ){
Object User = gethibernatetemplate (). Load (user. Class, ID );
Gethibernatetemplate (). Delete (User );
If (log. isdebugenabled ()){
Log. debug ("del user" + id );
}
}
}

This class implements the iuserdao interface method and inherits the hibernatedaosupport class. This class is used to access and operate objects through hibernate.Database.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.