struts + spring + hibernate summary

2009-05-25  来源:本站原创  分类:Java  人气:984 

struts + spring + hibernate summary
1. Myeclipse in order to load struts, spring, hibernate
2. Add filter
Add WEN-INF/web.xml
<filter>
<filter-name> encodingfilter </ filter-name>
<filter-class> com.yourcompany.EncodingFilter </ filter-class>
</ filter>
<filter-mapping>
<filter-name> encodingfilter </ filter-name>
<url-pattern> / * </ url-pattern>
</ filter-mapping>
EncodingFilter.java
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter (
public void init (FilterConfig cong) (
/ / Do nothing
)
public void doFilter (ServletRequest srequest, ServletResponse sresponse,
FilterChain chain) (
try (
srequest.setCharacterEncoding ( "UTF-8");
chain.doFilter (srequest, sresponse);
) Catch (Exception e) (
e.printStackTrace ();
)
)
public void destroy () (
/ / Do nothing
)
)
3. Log4j.properties with log
Log4j.properties
# Configure logging for testing: optionally with log file
log4j.rootLogger = debug, stdout
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =% d% p [% c] -% m% n
log4j.appender.logfile = org.apache.log4j.FileAppender
log4j.appender.logfile.File = target / spring.log
log4j.appender.logfile.layout = org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern =% d% p [% c] -% m% n
4. Struts of the two ways to load spring
The first is: spring loaded through web.xml context configuration, the configuration is as follows
<context-param>
<param-name> contextConfigLocation </ param-name>
<param-value> / WEB-INF/applicationContext.xml </ param-value>
</ context-param>
/ / Loaded through the listener
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</ listener-class>
</ listener>
Or use severlet Class Loading
<servlet>
<servlet-name> context </ servlet-name>
<servlet-class>
org.springframework.web.context.ContextLoaderServlet
</ servlet-class>
<load-on-startup> 1 </ load-on-startup>
</ servlet>
The second use of Struts plug-in in struts-config.xml
<plug-inclassName="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property = "contextConfigLocation"
value = "/ WEB-INF/applicationContext.xml" />
</ plug-in>
This is a clear distinction between the two configurations is that the first approach can be configured multiple spring configuration file.
5. Spring Integration Struts
Struts-config.xml Action to replace the Type
<action path="/login" type="org.springframework.web.struts.DelegatingActionProxy" />
In the Spring configuration file applicationContext.xml to configure Bean
Points: through the path and name of the bean to match, these two values must be the same
<bean name="/login"> </ bean>
6. Organizational Structure
dao storage interface dao
holding less dao.hibernate storage layer implementation
pojo storage model
storage business service layer interface
service.impl storage business layer implementation
web store UI action
7. Service agent
Spring also offers declarative transaction management. This is through the implementation of Spring AOP.
Spring transaction management in the usual way is to use AOP (for the programming section) approach for the general category of package java transaction control, it is the pass
Dynamic implementation of the agent had, because the interface is an example of delay, spring at this time through the interceptor, loading affairs section.
applicationContext.xml
SessionFactory definition
When the definition of sessionFactory
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </ prop>
<prop key="hibernate.show_sql"> true </ prop>
</ props>
</ property>
DataSource definition
SessionFactory definition
The definition of dao
Category as defined for the dao implementation type
<bean>
<property name="sessionFactory">
<ref bean="sessionFactory" />
</ property>
</ bean>
TransactionManager definition
<bean>
<property name="sessionFactory">
<ref local="sessionFactory" />
</ property>
</ bean>
The bean definition of agent
Business layer implementation UserService
At userDao for the spring into the business object layer
defined transactionAttributes Services agents will need to deal with intercept method
<bean>
<property name="proxyTargetClass">
<value> true </ value>
</ property>
<property name="transactionManager">
<ref bean="transactionManager" />
</ property>
<property name="target">
<bean>
<property name="userDao"> <ref bean="UserDAO" /> </ property>
</ bean>
</ property>
<property name="transactionAttributes">
<props>
<prop key="save*"> PROPAGATION_REQUIRED,-MyCheckedException </ prop>
<prop key="update*"> PROPAGATION_REQUIRED </ prop>
<prop key="*"> PROPAGATION_REQUIRED, readOnly </ prop>
<prop key="*"> PROPAGATION_REQUIRED </ prop>
</ props>
</ property>
</ bean>
Objects on the affairs of the other agent a written
<bean class = "org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
lazy-init = "true">
<property name="transactionManager">
<ref bean="transactionManager" />
</ property>
<property name="transactionAttributes">
<props>
<prop key="*"> PROPAGATION_REQUIRED </ prop>
</ props>
</ property>
</ bean>
<bean parent="baseTxProxy">
<property name="target">
<bean>
<property name="userDao">
<ref bean="UserDAO" />
</ property>
</ bean>
</ property>
</ bean>
8. POJO printing and testing
BaseObject.java
package com.yourcompany.hibernate;
import java.io.Serializable;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
public class BaseObject extends ActionForm implements Serializable (
public static final Log log = LogFactory.getLog (BaseObject.class);
public String toString () (
return ToStringBuilder.reflectionToString (this,
ToStringStyle.MULTI_LINE_STYLE);
)
public boolean equals (Object o) (
return EqualsBuilder.reflectionEquals (this, o);
)
public int hashCode () (
return HashCodeBuilder.reflectionHashCode (this);
)
)
9. Unit Testing
TestCase inheritance
public void testAdd () (
ApplicationContext ctx = new FileSystemXmlApplicationContext ( "D: \ \ wwwroot \ \ SSH \ \ WebRoot \ \ WEBINF \ \
applicationContext.xml ");
/ / new ClassPathXmlApplicationContext ( "springConfig.xml");
IUserService userService = (IUserService) ctx.getBean ( "UserService");
assertNotNull ( "userService is NULL!", userService);
User user = new User ();
user.setUsername ( "luo");
userService.save (user);
List list = userService.findByProperty ( "username", user.getUsername ());
User user01 = (User) list.get (0);
assertEquals (user01.getUsername (), "luo");
user01.setPassword ( "123456");
user01.setEmail ( "[email protected]");
user01.setBirthday ( "1980-8-8");
user01.setIntro ( "I love you!");
userService.attachDirty (user01);
userService.delete (user01);
)
Learn chainmobile
1. Organizational Structure
struts of the definition of UI-related action and form
po definition of pojo and mapping file
the definition of the relevant filter filter
related to the definition of dao and the dao interface implementation
business related to the definition and implementation of business logic interface
Call flow
2. Web.xml
Defined filters and struts configuration
3. Filter
Methods filter definition
The first layer filters the entire coding control station
public void doFilter (ServletRequest srequest, ServletResponse sresponse, FilterChain chain) (
try (
/ / Encoding
srequest.setCharacterEncoding ( "GBK");
/ / Continue to request
chain.doFilter (srequest, sresponse);
) catch (Exception e) (
e.printStackTrace ();
)
)
The second level control to determine whether the user has permission to enter the system
Struts action
Action form spring into
Business Interface dao interfaces
public void doFilter (ServletRequest srequest, ServletResponse sresponse, FilterChain chain) (
try (
HttpServletRequest requst = (HttpServletRequest) srequest;
HttpServletResponse response = (HttpServletResponse) sresponse;
HttpSession session = requst.getSession ();
/ / From the session object from the operator out, if there is no sign that is empty, go to the login page.
Toperator operator = (Toperator) session.getAttribute ( "operator");
if (operator == null) (
response.sendRedirect ( "/ chinamobile / index.html");
) Else (
chain.doFilter (srequest, sresponse);
)
) Catch (Exception e) (
e.printStackTrace ();
))
Control of the third layer to determine whether the user is an administrator
public void doFilter (ServletRequest srequest, ServletResponse sresponse, FilterChain chain) (
try (
HttpServletRequest requst = (HttpServletRequest) srequest;
HttpServletResponse response = (HttpServletResponse) sresponse;
HttpSession session = requst.getSession ();
/ / From the session operator to achieve
Toperator operator = (Toperator) session.getAttribute ( "operator");
String ad = operator.getIsAdmin (). ToString ();
/ / If it is an ordinary salesman, there is no authority for this operation
if (operator == null | | ad.equals ( "0")) (
response.sendRedirect ( "/ chinamobile / web / main.jsp");
) Else (
chain.doFilter (srequest, sresponse);
)
) Catch (Exception e) (
e.printStackTrace ();
))
Configure web.xml
<filter>
<filter-name> encodingfilter </ filter-name>
<filter-class> filter.EncodingFilter </ filter-class> / / filter the type of video
</ filter>
<filter-mapping>
<filter-name> encodingfilter </ filter-name>
<url-pattern> / * </ url-pattern> / / filter for those resources
</ filter-mapping>
struts-config.xml definition of action, actionForm, and data forward
class action
/ * This place is the key to spring
* FileSystemXmlApplicationContext category through the spring configuration file to be
* ApplicationContext get through the application context context.
* Using getBean (Class object name) method to get the business object layer
* Direct use of interface type on the correlation method can be called.
* /
Specific code examples:
ApplicationContext context = new
FileSystemXmlApplicationContext ( "C: \ \ eclipse \ \ workspace \ \ chinamobile \ \ src \ \ applicationContext.xml");
IOperator dooperator = (IOperator) context.getBean ( "operatorservice");
/ / Ioperator business layer interface into the implementation hosted by the spring
Business object layer
Dao here by injecting layer, business layer in order to realize the call of the persistence layer
Specific code examples:
/ / Data Access Layer Business Object operatordao accepted OperatorImp, by the spring into the (hosting)
<bean>
<property name="operator">
<ref bean="operatordao"/>
</ property>
</ bean>
/ / Data access layer into the sessionFactory, persistent implementation
Specific code examples:
<bean>
<property name="factory">
<ref bean="MySessionFactory"/>
</ property>
</ bean>
submitted with the things sessionFactory
private SessionFactory factory;
/ / Increase in operating
public boolean addOperator (Toperator operator) (
Session session = factory.openSession ();
Transaction ts = session.beginTransaction ();
session.save (operator);
ts.commit ();
boolean isok = ts.wasCommitted ();
session.close ();
return isok;
)
public boolean setMoney (Tcharge charge) (
boolean isok = true;
Session session = factory.openSession ();
Transaction ts = session.beginTransaction ();
System.out.println (charge.getChargeCode ());
Connection conn = session.connection ();
try (
Statement state = conn.createStatement ();
int i = state.executeUpdate ( "update TCHARGE set
charge = "+ charge.getCharge () +" where charge_code = ' "+ charge.getChargeCode ()+"'");
if (i == 0) (
isok = false;
)
) Catch (SQLException e) (
e.printStackTrace ();
)
ts.commit ();
session.close ();
return isok;
spring into the spring into the spring into the
Business Layer Interface
Business layer implementation
Data Access Layer Interface
Data access layer implementation sessionFactory
Data access layer implementation
)

相关文章
  • struts + spring + hibernate summary 2009-05-25

    struts + spring + hibernate summary 1. Myeclipse in order to load struts, spring, hibernate 2. Add filter Add WEN-INF/web.xml <filter> <filter-name> encodingfilter </ filter-name> <filter-class> com.yourcompany.EncodingFilter </

  • MVC layer model (struts + spring + hibernate) Summary 2010-04-30

    1 SSH in the development of the position J2EE framework is now more than a few open source is not clear, the current (already being) a common framework for popular about struts, spring, hibernate, jsf, webwork, the struts + spring + hibernate (SSH) T

  • Struts, Spring, Hibernate face questions Summary 2010-05-29

    Struts, Spring, Hibernate face questions Summary 1, Action is not thread safe? If not, what approach can guarantee the thread safety of Action? If yes, explain. Not declare local variables, or the expansion of RequestProcessor, so each time to create

  • Struts, Spring, Hibernate face Question Summary 2010-03-24

    Struts, Spring, Hibernate surface examination questions summarized Keywords: struts spring hibernate interview reproduced Address: http://blog.csdn.net/David8631/archive/2008/07/19/2676615.aspx only collection Hibernate works and why to use? Principl

  • Struts, Spring, Hibernate advantages and disadvantages 2009-05-07

    Struts, Spring, Hibernate advantages and disadvantages Struts with Tomcat, Turbine, and many other Apache projects, are open-source software, which is its one great advantage. Allow developers to more in-depth understanding of its internal mechanisms

  • The use of struts + spring + hibernate assembly web application 2009-11-16

    This article will discuss how the combination of several well-known framework to achieve the purpose of loosely coupled and how to set up your framework, how to make your line all the application layer. Challenging are: combination of these framework

  • Using struts + spring + hibernate web application assembly 2010-04-01

    This article will discuss how the combination of several well-known framework to achieve the purpose of loose coupling, how to build your framework, how to make you be consistent in all the application layer. Challenging is: the combination of these

  • Struts, Spring, Hibernate Web application development 1 2009-05-11

    This article is taken from: http://www.blogjava.net/jacky9881/archive/2008/01/02/172076.html This Web application is very simple implementation of a user registration page, when users register at register.jsp enter information page, point to preserve

  • struts, spring, hibernate, convent plugin 2010-03-25

    Integrate struts, spring, hibernate, the biggest trouble for beginners on their cumbersome xml configuration file. Now all of which are annotation-based configuration provides a good support for . The struts2, the use of convent plugin, thanks to ann

  • struts.spring.hibernate integration steps 2010-05-11

    SSH integration process? struts, spring, hibernate integration steps: 1. Importing struts, spring, hibernate package necessary 2. In the web.xml to configure <context-param> <param-name> contextConfigLocation </ param-name> <param-val

  • Struts Spring Hibernate lex EXT-GWT SqlServer MySql Oracle 2010-06-20

    My blog has been transferred to http://blog.csdn.net/Jerry_BJ Struts Spring Hibernate lex EXT-GWT SqlServer MySql Oracle

  • struts spring hibernate I see advantages and disadvantages of the (Comprehensive paste non-original) 2010-07-22

    Struts spring hibernate more "spread", and outside many companies are often asked about the SSH always advantages and disadvantages of the interview, the network also has many advantages and disadvantages of some article summing up ssh, but I fe

  • MyEclipse development of SSH (Struts + Spring + Hibernate) started [with map] 2010-08-04

    MyEclipse development of SSH (Struts + Spring + Hibernate) Getting Started March 6, 2008 at 11:24 (This reference from oksonic the " Struts + Spring + Hibernate practice (full) ") Source Download: http://ishare.iask.sina.com.cn/cgi-bin/fileid.cg

  • Struts + Spring + Hibernate processing Lob (Blob, Clob) 2010-12-09

    Struts + Spring + Hibernate processing Lob (Blob, Clob) Using struts + spring + hibernate in the development, sometimes the user will need the database files stored in the database normally used Blob Clob field or fields to store the binary image, st

  • Struts.Spring.Hibernate (SSH) integration examples 2009-04-09

    Web.xml is the first choice to create the ActionServlet and Struts configuration Spring characters filter <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http:/

  • Struts Spring Hibernate (SSH) integration example 2009-08-12

    http://www.blogjava.net/action/archive/2009/04/09/140566.html Web.xml is the first choice to create the ActionServlet and Struts configuration Spring filter characters <? xml version = "1.0" encoding = "UTF-8"?> <web-app xmlns

  • Struts + Spring + Hibernate development to join the real kung fu 2010-06-12

    The context of occupational demand. Book in-depth analysis of the current language of the mainstream Java development skills needs, and as the premise for the book content organization. * For application development into the behavior of target. This

  • Struts + Spring + Hibernate's technology 2010-06-28

    1, 3 About the framework Struts: Struts is Java Web MVC framework undisputed king. After more than five years of development, Struts has gradually grown into a stable, mature framework, and the possession of the MVC framework for the largest market s

  • Struts + Spring + Hibernate environment set up 2010-10-05

    First, the automatic loading Struts Create a new WebProject project, right-click the project name -> MyEclipse-> Add Struts Capabilities Select the version of Struts and fill "Base package for new classes" For example, "Struts1.2"

  • Struts / Spring / Hibernate wiki translation in English 2011-01-08

    see http://en.wikipedia.org/wiki/Apache_Struts Apache Struts From Wikipedia, the free encyclopedia Apache Struts is an open-source web application framework for developing Java EE web applications. It uses and extends the Java Servlet API to encourag