Spring.Hibernate.Struts1 integrated approach

http://zxmzfbdc.javaeye.com/blog/258946

[Original] Spring , Hibernate, Struts1 integrated approach
Complete source code as an example of the attachment upload, in order to reduce the size of the jar does not contain documents used, please download the reader himself, the inconvenience is also sorry.
9.1 Model Overview
As we know, Struts is a simple web framework, so the operator can do in other areas, such as the operation of the database. In addition it also should not rely on the management of relations between objects, so necessary and lasting framework and IoC frameworks in order to build a robust system integrity. This section provides an analysis of Struts + Spring + Hibernate combination of need.
9.1.1 the need to combine the three models
For people involved in web development, the use of Struts can greatly simplify the development process, the direct use of Servlet + JSP, it provides excellent package mechanism allows users to strictly follow the MVC architecture to the development and application. We do not have to think before using the web framework is how the chaos, needs its own data from the request out, and then assemble them in a lot of data, this is simply a nightmare. Verification code scattered everywhere, and safeguarding them is a tiring same live. In order to deal with different requests, it may be necessary to write a lot of the Servlet, not to mention the burden of the container problem, it is particularly web.xml file becomes bloated, it may become difficult to maintain a monster. This is me in the actual development of the real situation encountered. Even though the use of Struts, in the early encounter configuration file (struts-config.xml) expansion of the problem, but the Struts good through modular resolved the problem.
About verification, necessary to say something more, in fact, Struts validation not as some subsequent web framework, such as Webwork, Spring MVC, are pluggable, on the contrary, it has been included in the ActionForm, which is a Designed strong coupling. form much of the burden of the duty, making it more difficult to reuse, such as in the business layer and persistence layer, the other, form part of the framework are Struts, out of consideration to reduce the coupling can not be in the business layer and persistence layer in appear. After some of the framework it is very good solution to this problem: the use of an ordinary pojo, only data for the package, does not contain any logic. However, Struts is an extensible framework for any part of it can be replaced. We can, through its plug-ins provide a mechanism to provide their own functions, such as is usually the case, Spring and Struts integration as a way of implementation is through plug-ins. Through plug-ins, we can also provide pluggable authentication function.
Struts is a project has undergone numerous tests of the framework, with the largest number of communities, with sophisticated experience for reference, so at the risk of the project to use Struts very small. Moreover, Struts easier to use, so the cost of a relatively small study.
As we said earlier, Struts is a pure web framework that does not involve the business layer and persistence layer of the deal, therefore, necessary for the other layers through the use of other frameworks. For instance, in the persistence layer using Hibernate.
Database operations is a very complex problem, even though at Java in, JDBC had a very good abstract, but users need to operate direct SQL. Here there is a problem of data assembled, the actual development directly from the ResultSet to retrieve the data, and then into a model, it is very common approach. Lengthy boring operation set. At our actual development, the data are stored in the model, then the operation model, in this sense, model and database have a certain intrinsic relations. How to map this relationship, it is to be done by ORM. ORM mapping not only the properties of objects and database tables of the relationship between the fields, but also put the relationship between the mapping table for the relationship between objects, which put the operation on the database table, fully into operation on the object. This approach is more familiar to programmers, but also through the tools, we are also very easy to maintain relations and object-relational table synchronization. Hibernate is the ORM such a powerful instrument, in addition to the usual OR mapping, also offers other popular features, such as dirty data checks, such as lazy loading. These sections in front of us, the introduction has been done. Hibernate in the actual development of access to a wide range of applications, become the de facto standard. Therefore, in our development, persistence layer implementation, you can select Hibernate.
Struts is also a lack of IoC and AOP features, so the coupling must exist, for example, in the Action business object to call when the new required an example of this is a very common situation. Of course, we can use the factory pattern to eliminate this situation, but it required the introduction of factory class. Spring can be effectively used to eliminate this coupling. At our previous chapter, the introduction of the Spring and Struts integration methods, can be at our Spring of Action, adopted by ApplicationContext object to obtain, but in this Action and the code embedded in Spring. The third way to integrate through the Struts of the plug-in mechanism to Action hosted by the Spring, so that we can rely on the use of Action at implantation, the total elimination of this coupling. In addition, we can also use Spring's AOP mechanisms. Through the integration, we can take full advantage of all the advantages of the framework to achieve the perfect application to build the goal.
9.2 Model characteristics
Our analysis of the necessity of combining the three frameworks, we now analyze the model using the three characteristics of the framework.
9.2.1 the composition of the characteristics of model
At Spring + Hibernate + Struts model, Hibernate persistence responsible for the operation, Struts is responsible for web operations, between the two completely independent. Spring at the status of this model is very special, which provides for the management of the object, regardless of the objects which are in the layer, which achieve mission. Spring set for the user to rely on the relationship between objects, and through the AOP provides a unified approach in handling cross-cutting needs, these needs is often difficult to achieve the use of OO, such as authentication permissions. This, Spring will involve a wide range of areas, whether in which a layer. Or, Spring is a more basic framework, Struts and Hibernate rather than focus on their respective fields.
Is now clear Spring, Hibernate, Struts role, and now from the perspective of hierarchical analysis of this model.
Business layer deal with the logic of the actual operation, this part of the user are independent of implementation, with maximum flexibility. In some cases, persistence layer and business layer are mixed together, but once the database design is completed, it rarely changes all have considerable stability, so persistence layer also has considerable stability, so they can be independent. There is also a reason for persistent operation, when a lot of very complicated, especially when involved in things, therefore, the maintenance of a stable persistence layer, is conducive to the division of labor, but also to reduce maintenance costs. The emergence of Hibernate, making a lasting no longer operate as before, so complicated, so there is also the merger of the two-tier approach. Give us the following example, you will see a lot of time to business layer is only entrusted to the persistence layer the request itself to do nothing. However, in my opinion, the maintenance of an independent business layer, or good, at least in the future the implementation of lasting change, such as JDBC replaced by Hibernate, the business layer is not used for any changes, although this rarely happens.
Persistence layer, we can directly use the Hibernate API, a better way is to use Spring's Hibernate package. Spring provides a good package for Hibernate, so that we operate in a durable, you can use Spring to provide the package, simplifying the operation of persistence. Hibernate's Session of the resources are very expensive, therefore, each DAO (here refers to the category persistence layer) method, using a single Session is a waste, the use of Spring package, you can use a unified use of Session. Spring managed through the use of Session, the implementation OpenSessionInView our model, that is, at the request of each of the use of a Session. Of course, we can provide their own implementation OpenSessionInView, the simplest is to achieve a Filter. Spring in fact provided one of a kind of implementation is achieved in this way. At Spring-hosted environment, we can achieve Hibernate management statement. The use of the benefits of Spring is a package of treatment for abnormal, Spring can give very specific exceptions, which, unlike JDBC out unified SQLException, Hibernate out HibernateException. Spring also provides the function of abnormal conversion, the user in the configuration file can be converted into a statement of what kind of anomaly.
web layer, is the responsibility of Struts, this is usually not related to Hibernate and Spring, we are only dependent objects from the Spring administration of the injection. However, the request required a lot of time some of the horizontal web of requirements, such as the above-mentioned rights management, a more common situation is that users log in and register. Of course, we can use the Filter implementation, we can always make a top of the Action, a unified treatment of these requests, the need to deal with these requests that it can inherit the Action. However, this is a hard-coded implementation, configuration can not be changed, so the lack of flexibility. Determine whether the user is also a sign of the cross section of a typical application, it can be achieved through the AOP. The following examples we will give a user the use of interceptors to determine whether the implementation of the log. For the use of interceptors, we are here to give the Spring and Struts integration of the fourth approach involves SpringMVC content. Relatively speaking, SpringMVC more dependent on in the design of IoC and AOP, also provides a more open manner, and therefore more powerful, but too complicated. However, as it provides rich features, these complexities can be overcome, so the actual development, implementation can be considered web layer SpringMVC, that is, use it to replace Struts.
9.2.2 The purpose of the implementation model
Using Spring + Hibernate + Struts model for the purpose of the above have been related to the actual, and the advantages of these frameworks is to use one of the major reasons they are. More importantly, have a number of possible reasons, summarized as follows:
This is coupled to a topic of platitudes. Coupling go is so important that people want to experience in this area into a design mode. Spring through IoC, to achieve the coupling, so the user can replace the current implementation, rather than source code modification. This is the open software development - the principle of closure requirements. Spring advocacy-oriented programming interface, which is the most respected one of the best practices, implementation of succession only as a means of internal. Interface-oriented programming, not just to provide a better abstraction, in fact it is more conducive to the coupling.
Necessary expansion of Struts, Spring or Hibernate provides a good extension, Struts mechanisms through plug-ins, you can easily add functionality. Spring management of Bean also provided to expand, for example, users can provide their own scope. Hibernate users can customize their own persistence strategy.
Required to maintain all of these frameworks easier to maintain, they are very good implementation of the open - closed principle functions need to be replaced when a simple configuration file changes. They provide some common functions, configuration can also provide, a statement such as Spring-style services. Therefore greatly reduced maintenance costs.
Have a reason, because they have a huge community support, it is very easy to find technical support. Because they are very popular, so a trick is very easy for developers.
9.3 Hibernate + Spring + Struts Application Analysis Model
Through the above study, we combined the three models have a conceptual understanding, we are now, through a specific example to demonstrate how to integrate them together.
9.3.1 Application examples
We consider the example of a shopping cart, I believe that readers are exposed to more or less examples in this regard. The sake of simplicity, we do not consider the inventory problem, the merchandise entirely by the user fill in information, including trade names, introduction of goods, commodity prices, purchase quantity. Filling out the merchandise information, will be a temporary shopping cart Add each to Cart Order into an abstract. When the user to confirm the purchase of goods, you can submit to cars, thus the information was stored in the database, shopping cart empty. At these operations to do before, users first need to log in, if the user does not register, you can choose to register. Users can not only buy merchandise, but also can view the Order has been submitted to detailed information. A user can have multiple orders, an order can only belong to a user. Similarly, an order can contain multiple products, and a commodity can only belong to one Order. The names of users are only because this is the only confirmed the user's certificate. This is all the demand.
9.3.2 Analysis of examples
Well, we are now beginning to build the entire application. Application of the class library used as shown in Figure 9-1:

