Struts + hibernate getting started instance (eclipse Version)

Source: Internet
Author: User

I. Preface
II. Introduction to related concepts and tools
Iii. instance requirements and overall design
Iv. Persistence Layer and business layer practices (hibernate practices)
V. control layer and presentation layer practices (struts practices)
6. Release and run
7. Write at the end

I. Preface

J2EE and. NET are the two camps currently used by enterprises. I think the biggest advantage of J2EE over. NET is that it has developed a large number of models and a large number of advanced frameworks. Many of these frameworks are open-source, which is another advantage of the J2EE camp. This articleArticleCurrently, Hibernate and struts are the two most popular open-source frameworks in J2EE Web applications.

II. Introduction to related concepts and tools

Next I will explain the concepts involved in the "three major protagonists" in this article.

Hibernate and related knowledge
Hibernate:
The Chinese meaning is "hibernation". Haha, I don't know why the designer uses this name. It is an open-source ORM framework (which will be explained later). It encapsulates JDBC APIs to realize Java object persistence. Someone may ask: JDBC is not difficult to operate. Why should we encapsulate it? In fact, the answer is very simple, because currently all common databases are relational databases. We cannot implement OOP through JDBC operations, so hibernate encapsulates JDBC, in addition, a set of OO hibernate APIs are provided for top-level operations. Hibernate has almost become an accepted ORM standard. (The ORM used in the newly released EJB 3.0 standard is actually hibernate)

