Use myeclipse to integrate a sample program of struts, hibernate, and spring

Source: Internet
Author: User
In the java Enterprise application field, the powerful functions of ejbs are the same as the complicated configurations of ejbs, and they are also known for their difficulties in learning. But before, what can we do? You can only learn ejbs with a hard head. It is a bit of "understanding that there are tigers in the mountains and moving towards tigers. There has been an optimistic change in the form. The popularity of java open source has made the development of java Enterprise applications no longer limited to the ejb field. Here I will mainly introduce how to use open source Spring, Hibernate and Struts to build a lightweight architecture.

I. Overall architecture Introduction
In the field of software engineering, layering has always been a widely adopted method to reduce the Coupling Degree of modules and improve the reusability of modules. In fact, layers can also enable developers to focus on a certain layer of development, so that the division of labor in software development is refined and production efficiency is improved (this is comparable to the pipeline car production method invented by Ford, workers are responsible for the production and final assembly of specific components ).

An enterprise-level java application is generally divided into the following layers: UI Layer, business logic layer, data persistence layer, and domain object layer. Next we will give a brief introduction to these layers:
1. UI Layer: Responsible for interaction with users, including accepting users' requests and returning processing results to users. Here we use struts for the UI Layer. Although the Struts design is somewhat lazy compared to the event-driven presentation layer technologies such as Tapestry and JSF, it is still the de facto standard of the presentation layer, so we still choose it.
2. Business logic layer: mainly responsible for specific business processing. Coupling of various functions through Spring IOC and AOP
3. Data Persistence Layer: mainly responsible for dealing with underlying databases. Here we use the Spring-encapsulated Hibernate operation to simplify the actual encoding. The main operations are CRUD (create, read, update, delete)
4. domain object Layer: specific entity classes, such as teachers and students (Note: it must correspond to a certain mark in the database ).
The above section briefly introduces the division of each layer and the open-source framework corresponding to each layer. To learn more about the layer information, visit the official websites of struts, hibernate, and spring.
Ii. instance analysis
Example: A website logon example is simple, but it shows how the layers coordinate the work.
Tools: jdk1.5, eclipse3.2, myeclipse5.0GA, mysql5.0, and tomcat5.5. I will not talk about how to install these tools here. If you have no idea, you can search for them online. The procedure is as follows:
Preparations: use mysql to create a test database, create a user table, and create two fields: username and password. The script is as follows:

Drop database if exists 'test ';
Create database 'test'
USE 'test ';

Create table 'user '(
'Id' int (11) not null auto_increment,
'Username' varchar (30) not null default '',
'Password' varchar (30) default '',
Primary key ('id ')
) ENGINE = InnoDB default charset = gb2312;
Open the myeclipse database Development E perspective

Right-click the blank area on the left and click new

Click "configure database driver" to configure the database driver. You must have the jdbc driver of mysql and download it from the official website of mysql.

Test whether the database configuration is successful.

1. Create a myeclipse WEB Project

2. Introduce the spring package
Right-click the project name

Note: In order to save the trouble before adding spring related packages, all the packages are selected at one time. Selected
Copy option, which copies these packages to the/webroot/WEB-INF/lib directory for future deployment.

3. Add a hibernate package

The system detects that the spring package has been added to the project and selects the spring configuration file.

Click Next

Click Next

Click Next

Click Finish.
4. Switch to the database sort e view and right-click "hibrnate reverse engineering" in the User table"

The following window is displayed:

Click "Next"

Click Finish.
In the package view, we can see that there is an additional package named VO under SRC and four files under the package.

To display layers more intuitively, I created a package named Dao and moved userdao. Java to Dao.

At the same time, note that the reference part of userdao is also modified in applicationcontext. xml.
5. Establish the business logic layer code
Create a new package named service and create a service class in it. The Code is as follows:

Package service; import java. util. list; import vo. user; import dao. userDAO; public class Service {private UserDAO userDao; public UserDAO getUserDao () {return userDao;} public void setUserDao (UserDAO userDao) {this. userDao = userDao;} public boolean isValid (User user User) {// judge whether the user is legal List result = userDao. findByExample (user); if (result. size ()> 0) return true; elsereturn false ;}}

Add the following configuration in applicationContext. xml
<Bean id = "service" class = "service. Service" singleton = "false">
<Property name = "userDao">
<Ref bean = "userDao"/>
</Property>
</Bean>

6. Configure the UI Layer
Add the struts package in the same way as adding spring.

Configure the struts-config.xml file, right-click a new action, actionForm, jsp in the blank area

 

 

Next step
Set forward, add succeed to welcome. jsp, and fail to login. jsp.

Create a welcome. jsp file in the webroot directory to display the welcome information after successful logon.

6. Connect struts and spring
6.1 modify struts-config.xml note red font Section

<actionattribute="loginForm"input="/login.jsp"name="loginForm"path="/login"scope="request"type="org.springframework.web.struts.DelegatingActionProxy"><forward name="fail" path="/login.jsp" /><forward name="succeed" path="/welcome.jsp" /></action>

 

Add the following code in the strut-config.xml

 

<Plug-in classname = "org. springframework. web. struts. contextloaderplugin "> <set-Property =" contextconfiglocation "value ="/WEB-INF/classes/applicationcontext. XML "/> </plug-in> 6.2 modify applicationcontext and add <bean name ="/login "class =" Web. action. loginaction "Singleton =" false "> <property name =" service "> <ref bean =" service "/> </property> </bean>

 

6.3 modify part of the loginaction. Java code, add a service variable, and its get/Set Method (mainly used in Spring IoC ). The Code is as follows:

 

/** Generated by MyEclipse Struts* Template path: templates/java/JavaClass.vtl*/package web.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 web.form.LoginForm;import service.Service;import vo.User;/*** MyEclipse Struts Creation date: 09-27-2006** XDoclet definition:** @struts.action path="/login" name="loginForm" input="/login.jsp"*           scope="request" validate="true"* @struts.action-forward name="fail" path="/login.jsp"* @struts.action-forward name="succeed" path="/welcome.jsp"*/public class LoginAction extends Action {/** Generated Methods*//*** Method execute** @param mapping* @param form* @param request* @param response* @return ActionForward*/private Service service;public void setService(Service service) {this.service = service;}public Service getService() {return service;}public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {LoginForm loginForm = (LoginForm) form;// TODO Auto-generated method                                                        // stub        User user = new User();user.setPassword(loginForm.getPassword());user.setUsername(loginForm.getUserName());if (service.isValid(user))return mapping.findForward("succeed");elsereturn mapping.findForward("fail");}}

 

So far, a simple login has been made. The rest is to package and release your application.

Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1549145

 

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.