Figure 9-1 Application of the jar used packets
First of all, we need to set up the necessary database tables, we have used three forms, each table has a logo for the id, these three tables are:

• tb _user - user form, used to store user information, including user name and password;
• tb _order - Order form Order used to store information, including the Order description, generation time, the user id;
• tb _item - merchandise table used to store merchandise information, including trade names, product descriptions, prices, purchase quantity, the order id.

Are used in my database Oracle9i, the three tables used to generate SQL as follows:

Sql code
1. / * Merchandise table * /
2.create table tb_item (
3. Id number (10,0) not null,
4. Orderid number (10,0) not null, / * Order id * /
5. Name varchar2 (20 char) not null, / * Name * /
6. Description varchar2 (800 char), / * product description * /
7. Price number (18,2), / * commodity prices * /
8. Count number (10,0), / * * Purchase Quantity /
9. Primary key (id)
10.)
11.
12. / * Order Form * /
13.create table tb_order (
14. Id number (10,0) not null,
15. Userid number (10,0) not null, / * user id * /
16. Description varchar2 (800 char), / * Order Description * /
17. CreateTime timestamp, / * Generation time * /
18. Primary key (id)
19.)
20.
21. / * User table * /
22.create table tb_user (
23. Id number (10,0) not null,
24. Name varchar2 (20 char) not null, / * user name * /
25. Password varchar2 (20 char) not null, / * password * /
26. Primary key (id)
27.)
28.
29.alter table tb_item
30. Add constraint FKA4F9FA443A36B48F
31. Foreign key (orderid)
32. References tb_order
33.
34.alter table tb_order
35. Add constraint FKFA98EE3D6705FE99
36. Foreign key (userid)
37. References zxm.tb_user
38.
39.create sequence hibernate_sequence
/ * Merchandise table * /
create table tb_item (
id number (10,0) not null,
orderid number (10,0) not null, / * Order id * /
name varchar2 (20 char) not null, / * Name * /
description varchar2 (800 char), / * product description * /
price number (18,2), / * commodity prices * /
count number (10,0), / * purchase quantity * /
primary key (id)
)

/ * Order Form * /
create table tb_order (
id number (10,0) not null,
userid number (10,0) not null, / * user id * /
description varchar2 (800 char), / * Order Description * /
createTime timestamp, / * Generation time * /
primary key (id)
)

/ * User table * /
create table tb_user (
id number (10,0) not null,
name varchar2 (20 char) not null, / * user name * /
password varchar2 (20 char) not null, / * password * /
primary key (id)
)

alter table tb_item
add constraint FKA4F9FA443A36B48F
foreign key (orderid)
references tb_order

alter table tb_order
add constraint FKFA98EE3D6705FE99
foreign key (userid)
references zxm.tb_user

create sequence hibernate_sequence
Next, we generated pojo and related hibernate mapping file, which can be achieve through the hibernate-tools, you can achieve through Middlegen. Name pojo corresponding, respectively, are User, Order, and Item, and pojo mapping file of the same name. Attention to the naming of packages through the package, we can carry out sub-categories, easy to manage. At our development, should pay attention to the management package, at least in an application should have a unified naming convention. Here the naming habits and the use of the documents are placed like this:

• cn .zxm.order.pojo--pojo mapping and related documents;
• cn .zxm.order.dao-- lasting of interface;
• cn .zxm.order.dao.impl-- achieve lasting type of interface;
• cn .zxm.order.service-- business interface;
• cn .zxm.order.service.impl-- business category interface implementation;
• cn .zxm.order.form-- Application used ActionForm;
• cn .zxm.order.action-- applications used in Action;
• cn .zxm.order.util-- the application of the tools used.

Here we list only the source pojo, omit the mapping file, and other types of interfaces will be listed behind:
User.java:

Java code
1.public class User implements java.io.Serializable (
2. Private Integer id;
3. Private String name;
4. Private String password;
5. Private Set <Order> orders = new HashSet <Order> (0);
6.
7. ... ... The corresponding getter and setter methods ... ...
8.)
public class User implements java.io.Serializable (
private Integer id;
private String name;
private String password;
private Set <Order> orders = new HashSet <Order> (0);

... ... The corresponding getter and setter methods ... ...
)
Order.java:

Java code
1.public class Order implements java.io.Serializable (
2. Private Integer id;
3. Private User user;
4. Private String description;
5. Private Date createTime;
6. Private Set <Item> items = new HashSet <Item> (0);
7.
8. ... ... The corresponding getter and setter methods ... ...
9.)
public class Order implements java.io.Serializable (
private Integer id;
private User user;
private String description;
private Date createTime;
private Set <Item> items = new HashSet <Item> (0);

... ... The corresponding getter and setter methods ... ...
)
Item.java:

Java code
1.public class Item implements java.io.Serializable (
2. Private Integer id;
3. Private Order order;
4. Private String name;
5. Private String description;
6. Private BigDecimal price;
7. Private Integer count;
8.
9. ... ... The corresponding getter and setter methods ... ...
10.)
public class Item implements java.io.Serializable (
private Integer id;
private Order order;
private String name;
private String description;
private BigDecimal price;
private Integer count;

... ... The corresponding getter and setter methods ... ...
)

The third step is to build a lasting interface and their implementation. Begin to build, we probably do not know what methods required, no relationship to our needs from the smallest to consider only the definition of certain methods can be used for the application required a new approach, you can add through Reconstruction, and now a lot of the IDE have provided a good functional reconstruction. So when are first interface reconstruction begin, or start from the implementation? In general, start from the interface must be included to ensure the realization of this method, but from the type of start, we may forget to approach to the interface. However, this problem is not that we developed are used in interfaces, so this is not a problem. My proposal is to start from the reconstruction of implementation.
For the user's operation, we need access to users based on the primary key information. Because users have to deal with registration, so users need to preserve information. Sign in to deal with, so users who need to access user information. This is necessary to use the three methods, under the pretext of the definition is as follows:

Java code
1.public interface UserDAO (
2. / **
3. * Save user
4. * @ Param user
5. * /
6. Void save (User user);
7.
8. / **
9. * Access to users based on user id information
10. * @ Param id
11. * @ Return
12. * /
13. User getUser (int id);
14.
15. / **
16. * The user name to obtain the user information
17. * @ Param name
18. * @ Return
19. * /
20. User getUserByName (String name);
21.)
public interface UserDAO (
/ **
* Save user
* @ Param user
* /
void save (User user);

/ **
* Based on user id access to user information
* @ Param id
* @ Return
* /
User getUser (int id);

/ **
* The user name access to user information
* @ Param name
* @ Return
* /
User getUserByName (String name);
)

Corresponding to our implementation of Spring's HibernateTemplate use category, the class encapsulates the common operations for Hibernate. Implementation is as follows:
UserDAOImpl:

Java code
1.public class UserDAOImpl implements UserDAO (
2. Protected HibernateTemplate hibernate;
3.
4. Public void setHibernate (HibernateTemplate hibernate) (
5. This.hibernate = hibernate;
6.)
7.
8. Public User getUser (int id) (
9. Return (User) hibernate.load (User.class, id);
10.)
11.
12. Public User getUserByName (String name) (
13. String hql = "from User where name =?";
14. User user = null;
15. / / Iterate method to use, and the second is an array of parameters can be used to assign the parameters in the hql
16. Iterator <User> iterator = hibernate.iterate (hql, name);
17. / / Access to user information, did not return null
18. If (iterator.hasNext ()) (
19. User = iterator.next ();
20.)
21. Return user;
22.)
23.
24. Public void save (User user) (
25. Hibernate.saveOrUpdate (user);
26.)
27.)
public class UserDAOImpl implements UserDAO (
protected HibernateTemplate hibernate;

public void setHibernate (HibernateTemplate hibernate) (
this.hibernate = hibernate;
)

public User getUser (int id) (
return (User) hibernate.load (User.class, id);
)

public User getUserByName (String name) (
String hql = "from User where name =?";
User user = null;
/ / Iterate method to use, and the second is an array of parameters can be used to assign the parameters in the hql
Iterator <User> iterator = hibernate.iterate (hql, name);
/ / Access to user information, did not return null
if (iterator.hasNext ()) (
user = iterator.next ();
)
return user;
)

public void save (User user) (
hibernate.saveOrUpdate (user);
)
)

Because at other HibernateTemplate implementation of DAO to be used, so we can put it into a super-class, so all of the DAO implementation can be inherited through the super-category, rather than a statement in the need to have their own HibernateTemplate. Super-category named BaseDAO, the code is as follows:

Java code
1.public class BaseDAO (
2. Protected HibernateTemplate hibernate;
3.
4. Public BaseDAO () (
5. Super ();
6.)
7.
8. Public void setHibernate (HibernateTemplate hibernate) (
9. This.hibernate = hibernate;
10.)
11.)
public class BaseDAO (
protected HibernateTemplate hibernate;

public BaseDAO () (
super ();
)

public void setHibernate (HibernateTemplate hibernate) (
this.hibernate = hibernate;
)
)

Modify UserDAOImpl, so he inherited BaseDAO, the code is as follows:

Java code
1.public class UserDAOImpl extends BaseDAO implements UserDAO (
2. Public User getUser (int id) (
3. ... ...
4.)
5.
6. Public User getUserByName (String name) (
7. ... ...
8.)
9.
10. Public void save (User user) (
11. ... ...
12.)
13.)
public class UserDAOImpl extends BaseDAO implements UserDAO (
public User getUser (int id) (
... ...
)

public User getUserByName (String name) (
... ...
)

public void save (User user) (
... ...
)
)
Order required to operate the same save operation, you may need to delete operation, because To view the Order, a clear need for a query method for easy, do not consider amending the operation (there is dirty because of Hibernate data check function, in fact, through the inquiry method, we can also amend the implementation operation). Code is as follows:

Java code
1.public interface OrderDAO (
2. / **
3. * Save Order
4. * @ Param order
5. * /
6. Void save (Order order);
7.
8. / **
9. * Id access in accordance with Order Order information
10. * @ Param id
11. * @ Return
12. * /
13. Order getOrder (int id);
14.
15. / **
16. * Delete Order
17. * @ Param order
18. * /
19. Void delete (Order order);
20.)
public interface OrderDAO (
/ **
* Save Order
* @ Param order
* /
void save (Order order);

/ **
* Based on Order Order id access to information
* @ Param id
* @ Return
* /
Order getOrder (int id);

/ **
* Delete Order
* @ Param order
* /
void delete (Order order);
)

OrderDAO implementation of the code is as follows:

Java code
1.public class OrderDAOImpl extends BaseDAO implements OrderDAO (
2. Public Order getOrder (int id) (
3. Return (Order) hibernate.load (Order.class, id);
4.)
5.
6. Public void save (Order order) (
7. Hibernate.save (order);
8.)
9.
10. Public void delete (Order order) (
11. Hibernate.delete (order);
12.)
13.)
public class OrderDAOImpl extends BaseDAO implements OrderDAO (
public Order getOrder (int id) (
return (Order) hibernate.load (Order.class, id);
)

public void save (Order order) (
hibernate.save (order);
)

public void delete (Order order) (
hibernate.delete (order);
)
)