Orm:
Here we will explain the Orm. Orm is a mode (for more information about the mode, I have published an article about the factory mode. For more information, see this article). It is an object-Relation Mapping in English, translated as object-relationship ing, it refers to "taking charge of the persistence of all object domain objects in a single group and encapsulating data access details" (Note: This definition comes from "proficient in hibernate: explanation of Java object persistence technology, Sun weiqin, Electronics Industry Press ). I think it is easy to understand: the relational database is object-oriented.

Struts and related knowledge
Struts:
Struts is an open-source project developed by the famous Apache Foundation. As the name suggests, it is an MVC framework. As we all know, MVC is a mode of separation of business logic and representation. It is widely used in Java Web. In the past, the main manifestation of MVC was JSP model2, that is, the application of JSP + servlet + JavaBean. In recent years, Struts has become more and more widely used and is now the most popular MVC framework.

MVC:
Model-View-controller, translated as Model-View-controller. MVC is not a true software design pattern, but a solution. It gives the model the programming of all business logic aspects of the software system, the design and programming of all UI views are handed over to the view, and the controller is used to control the model and generate the corresponding view, thus truly realizing the separation of business logic and user interface.

Eclipse Introduction
Eclipse is an open-source tool developed by IBM and then donated for free, is a set of IDE mainly used for Java Development (eclipse can develop UML, C ++, etc. by adding some plug-ins ). Eclipse has powerful extension functions and its open-source features. As a result, many enthusiasts and companies have developed excellent plug-ins for it. myeclipse is one of them. Myeclipse is an Eclipse plug-in for J2EE developers. It is powerful and easy to use. This example is developed based on the eclipse + myeclipse environment.

In addition to installing the above tools and plug-ins, you also need to install a Web container to create/run this instance. JBoss is used in this article. You can choose to use tomcat or WebLogic on your own, these have little impact on running this article.

The database selected in this article is sqlserver2000. The operation methods for other databases such as MySQL and Oracle are similar.

This article does not describe how to download and install eclipse. You can find related methods on the Internet.

Iii. instance requirements and overall design
1. requirement definition
The purpose of this article is to introduce the specific methods for developing STRUTS + hibernate under Eclipse IDE, rather than introducing the skills of project development/software design. Therefore, the instance requirements in this article are very simple.

This example is a web message book that allows anonymous users to post messages and save them to the database. A friend who has done Web development must have done this kind of instance, which is very classic. Because the instance is simple and easy to understand, I also need to skip the steps for illustration.

2. Overall Design
Based on the traditional J2EE Web project design method, this instance is divided into five layers of architecture, from bottom to top: database layer-> ORM layer (hibernate layer) -> business logic layer-> control layer (struts action)-> View presentation layer.

The DDL statements of the database are as follows:


Iv. Persistence Layer and business layer practices (hibernate practices)
Okay, let's get started.

1. Open eclipse first. Click "new project"-> "WEB Project". The following window is displayed. In the window, enter "memo" as the project name:

Code : [Copy] Create Database memotest
Create Table memo
(
Id int not null identity (1, 1 ),
Topic varchar (255 ),
Content text,
Guest varchar (50 ),
Primary Key (ID)
)

 

2. Click "window"> "open perspective"> "Others". The following window is displayed. Double-click "myeclipse Database Explorer" to switch to the following view:

3. Click "new" on the "DB Browser" Control Panel to create a new database connection. In the pop-up window, click "new driver" to create a database connection driver. For example:

4. Return to the following view after the previous step, select the driver created in the previous step in the list, fill in the relevant database information, and click OK. (The database must be opened before this step, and the database and table have been created according to the DDL of this instance)

5. After completing the previous step, the following view appears. Right-click "memo" and choose "Open connetion"> "OK ". If the preceding steps are successful, the database is connected and the related database structure is displayed.

For example:

6. Click "window"> "open perspective"> "Others"> "myeclipse" to switch to the project control view. Right-click the project name and choose "myeclipse"> "add hibernate capabilites". The following view is displayed and related information is filled in:

Click next and the following figure is displayed. Fill in the following figure based on the image content:

After submission, the following view is displayed. Enter the following view based on the image content:

7. Right-click the project name and choose "myeclipse"> "add struts capabilites". The following view is displayed, showing the world as shown in the figure:

CTRL + mouse wheel to zoom in/out "src_cetemp =" http://blog.csdn.net/images/blog_csdn_net/woolceo/7.jpg ">

8. Click "window"> "open perspective"> "Others". The following window is displayed. Double-click "myeclipse Database Explorer" to switch to the database management view, find the table we created for this instance, right-click it, and choose create hibernate mapping. Enter the following information in the figure:

9. So far, Hibernate has been created. For example, we will write a DaO factory class to operate the hibernate API.

Click the com. Woden package to create a new class, such:

Enter the following code:

Code: [copy] package com. Woden;

Import net. SF. hibernate. hibernateexception;
Import net. SF. hibernate. Session;
Import net. SF. hibernate. transaction;

Public class memodaofactory {
Session session;
Transaction TX;

Public void add (memo) throws hibernateexception {
Try {
Session = sessionfactory. currentsession ();
Tx = session. begintransaction ();
Session. Save (Memo );
TX. Commit ();
} Catch (hibernateexception e ){
System. Out. println (E. tostring ());
} Finally {
If (TX! = NULL ){
TX. rollback ();
}
Sessionfactory. closesession ();
}
}

}

There is only one insert method. If you need more methods, you can add them in Dao.

So far, the code at the database, Orm, and business layers has been completed.

V. control layer and presentation layer practices (struts practices)

1. Create a new welcome. jsp file as the homepage of the instance. The specific method is to right-click the "webroot" folder icon-> New-> "jsp". The following content is simple and you don't need to introduce it.

2. Struts has been imported in myeclipse in step 1 of the previous step. Now we can edit and set up our struts instance. Open the struts profile WEB-INF in the struts-config.xml under the webboot directory, such:

CTRL + mouse wheel to zoom in/out "src_cetemp =" http://blog.csdn.net/images/blog_csdn_net/woolceo/s1.jpg ">

3. Right-click the blank area on the screen and choose "New"> "new form, action and JSP". The following view is displayed. Enter the following content as prompted:

Click the "jsp" tab bar. The following page is displayed, and you can set it as follows:

4. Set form in the previous step, click Next to view the following view, and click set. Click "foward"> "add"> "success" for name ", select "welcome. JSP ", other do not need to fill in-> OK.

5. After clicking "finish" in the previous step, the following page appears:

CTRL + mouse wheel to zoom in/out "src_cetemp =" http://blog.csdn.net/images/blog_csdn_net/woolceo/s4.jpg ">

6. This step is to set up the resource file to prepare for struts internationalization and error prompts. Find SRC (source folder) in the project folder, find applicationresourse. properties, and double-click it, as shown in configuration :( Note: Here I have installed a free ASCII to Unicode plug-in)

CTRL + mouse wheel to zoom in/out "src_cetemp =" http://blog.csdn.net/images/blog_csdn_net/woolceo/s5.jpg ">

If you have not installed ASCII to convert to Unicode, you can directly copy the converted resource file content:

Code: [copy] form. addmemo. Err. content = \ u7559 \ u8a00 \ u5185 \ u5bb9 \ u4e0d \ u80fd \ u4e3a \ u7a7a \ u3002

Form. addmemo. Err. Guest = \ u7559 \ u8a00 \ u8005 \ u59d3 \ u540d \ u4e0d \ u80fd \ u4e3a \ u7a7a \ u3002

Form. addmemo. Err. Topic = \ u7559 \ u8a00 \ u6807 \ u9898 \ u4e0d \ u80fd \ u4e3a \ u7a7a \ u3002

JSP. addmemo. content = \ u8bf7 \ u8f93 \ u5165 \ u5185 \ u5bb9 \ uff1a

JSP. addmemo. Guest = \ u60a8 \ u7684 \ u59d3 \ u540d \ uff1a

JSP. addmemo. pagetitle = \ u7559 \ u8a00 \ u6dfb \ u52a0

JSP. addmemo. Reset = \ u91cd \ u8bbe

JSP. addmemo. Submit = \ u63d0 \ u4ea4

JSP. addmemo. Topic = \ u6807 \ u9898 \ uff1a

JSP. Welcome. content = \ u6b22 \ u8fce \ u4f7f \ u7528hibernate + Struts \ u5b9e \ u4f8b \ u3002

JSP. Welcome. Title = \ u4f60 \ u597d \ u3002 \ u3002 \ u3002

7. Open the com. Woden. Form. memoform. Java file and enter the following code:

Code: [copy] package com. Woden. form;

Import javax. servlet. http. httpservletrequest;

Import org. Apache. Struts. Action. actionerrors;
Import org. Apache. Struts. Action. actionform;
Import org. Apache. Struts. Action. actionmapping;
Import org. Apache. Struts. Action. actionmessage;

Public class memoform extends actionform {

Private string topic;
Private string content;
Private string guest;

Public actionerrors validate (
Actionmapping mapping,
Httpservletrequest request ){
Actionerrors errors = new actionerrors ();

If (getguest () = NULL | "". Equals (getguest ()))
{
Errors. Add ("memoform. Err. Guest", new actionmessage ("form. addmemo. Err. Guest "));
}

If (gettopic () = NULL | "". Equals (gettopic ()))
{
Errors. Add ("memoform. Err. Topic", new actionmessage ("form. addmemo. Err. Topic "));
}

If (getcontent () = NULL | "". Equals (getcontent ()))
{
Errors. Add ("memoform. Err. Content", new actionmessage ("form. addmemo. Err. Content "));
}

Return errors;
}

Public void reset (actionmapping mapping, httpservletrequest request ){
This. Topic = NULL;
This. content = NULL;
This. Guest = NULL;
}

Public String gettopic (){
Return topic;
}

Public void settopic (string topic ){
This. Topic = topic;
}

Public String getcontent (){
Return content;
}

Public void setcontent (string content ){
This. content = content;
}

Public String getguest (){
Return guest;
}

Public void setguest (string guest ){
This. Guest = guest;
}
}

8. The above code of actionform has been written. I will not explain the specific code here. I think it should be clear to all my friends who have read the struts basics. The following is the code of action:

Code: [copy] package com. Woden. Action;

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. Woden. memo;
Import com. Woden. memodaofactory;
Import com. Woden. Form. memoform;

Public class memoaction extends action {

Public actionforward execute (
Actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response ){
Memoform = (memoform) form;

Memodaofactory memodao = new memodaofactory ();
Memo memo = new memo ();
Memo. settopic (memoform. gettopic ());
Memo. setcontent (memoform. getcontent ());
Memo. setguest (memoform. getguest ());

Try {
Memodao. Add (Memo );
} Catch (exception E)
{
System. Out. Print (E. tostring ());
}

Return Mapping. findforward ("success ");
}
}

9. Finally, edit the content of several related JSP files as follows:

Code: [copy] Welcome. jsp
<% @ Page contenttype = "text/html; charset = UTF-8" %>
<% @ Taglib uri = "http://struts.apache.org/tags-bean" prefix = "Bean" %>
<% @ Taglib uri = "http://struts.apache.org/tags-html" prefix = "html" %>

<! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en">
<HTML: HTML>
<Head>
<HTML: base/>
<Title> <Bean: Message key = "JSP. Welcome. Title"/> </title>
</Head>

<Body>
<Bean: Message key = "JSP. Welcome. Content"/>
</Body>
</Html: HTML>

Addmemo. jsp
<% @ Page contenttype = "text/html; charset = UTF-8" %>
<% @ Taglib uri = "http://jakarta.apache.org/struts/tags-bean" prefix = "Bean" %>
<% @ Taglib uri = "http://jakarta.apache.org/struts/tags-html" prefix = "html" %>

<HTML>
<Head>
<Title> <Bean: Message key = "JSP. addmemo. pagetitle"/> </title>
</Head>
<Body>
<HTML: Form Action = "/memo">
<Bean: Message key = "JSP. addmemo. guest "/> <HTML: Text property =" guest "/> <HTML: errors property =" memoform. err. guest "/> <br/>
<Bean: Message key = "JSP. addmemo. topic "/> <HTML: Text property =" topic "/> <HTML: errors property =" memoform. err. topic "/> <br/>
<Bean: Message key = "JSP. addmemo. content "/> <HTML: textarea property =" content "/> <HTML: errors property =" memoform. err. content "/> <br/>
<HTML: Submit> <Bean: Message key = "JSP. addmemo. Submit"/> <HTML: reset> <Bean: Message key = "JSP. addmemo. Reset"/> </Html: Form>
</Body>
</Html>

So far, this instance has been completed.

6. Release and run
1. Right-click the project file and choose "myeclipse"> "add and remove project deployment", for example:

2. Click the icon and select "JBoss"-> "start" (Note: If Tomcat is used here, It is similar. The server configuration method is not mentioned here, ask the reader to find the relevant information on the Internet), and the console will output similar information:

CTRL + mouse wheel to zoom in/out "src_cetemp =" http://blog.csdn.net/images/blog_csdn_net/woolceo/s6b.jpg ">

Open the browser and enter: http: // localhost: 8080/. If it appears, it indicates that the startup is successful:

3. Enter the URL: http: // localhost: 8080/Memo/addmemo. jsp. The following figure is displayed:

4. Leave a message once according to the normal process and the abnormal process. Why? If no expected results are displayed, check the previous steps.

7. Write at the end

At the end of this article, I once again stressed that the purpose of this article is to introduce Eclipse IDE's methods for creating STRUTS + hibernate applications, rather than introducing the concept and application of the J2EE framework, not to mention the Java design and pattern. This article does not detail ide configuration and server configuration methods, because this is not the focus of this article. If you want to know more about the above knowledge, You can Google it.

The example in this article is just an entry point, emphasizing a method rather than a function. Therefore, the instance in this article only has a simple entry function. After reading this article, you can add more features (I think it is quite easy to add features after this architecture is built ).

You are welcome to post any comments and suggestions. Please note "", and finally welcome to visit my blog: http://blog.csdn.net/woolceo.

From: http://blog.csdn.net/woolceo

Related Article

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.