The operation of merchandise, we are directly on the session, only when the Order will be submitted to the save operation involved, here we use Hibernate cascade save, so the operation does not involve a separate Item of the situation, ItemDAO Do not need in this case, there omitted. The readers can improve their own applications, such as delete and view a single orders for merchandise and other information.
Achieve a logical persistence layer, we now consider the implementation of the logic layer.
User operation and the operation is similar to DAO, but deal with only businesses here will not affect the data access operation, the code is as follows:

Java code
1.public interface UserService (
2. / **
3. * Save user
4. * @ Param user
5. * /
6. Void save (User user);
7.
8. / **
9. * Access to users based on user id information
10. * @ Param id
11. * @ Return
12. * /
13. User getUser (int id);
14.
15. / **
16. * Based on the user data into user access to complete information
17. * @ Param user
18. * @ Return
19. * /
20. User getUser (User user);
21.)
public interface UserService (
/ **
* Save user
* @ Param user
* /
void save (User user);

/ **
* Based on user id access to user information
* @ Param id
* @ Return
* /
User getUser (int id);

/ **
* Based on the user data into user access to complete information
* @ Param user
* @ Return
* /
User getUser (User user);
)

Corresponding implementation is as follows:

Java code
1.public class UserServiceImpl implements UserService (
2. Private final Log log = LogFactory.getLog (UserServiceImpl.class);
3. Private UserDAO userDAO;
4.
5. Public void setUserDAO (UserDAO userDAO) (
6. This.userDAO = userDAO;
7.)
8.
9. Public User getUser (User user) (
10. Log.debug ( "authenticate users");
11. Return userDAO.getUserByName (user.getName ());
12.)
13.
14. Public User getUser (int id) (
15. Return userDAO.getUser (id);
16.)
17.
18. / **
19. * Use the Service mark here, so you can use Declarative Services
20. * If the user name space, will not be saved
21. * /
22. @ Transactional
23. Public void save (User user) (
24. Log.debug ( "Save user");
25. If (userDAO.getUserByName (user.getName ())!= null)
26. Return;
27. UserDAO.save (user);
28.)
29.)
public class UserServiceImpl implements UserService (
private final Log log = LogFactory.getLog (UserServiceImpl.class);
private UserDAO userDAO;

public void setUserDAO (UserDAO userDAO) (
this.userDAO = userDAO;
)

public User getUser (User user) (
log.debug ( "authenticate users");
return userDAO.getUserByName (user.getName ());
)

public User getUser (int id) (
return userDAO.getUser (id);
)

/ **
* The use of the Service mark here, so you can use Declarative Services
* If the user name space, will not be saved
* /
@ Transactional
public void save (User user) (
log.debug ( "Save user");
if (userDAO.getUserByName (user.getName ())!= null)
return;
userDAO.save (user);
)
)

Order of the deal, we need a method to obtain the Order information, but also need a way to preserve order, interface code as follows:

Java code
1.public interface OrderService (
2. / **
3. * Order to obtain detailed information
4. * @ Param id
5. * @ Return
6. * /
7. Order getOrder (int id);
8.
9. / **
10. * Save Order
11. * @ Param order
12. * /
13. Void save (Order order);
14.)
public interface OrderService (
/ **
* Order to obtain detailed information
* @ Param id
* @ Return
* /
Order getOrder (int id);

/ **
* Save Order
* @ Param order
* /
void save (Order order);
)

Corresponding implementation is as follows:

Java code
1.public class OrderServiceImpl implements OrderService (
2. Private OrderDAO orderDAO;
3.
4. Public void setOrderDAO (OrderDAO orderDAO) (
5. This.orderDAO = orderDAO;
6.)
7.
8. Public Order getOrder (int id) (
9. Return orderDAO.getOrder (id);
10.)
11.
12. / **
13. * Preservation orders, give orders here at our set up time to generate
14. * /
15. @ Transactional
16. Public void save (Order order) (
17. Order.setCreateTime (new Timestamp (System.currentTimeMillis ()));
18. OrderDAO.save (order);
19.)
20.)
public class OrderServiceImpl implements OrderService (
private OrderDAO orderDAO;

public void setOrderDAO (OrderDAO orderDAO) (
this.orderDAO = orderDAO;
)

public Order getOrder (int id) (
return orderDAO.getOrder (id);
)

/ **
* Preservation orders, give orders here at our set up time to generate
* /
@ Transactional
public void save (Order order) (
order.setCreateTime (new Timestamp (System.currentTimeMillis ()));
orderDAO.save (order);
)
)

Our shopping cart through the implementation of HttpSession, so we are not here to define a Service, or through a type of instrument to achieve the functional operation of the shopping cart. Here cart are saved have not yet submitted an order. Order because of the need to keep merchandise, at our Order to add a method, the code is as follows:

Java code
1. / **
2. * Add the merchandise, pay attention to our manually added orders for merchandise related to
3. * This is the cascade in order to preserve the use of Hibernate
4. * @ Param item
5. * /
6.public void addItem (Item item) (
7. Item.setOrder (this);
8. Items.add (item);
9.)
/ **
* Add the merchandise, pay attention to our manually added orders for merchandise related to
* This is the cascade in order to preserve the use of Hibernate
* @ Param item
* /
public void addItem (Item item) (
item.setOrder (this);
items.add (item);
)

Tools of the code is as follows:

Java code
1.public final class OrderUtils (
2. / **
3. * Merchandise Add to Cart
4. * @ Param request
5. * @ Param item
6. * /
7. Public static void saveItem (HttpServletRequest request, Item item) (
8. HttpSession session = request.getSession ();
9. User user = (User) session.getAttribute ( "user");
10. Order order = getOrder (request);
11. Order.addItem (item);
12. Session.setAttribute (user.getName (), order);
13.)
14.
15. / **
16. * Access to information to Cart
17. * @ Param request
18. * @ Return
19. * /
20.
21. Public static Order getOrder (HttpServletRequest request) (
22. HttpSession session = request.getSession ();
23. User user = (User) session.getAttribute ( "user");
24. Order order = (Order) session.getAttribute (user.getName ());
25. / / If the session did not Order object, then the instantiation is a
26. If (order == null) (
27. Order = new Order ();
28.)
29. Return order;
30.)
31.
32. / **
33. * Empty Shopping Cart
34. * @ Param request
35. * /
36. Public static void clearCart (HttpServletRequest request) (
37. HttpSession session = request.getSession ();
38. User user = (User) session.getAttribute ( "user");
39. Session.removeAttribute (user.getName ());
40.)
41.)
public final class OrderUtils (
/ **
* Add to Cart merchandise
* @ Param request
* @ Param item
* /
public static void saveItem (HttpServletRequest request, Item item) (
HttpSession session = request.getSession ();
User user = (User) session.getAttribute ( "user");
Order order = getOrder (request);
order.addItem (item);
session.setAttribute (user.getName (), order);
)

/ **
* Access to information to Cart
* @ Param request
* @ Return
* /

public static Order getOrder (HttpServletRequest request) (
HttpSession session = request.getSession ();
User user = (User) session.getAttribute ( "user");
Order order = (Order) session.getAttribute (user.getName ());
/ / If the session does not Order object, then the instantiation is a
if (order == null) (
order = new Order ();
)
return order;
)

/ **
* Clear cart
* @ Param request
* /
public static void clearCart (HttpServletRequest request) (
HttpSession session = request.getSession ();
User user = (User) session.getAttribute ( "user");
session.removeAttribute (user.getName ());
)
)

Now we need these type of configuration in the Spring configuration file, it is necessary to pay attention to us here are using a statement-type services, therefore a need to introduce the corresponding schema, introduced in the previous chapter has been introduce, are not repeated here. Configuration file as follows:

Xml code
1. <beans Default-autowire="byName">
2. <bean>
3. <property Name="jndiName" value="java:/comp/env/jdbc/order"/>
4. </ Bean>
5. <Bean
6.class = "org.springframework.orm.hibernate3.HibernateTransactionManager">
7. <property Name="dataSource" ref="dataSource"/>
8. <property Name="sessionFactory" ref="sessionFactory"/>
9. </ Bean>
10. <tx:annotation-driven />
11. <Bean
12.class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
13. <property Name="dataSource" ref="dataSource"/>
14. <property Name="mappingResources">
15. <list>
16. <value> Cn / zxm / order / pojo / User.hbm.xml </ value>
17. <value> Cn / zxm / order / pojo / Order.hbm.xml </ value>
18. <value> Cn / zxm / order / pojo / Item.hbm.xml </ value>
19. </ List>
20. </ Property>
21. <property Name="hibernateProperties">
22. <props>
23. <prop Key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </ prop>
24. <prop Key="hibernate.show_sql"> false </ prop>
25. <prop Key="hibernate.format_sql"> true </ prop>
26. </ Props>
27. </ Property>
28. </ Bean>
29. <bean/>
30. <bean Abstract="true"/>
31. <bean/>
32. <bean Parent="baseDAO"/>
33. <bean Parent="baseDAO"/>
34. <bean Parent="baseDAO"/>
35. <bean/>
36. <bean/>
37. <bean/>
38. </ Beans>
<beans default-autowire="byName">
<bean>
<property name="jndiName" value="java:/comp/env/jdbc/order"/>
</ bean>
<bean
class = "org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="dataSource" ref="dataSource"/>
<property name="sessionFactory" ref="sessionFactory"/>
</ bean>
<tx:annotation-driven />
<bean
class = "org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value> cn / zxm / order / pojo / User.hbm.xml </ value>
<value> cn / zxm / order / pojo / Order.hbm.xml </ value>
<value> cn / zxm / order / pojo / Item.hbm.xml </ value>
</ list>
</ property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.Oracle9Dialect </ prop>
<prop key="hibernate.show_sql"> false </ prop>
<prop key="hibernate.format_sql"> true </ prop>
</ props>
</ property>
</ bean>
<bean/>
<bean abstract="true"/>
<bean/>
<bean parent="baseDAO"/>
<bean parent="baseDAO"/>
<bean parent="baseDAO"/>
<bean/>
<bean/>
<bean/>
</ beans>
It should be noted that in order to simplify the configuration, we use an automatic loading. Hibernate complete information needed to configure here, and thus the status of replacing the hibernate.cfg.xml. Management of the transparencies are designed specifically for Hibernate3, data sources are read through JNDI, which are in need of special attention.
Can now develop a web layer. Because of Action and Form depends on the page, so we first consider building a page, all pages of the order is located in the application directory. According to demand, first of all need a login page, simply use a username and password input box. Code is as follows (here only the relevant parts list and input the code, other parts omitted):

Html code
1. <html:form Action="/loginAction.do" method="get">
2. <table Width="400" border="0" align="center" cellpadding="10" cellspacing="1">
3. <tr>
4. <td> Account </ td> <td> <html:text property="name""width:98%;"/> </ td>
5. </ Tr>
6. <tr>
7. <td> Password </ td> <td> <html:password property="password""width:98%;"/> </ td>
8. </ Tr>
9. <tr> <td> </ Td> <td> <input type="submit" value=" Login "/> </ td> </ tr>
10. </ Table>
11. </ Html: form>
<html:form action="/loginAction.do" method="get">
<table width="400" border="0" align="center" cellpadding="10" cellspacing="1">
<tr>
<td> Account </ td> <td> <html:text property="name""width:98%;"/> </ td>
</ tr>
<tr>
<td> password </ td> <td> <html:password property="password""width:98%;"/> </ td>
</ tr>
<tr> <td> </ td> <td> <input type="submit" value=" Login "/> </ td> </ tr>
</ table>
</ html: form>
Here the use of the Struts tags, use them when necessary to ensure that the right to introduce the head of the page. Attention to form in the following categories, the property name and the name to be consistent here. Category code related to the form as follows:

Java code
1.public class UserForm extends ActionForm (
2. Private String name;
3. Private String password;
4. Private User user;
5.
6. / / Setter and getter methods
7.)
public class UserForm extends ActionForm (
private String name;
private String password;
private User user;

/ / setter and getter methods
)
Action And to write a treatment for landing, the code is as follows:

Java code
1.public class LoginAction extends Action (
2. Private final Log log = LogFactory.getLog (LoginAction.class);
3. Private UserService userService;
4. Private User user;
5.
6. Public void setUserService (UserService userService) (
7. This.userService = userService;
8.)
9.
10. Public void setUser (User user) (
11. This.user = user;
12.)
13.
14. / **
15. @ See
16. Org.apache.struts.action.Action # execute (org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
17. * /
18. @ Override
19. Public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception (
20. UserForm uf = (UserForm) form;
21. / / Cloning a User object to log information to ensure the independence of
22. User user2 = (User) BeanUtils.cloneBean (user);
23. / / User data sent Add User object
24. CopyProperties (user2, uf);
25. / / Re-initialize the form
26. Uf.reset (mapping, request);
27. / / Query user information
28. User u = userService.getUser (user2);
29. / / If the user input information does not exist or is not correct, specified on the back page
30. If (u == null | |! U.getPassword (). Equals (user2.getPassword ()))
31. Return mapping.findForward ( "fail");
32. User2.setId (u.getId ());
33. User2.setPassword (u.getPassword ());
34. / / Get the query form Add the User object, so the page can use Hibernate's lazy loading
35. Uf.setUser (u);
36. / / Information into the user session
37. Request.getSession (). SetAttribute ( "user", user2);
38. / / Log successful, return the specified page
39. Return mapping.findForward ( "welcome");
40.)
41.)
public class LoginAction extends Action (
private final Log log = LogFactory.getLog (LoginAction.class);
private UserService userService;
private User user;

public void setUserService (UserService userService) (
this.userService = userService;
)

public void setUser (User user) (
this.user = user;
)

/ **
@ see
org.apache.struts.action.Action # execute (org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
* /
@ Override
public ActionForward execute (ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception (
UserForm uf = (UserForm) form;
/ / Cloning a User object to log information to ensure the independence of
User user2 = (User) BeanUtils.cloneBean (user);
/ / User data sent Add User object
copyProperties (user2, uf);
/ / Re-initialize the form
uf.reset (mapping, request);
/ / Query user information
User u = userService.getUser (user2);
/ / If the user input information does not exist or is not correct, specified on the back page
if (u == null | |! u.getPassword (). equals (user2.getPassword ()))
return mapping.findForward ( "fail");
user2.setId (u.getId ());
user2.setPassword (u.getPassword ());
/ / Get the query form Add the User object, so the page can use Hibernate's lazy loading
uf.setUser (u);
/ / Information into the user session
request.getSession (). setAttribute ( "user", user2);
/ / Login successful, return the specified page
return mapping.findForward ( "welcome");
)
)

Landing point for the development of the type of finish. Remaining is the allocation of the previous chapter we mentioned the first to use Spring and Struts integration of a third way, namely, the use of Struts of Plug-in mechanism, struts-config.xml as follows:

Xml code
1. <? Xml version = "1.0"?>
2. <! DOCTYPE struts-config PUBLIC "- / / Apache Software Foundation / / DTD Struts Configuration 1.3 / / EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
3. <struts-config>
4. <plug-in ClassName="org.springframework.web.struts.ContextLoaderPlugIn">
5. <Set-property property = "contextConfigLocation"
6. Value = "/ WEB-INF/classes/beans.xml" />
7. </ Plug-in>
8. </ Struts-config>
<? xml version = "1.0"?>
<! DOCTYPE struts-config PUBLIC "- / / Apache Software Foundation / / DTD Struts Configuration 1.3 / / EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property = "contextConfigLocation"
value = "/ WEB-INF/classes/beans.xml" />
</ plug-in>
</ struts-config>

In the WEB-INF directory create a new file struts-order-config.xml, this document is used to configure the module we are using. Struts modules are divided in accordance with the directory. Add the module in the future, the corresponding web.xml, the ActionServlet to add the following parameters:

Xml code
1. <init-param>
2. <param-name> Config / order </ param-name>
3. <param-value> Struts-order-config.xml </ param-value>
4. </ Init-param>
<init-param>
<param-name> config / order </ param-name>
<param-value> struts-order-config.xml </ param-value>
</ init-param>
If there is other, then add the module, simply add a can in accordance with the format. Attention is required confg / behind the parameters of the corresponding module must be a directory name. Such applications when access to specific modules, Struts will automatically name of an additional module. Such as the current log, the page client form corresponds to the value of action are / loginDispatcher.do, Struts will automatically be converted to / order / loginDispatcher.do. The Struts configuration file itself, the module name change at the time Do not need to make any changes. This application is very small, there is no need to use the modular function, use it here only for demonstration. The demand for such practical applications are quite common.
Struts-order-config.xml configuration is as follows:

Xml code
1. <struts-config>
2. <form-beans>
3. <Form-bean name = "userForm"
4.type = "cn.zxm.order.form.UserForm" />
5. </ Form-beans>
6. <action-mappings>
7. <action Path="/loginDispatcher" forward="/login.jsp"/>
8. <Action path = "/ loginAction"
9.input = "/ login.jsp"
10.type = "org.springframework.web.struts.DelegatingActionProxy" name = "userForm">
11. <forward Name="fail" path="/loginDispatcher.do"/>
12. <forward Name="welcome" path="/orderList.jsp"/>
13. </ Action>
14. </ Action-mappings>
15. </ Struts-config>
<struts-config>
<form-beans>
<form-bean name = "userForm"
type = "cn.zxm.order.form.UserForm" />
</ form-beans>
<action-mappings>
<action path="/loginDispatcher" forward="/login.jsp"/>
<action path = "/ loginAction"
input = "/ login.jsp"
type = "org.springframework.web.struts.DelegatingActionProxy" name = "userForm">
<forward name="fail" path="/loginDispatcher.do"/>
<forward name="welcome" path="/orderList.jsp"/>
</ action>
</ action-mappings>
</ struts-config>

orderList.jsp used to display all the user's Order. path name, must have the agreement should, for example, simply mapping the page, use the page name of the form + Dispatcher; deal with the path of the request page using the page name + Action form, and so on, which is conducive to the future, our use of wildcard to simplify the configuration. This issue behind us will be involved.
In the Spring configuration file add the definition of Action of, bean the name of the corresponding Struts in the path, only the name of the bean that contains the module name:

Xml code
1. <Bean name = "/ order / loginAction"
2.class = "cn.zxm.order.action.LoginAction" />
<bean name = "/ order / loginAction"
class = "cn.zxm.order.action.LoginAction" />
Now we can test the sign, we in the database, enter a user's information, user name and password are zxm. Open the browser, enter in the address bar
http://www.zxm.net:8090/order/order/loginDispatcher.do
Page in Figure 9-2.

Sign in Figure 9-2
Enter the user name and password, enter an incorrect user name or password, should be sent back to the login page, a list of success to enter the Order page, the page client because of the need to use Hibernate's lazy loading features, will be out first visit to the unusual session closed.

Order now to build our show page Order page code is as follows:

Html code
1. <% @ Page language = "java" contentType = "text / html; charset = GBK"
2. PageEncoding = "GBK"%>
3. <% @ Taglib uri = "http://struts.apache.org/tags-html" prefix = "html"%>
4. <% @ Taglib uri = "http://struts.apache.org/tags-bean" prefix = "bean"%>
5. <% @ Taglib uri = "http://struts.apache.org/tags-logic" prefix = "logic"%>
6. <% @ Taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn"%>
7. <! DOCTYPE html PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
8. <html>
9. <head>
10. <meta Http-equiv="Content-Type" content="text/html; charset=GBK">
11. <link Rel="stylesheet" href="style.css" />
12. <title> Order a list of users </ title>
13. </ Head>
14. <body>
15. $ (UserForm.user.name), Hello, you submitted a total of $ (fn: length (userForm.user.orders)) In order <br/>
16. <table Width="100%" border="0" align="center" cellpadding="10" cellspacing="1">
17. <tr>
18. <th> Id </ th> <th> Order Name </ th> <th> Order Description </ th> <th> generated Order Date </ th>
19. </ Tr>
20. <logic:iterate Property="user.orders" name="userForm">
21. <tr>
22. <td> <html:link Action="/search_items.do?id=${order.id}"> $ (order.id) </ html: link> </ td>
23. <td> No </ td>
24. <td> $ (Order.description) </ td>
25. <td> $ (Order.createTime) </ td>
26. </ Tr>
27. </ Logic: iterate>
28.
29. </ Table>
30. <html:link Action="/search_items.do"> Cart </ html: link> <br/>
31. <html:link Action="/itemDispatcher.do"> ordering merchandise </ html: link>
32. </ Body>
33. </ Html>
<% @ Page language = "java" contentType = "text / html; charset = GBK"
pageEncoding = "GBK"%>
<% @ Taglib uri = "http://struts.apache.org/tags-html" prefix = "html"%>
<% @ Taglib uri = "http://struts.apache.org/tags-bean" prefix = "bean"%>
<% @ Taglib uri = "http://struts.apache.org/tags-logic" prefix = "logic"%>
<% @ Taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn"%>
<! DOCTYPE html PUBLIC "- / / W3C / / DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<link rel="stylesheet" href="style.css" />
Order <title> users list </ title>
</ head>
<body>
$ (userForm.user.name), Hello, you submitted a total of $ (fn: length (userForm.user.orders)) In order <br/>
<table width="100%" border="0" align="center" cellpadding="10" cellspacing="1">
<tr>
<th> id </ th> <th> Order Name </ th> <th> Order Description </ th> <th> generated Order Date </ th>
</ tr>
<logic:iterate property="user.orders" name="userForm">
<tr>
<td> <html:link action="/search_items.do?id=${order.id}"> $ (order.id) </ html: link> </ td>
<td> No </ td>
<td> $ (order.description) </ td>
<td> $ (order.createTime) </ td>
</ tr>
</ logic: iterate>

</ table>
<html:link action="/search_items.do"> to Cart </ html: link> <br/>
<html:link action="/itemDispatcher.do"> order merchandise </ html: link>
</ body>
</ html>
Here not only the use of the Struts tag, but also the use of JSTL, fn the definition of a number of useful functions, can be used in the EL, such as calculating the length of the pool length. Logic tag library are used to deal with the logic of the tag library, iterator used to traverse the collection, name for the property from the request, session, pageContext or application value, which is equivalent to calling the getAttribute () method, property is the corresponding property, the way you can use regular expressions, such as here user.orders, equivalent to the object call getUser (). getOrders () method, this form is common, such as in the Spring and on ognl support this form of expression. id attribute is the name of reference, its role and the following variables rather order:

Java code
1.for (Order order: contains a collection of Order objects) (
2. ... ...
3.)
for (Order order: contains a collection of Order objects) (
... ...
)
EL language used above, has already been introduced, will not repeat them here.
Orders here are eye-catching collection is removed from the User object, and in our code there is no such assignment. In fact, this use of the Hibernate features of lazy loading, so the requirements of the User object used here must be a persistent object. This requires treatment at a time when the page is essential to ensure open Hibernate Session. Therefore, we should be OpenSessionInView model, we can provide through the use of Spring to the implementation of this model OpenSessionInViewFilter, Spring can also be provided through the use of OpenSessionInViewInterceptor, the role of both the same. Filter the benefits of the use of developers are more familiar with it, use the Interceptor to a more elegant way. Since we need to use Spring's interceptor implementation to the user to determine whether or not the sign, here the way we use Interceptor. But this means necessary to achieve SpringMVC, slightly complex. Struts and Spring This is the fourth integrated way. Details are as follows.
We use Spring to distribute the DispatcherServlet request, required the use of the Servlet register a Listener, web.xml configuration is as follows:

Xml code
1. <? Xml version = "1.0" encoding = "UTF-8"?>
2. <Web-app version = "2.5"
3. Xmlns = "http://java.sun.com/xml/ns/javaee"
4. Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
5. Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6. <listener>
7. <listener-class>
8.org.springframework.web.context.ContextLoaderListener
9. </ Listener-class>
10. </ Listener>
11. <servlet>
12. <servlet-name> Actions </ servlet-name>
13. <servlet-class>
14.org.springframework.web.servlet.DispatcherServlet
15. </ Servlet-class>
16. <load-on-startup> 1 </ load-on-startup>
17. </ Servlet>
18. <servlet-mapping>
19. <servlet-name> Actions </ servlet-name>
20. <url-pattern> *. Do </ url-pattern>
21. </ Servlet-mapping>
22. </ Web-app>
<? xml version = "1.0" encoding = "UTF-8"?>
<web-app version = "2.5"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</ listener-class>
</ listener>
<servlet>
<servlet-name> actions </ servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</ servlet-class>
<load-on-startup> 1 </ load-on-startup>
</ servlet>
<servlet-mapping>
<servlet-name> actions </ servlet-name>
<url-pattern> *. do </ url-pattern>
</ servlet-mapping>
</ web-app>

DispatcherServlet use profile, the default rules follow: Servlet name-servlet.xml. Here are actions-servlet, it should be located under the WEB-INF, which is a standard Spring configuration file. ContextLoaderListener has also required a default configuration file name is applicationContext.xml, also located under the WEB-INFO. I put all my configuration information placed in the applicationContext.xml. We need to remove the struts-config.xml in the plug-in configuration. Well, web.xml so many of the information. Now need to amend the Spring configuration file applicationContext.xml, add it at the following configuration:

Xml code
1. <bean>
2. <property Name="flushMode" value="0"/>
3. </ Bean>
<bean>
<property name="flushMode" value="0"/>
</ bean>
property settings flushMode way flush the session, here set to 0, that will never be the use of automatic flush, this is the transaction in order to use the statement.

Xml code
1. <bean>
2. <property Name="servletClass">
3. <value> Org.apache.struts.action.ActionServlet </ value>
4. </ Property>
5. <property Name="servletName" value="action"/>
6. <property Name="initParameters">
7. <props>
8. <prop Key="config"> / WEB-INF/struts-config.xml </ prop>
9. <prop Key="config/order"> / WEB-INF/struts-order-config.xml </ prop>
10. <prop Key="debug"> true </ prop>
11. </ Props>
12. </ Property>
13. </ Bean>
<bean>
<property name="servletClass">
<value> org.apache.struts.action.ActionServlet </ value>
</ property>
<property name="servletName" value="action"/>
<property name="initParameters">
<props>
<prop key="config"> / WEB-INF/struts-config.xml </ prop>
<prop key="config/order"> / WEB-INF/struts-order-config.xml </ prop>
<prop key="debug"> true </ prop>
</ props>
</ property>
</ bean>

Statement here, a Controller, ServletWrappingController are specially designed for Struts, Struts role of the agent is equivalent to ActionServlet, the following attributes are well understood, we can see and almost at the configuration of web.xml, but the form of differences.
Finally we need to put the request Struts associated with the path and Controller:

Xml code
1. <Bean
2.class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
3. <property Name="interceptors">
4. <list>
5. <ref Bean="openSessionInViewInterceptor" />
6. </ List>
7. </ Property>
8. <property Name="mappings">
9. <props>
10. <prop Key="/*/*.do"> strutsWrappingController </ prop>
11. </ Props>
12. </ Property>
13. </ Bean>
<bean
class = "org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="interceptors">
<list>
<ref bean="openSessionInViewInterceptor" />
</ list>
</ property>
<property name="mappings">
<props>
<prop key="/*/*.do"> strutsWrappingController </ prop>
</ props>
</ property>
</ bean>
So that we can use Hibernate's lazy loading features and Spring of the transaction statement. Note intercptors property, we can add your own implementation of the interceptor and later on we will give a specific example. The order of interceptors is to be more attention. After Successful Login page shown in Figure 9-3.

Figure 9-3 Order user list
Users register and log in the flow, the Registration page and log in, like we have not listed here, only deal with the Register Action, the code is as follows:

Java code
1.public class RegisterAction extends Action (
2. Protected final Log log = LogFactory.getLog (RegisterAction.class);
3. Private UserService userService;
4. Private User user;
5.
6. Public void setUserService (UserService userService) (
7. This.userService = userService;
8.)
9.
10. Public void setUser (User user) (
11. This.user = user;
12.)
13.
14. / **
15. * @ See org.apache.struts.action.Action # execute (org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http . HttpServletResponse)
16. * /
17. @ Override
18. Public ActionForward execute (ActionMapping mapping,
19. ActionForm form, HttpServletRequest request,
20. HttpServletResponse response) throws Exception (
21. UserForm uf = (UserForm) form;
22. User u = (User) cloneBean (user);
23. CopyProperties (u, uf);
24. Uf.reset (mapping, request);
25. UserService.save (u);
26. / / Register the failure of the user, then return the failure of the page
27. If (u.getId () == null | | u.getId () == 0)
28. Return mapping.findForward ( "fail");
29. / / Register the success of the list on the back page of Order
30. Uf.setUser (u);
31. Request.getSession (). SetAttribute ( "user", u);
32. Return mapping.findForward ( "welcome");
33.)
34.)
public class RegisterAction extends Action (
protected final Log log = LogFactory.getLog (RegisterAction.class);
private UserService userService;
private User user;

public void setUserService (UserService userService) (
this.userService = userService;
)

public void setUser (User user) (
this.user = user;
)

/ **
* @ See org.apache.struts.action.Action # execute (org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse )
* /
@ Override
public ActionForward execute (ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception (
UserForm uf = (UserForm) form;
User u = (User) cloneBean (user);
copyProperties (u, uf);
uf.reset (mapping, request);
userService.save (u);
/ / Register the failure of the user, then return the failure of the page
if (u.getId () == null | | u.getId () == 0)
return mapping.findForward ( "fail");
/ / Register the success of the list on the back page of Order
uf.setUser (u);
request.getSession (). setAttribute ( "user", u);
return mapping.findForward ( "welcome");
)
)
Registration pages are register.jsp, the corresponding path is / registerAction. And we add a log in page under the Register button, so users can log in page from the page to register. Register button to register a way to respond to click, the code is as follows:

Js code
1. <script Language="javascript">
2.function register () (
3. Window.location = "registerDispatcher.do";
4.)
5. </ Script>
<script language="javascript">
function register () (
window.location = "registerDispatcher.do";
)
</ script>
In the struts-order-config.xml add the following configuration:

Xml code
1. <action Path="/registerDispatcher" forward="/register.jsp"/>
2. <Action path = "/ registerAction"
3.input = "/ register.jsp"
4.type = "org.springframework.web.struts.DelegatingActionProxy" name = "userForm">
5. <forward Name="fail" path="/registerDispatcher.do"/>
6. <forward Name="welcome" path="/orderList.jsp"/>
7. </ Action>
<action path="/registerDispatcher" forward="/register.jsp"/>
<action path = "/ registerAction"
input = "/ register.jsp"
type = "org.springframework.web.struts.DelegatingActionProxy" name = "userForm">
<forward name="fail" path="/registerDispatcher.do"/>
<forward name="welcome" path="/orderList.jsp"/>
</ action>
ApplicationContext.xml added at the corresponding Action statement:

Xml code
1. <Bean name = "/ order / registerAction"
2.class = "cn.zxm.order.action.RegisterAction" />
<bean name = "/ order / registerAction"
class = "cn.zxm.order.action.RegisterAction" />
This sign can be tested. Readers can sign up for an English test, and successful, you will find user name are garbled, it is because of the use of Tomcat the default ISO-8859-1 encoding, and we are GBK encoding used. Resolve this problem, the way for the request, have a different strategy to deal with. For instance on the POST request, we need to use the filter to re-encoding, the GET request, at Tomcat port configuration required to set up encoding. Introduce us to be separately below.
We can achieve this filter, but Spring has provided us with a ready-made implementation, and its configuration is as follows:

Xml code
1. <filter>
2. <filter-name> EncodeFilter </ filter-name>
3. <filter-class>
4.org.springframework.web.filter.CharacterEncodingFilter
5. </ Filter-class>
6. <init-param>
7. <param-name> ForceEncoding </ param-name>
8. <param-value> True </ param-value>
9. </ Init-param>
10. <init-param>
11. <param-name> Encoding </ param-name>
12. <param-value> GBK </ param-value>
13. </ Init-param>
14. </ Filter>
15. <filter-mapping>
16. <filter-name> EncodeFilter </ filter-name>
17. <url-pattern> *. Do </ url-pattern>
18. </ Filter-mapping>
<filter>
<filter-name> encodeFilter </ filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</ filter-class>
<init-param>
<param-name> forceEncoding </ param-name>
<param-value> true </ param-value>
</ init-param>
<init-param>
<param-name> encoding </ param-name>
<param-value> GBK </ param -
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of Spring.Hibernate.Struts1 integrated approach

  • Properties with 6 supplementary hibernate.cfg.xml configuration

    In some special circumstances, we may be saved in the database connection information config.properties document, for example, make a install.jsp to modify config.properties documents, implementation of online information on the database configuration. At

  • hibernate the third study (mapping file configuration)

    If you do not want to use the default hibernate.cfg.xml file as a configuration file, we can also specify the configuration file name: File file = new File ( "C: \ \ myhibernate.xml"); Configuration config = new Configuration (). Configure (file

  • Hibernate doubts

    Hibernate has been used recently, encountered in the implementation of inquiry A "Session is closed!" Troublesome, is as follows: org.hibernate.SessionException: Session is closed! at org.hibernate.impl.AbstractSessionImpl.errorIfClosed (Ab ...

  • Using Rails Captcha plug-in, easy implementation Verification Code

    Simple Captcha Plugin Can help us easily in the Rails implementation of Verification Code function. In addition, he has the option to provide sufficient to meet the U.S. requirements for certification, the use of easy. Supported picture and digital authen

  • Struts2 Spring Hibernate integration of easy

    1. Add Spring 2.0 in Libraries Choose the following four jar, and configure the / WEB-INF/lib under Spring2.0 AOP Libraries Spring2.0 Core Libraries Spring2.0 Persistence Core Libraries Spring2.0 WEb Libraries At the same time, the applicationContext ...

  • Struts2 Spring Hibernate's easy to integrate

    1. Add Spring 2.0 in Libraries Choose the following four jar, and configure the / WEB-INF/lib under Spring2.0 AOP Libraries Spring2.0 Core Libraries Spring2.0 Persistence Core Libraries Spring2.0 WEb Libraries At the same time, the applicationContext ...

  • jboss ejb3 Message Driven Bean

    Super Medium ejb hate. . . . . . . . . . . . . . . . . . . ================================================ To configure a Message Driven Bean in a different application server parameters are not the same. Currently only passed the test jboss. Message Dri

  • java read file

    java read documents in two ways: java.io and java.lang.ClassLoader When using the java.io, when java.lang.ClassLoader use it? (Note: If prior to read xml file java read file clearly aware of these two methods have been like! Can take much less to understa

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • WebQQ, ExtJs + Servlet + Hibernate + Spring implementation

    Code for the development of boredom when using ExtJs + Servlet + hibernate (Ant + xdoclet generate HBM files) + spring implementation, Pure whim, but implementation has been more than chat, group chat, what's not achieve, nor how to consider the perfo

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries