SSH integration and ssh integration instances

Source: Internet
Author: User

SSH integration and ssh integration instances

Preface

The so-called SSH means that the presentation layer uses Struts2, the business logic layer uses Spring, and the data access layer uses Hibernate. Well, we don't need to talk much about it. Let's start it.

Prerequisites: You need to be familiar with the basic use of Struts2, Spring, and Hibernate.

Step 1: Add tedious Jar packages. Step 2: integrate Hibernate with Spring. Step 3: integrate Struts2 with Spring.

------------------------------------------------- I don't know what the split line is --------------------------------------------------------------------------------

I am searching for jar packages in these four files.

(1) Import Struts jar package, struts-2.3.15.3 \ apps \ struts2-blank \ WEB-INF \ lib under the jar package

 

The following is a key jar package for Struts and Spring:Struts2-spring-plugin-2.3.15.3.jar, Not listed above. (14 packages in total)

② Import Spring jar package, one is the core package: spring-framework-3.2.0.RELEASE \ libs

The other is the dependency package:

Among them, the spring-orm.jar is Spring integration Hibernate off the build package. (13 packages in total)

Note: If you reference Spring separately, you also need to introduce a dependency package: com.springsource.org. apache. commons. logging-1.1.1.jar, but since the previous Struts2 introduced the commons-logging-1.1.3.jar package, you do not need to reference it again. In fact, they are the same code, but Spring changes its name and you can view the code to find it.

③ Import the Hibernate Jar package

The ehcache. jar package is Hibernate's second-level cache package, which relies on backport-util-concurrent.jar, and commons-logging.jar packages. (10 packages in total)

Hibernate also has a javassist-3.12.0.GA.jar package, Struts2 has referenced the javassist-3.11.0.GA.jar, All I replace with 12. Not listed above.

④ Of course, there is a jar package, that isMysql-connector-java-5.0.8-bin.jar.

So far, a total of 38 packages have been added and will not be changed.

---------------------------------------- Set the split line --------------------------------------------------------------------------------------------------

Business: Add a user

Entity class: User (two fields: name and age)

------------------------------ [Spring + Hibernate] split line -----------------------------------------------------------------------------------------------

Spring began to integrate Hibernate. As we all know, both frameworks have their own configuration files: Spring applicationContext. xml (any name), Hibernate configuration file and hibernate ing file Hibernate. cfg. xml and [entity class ]. hbm. xml file. The result of integration is that the Hibernate configuration file disappears (of course, its configuration information is included in the Spring configuration file ).

Program code:

// User interface of the DAL layer public interface UserDao {boolean insert (user User );} // specific implementation of the User interface at the DAL layer public class UserDaoImpl extends HibernateDaoSupport implements UserDao {@ Override public boolean insert (user User) {HibernateTemplate s = this. getHibernateTemplate (); s. save (user); return true ;}}

ApplicationContext. xml file configuration: (User. hbm. xml is not much to say, no difference)

<! -- Use C3P0 to obtain the data source --> <bean id = "dataSource" class = "com. mchange. v2.c3p0. comboPooledDataSource "> <property name =" driverClass "value =" com. mysql. jdbc. driver "> </property> <property name =" jdbcUrl "value =" jdbc: mysql: // localhost: 3306/test "> </property> <property name =" user "value =" root "> </property> <property name =" password "value =" 123456 "> </property> </bean> <! -- Use FactoryBean to create Spring and get SessionFactory --> <bean id = "sessionFactory" class = "org. springframework. orm. hibernate3.LocalSessionFactoryBean"> <! -- Hibernate. cfg. the configuration information in the xml file is injected in, you can delete the configuration file --> <property name = "dataSource" ref = "dataSource"> </property> <property name = "hibernateProperties"> <props> <prop key =" hibernate. dialect "> org. hibernate. dialect. mySQLDialect </prop> <prop key = "javax. persistence. validation. mode "> none </prop> <prop key =" hibernate. show_ SQL "> true </prop> <prop key =" hibernate. format_ SQL "> true </prop> <prop key =" hibernate. hbm2ddl. au To "> update </prop> <prop key =" hibernate. current_session_context_class "> thread </prop> </props> </property> <property name =" mappingLocations "value =" classpath: king/domain/User. hbm. xml "> </property> </bean> <! -- Purpose: to create DAO --> <bean id = "userDao" class = "king. dao. impl. userDaoImpl "> <property name =" sessionFactory "ref =" sessionFactory "> </property> </bean> <! -- For Hibernate of Spring transaction management, SessionFactory needs to be injected --> <bean id = "txManager" class = "org. springframework. orm. hibernate3.HibernateTransactionManager "> <property name =" sessionFactory "ref =" sessionFactory "> </property> </bean> <! -- Notification --> <tx: advice id = "adviceId" transaction-manager = "txManager"> <tx: attributes> <tx: method name = "*" propagation = "REQUIRED" isolation = "DEFAULT"/> </tx: attributes> </tx: advice> <aop: config> <aop: advisor advice-ref = "adviceId" pointcut = "execution (* king. dao. impl. *. *(..)) "/> </aop: config>

Test code:

    @Test    public void test1(){        ClassPathXmlApplicationContext app=new ClassPathXmlApplicationContext("applicationContext.xml");        UserDao user=app.getBean(UserDao.class);        User u=new User();        u.setAge(1);        u.setName("King");        user.insert(u);        app.close();    }

In this way, the integration of Spring and Hibernate is realized, and the hibernate. cfg. xml file is removed. From the original direct operation of SessionFactory, Session is now operated on the classes provided by Spring.

Explanation:

  • 1

Previously, when we used Spring JdbcTemplate, we needed the DAL layer object to inherit JdbcDaoSupport. While we integrated Hibernate, we needed the DAO object to inherit the HibernateDaoSupport. Instead, we inherit this class to get the HibernateTemplate object and operate the database. The HibernateTemplate is used in a similar way as the Session, and the underlying layer is Session. Data sources and other configurations must be before we get the HibernateTemplate object. Therefore, we must inject the [configuration information originally written in hibernate. cfg. xml ]. When it comes to HibernateDaoSupport injection, either inject SessionFactory or HibernateTemplate. Here we inject SessionFactory. You can see in the configuration file above.

  • 2

Let's talk about the applicationContext. xml file. To get the UserDaoImpl object, we need to inject SessionFactory into it. To get SessionFactory, we need to inject DataSource and various configuration information into it. The data source (connection pool) here uses C3P0.

  • 3

Let's take a look at the generation of the UserDaoImpl object. We certainly get the proxy object, because the <aop: config> </aop: config> label has been added below, therefore, it is a fully automatic proxy object generated based on the JDK proxy object method of the interface. Of course, you can also set it to CGlib to generate the proxy object, additional configuration required <proxy-target-class = "true">

  • 4

The notification of the proxy object here is a transaction. You can use txManager to add [enable transaction] [commit transaction/rollback transaction and other operations] before and after the target method, and then return the proxy object. At this time, all our operations are in the transaction. As long as an exception occurs, the transaction will be rolled back. Here is a declarative transaction.

  • 5

Let's talk about the functions of the packages we added.

Spring-orm.jar it is the key to Spring integration Hibernate, it depends on the spring-jdbc.jar package, because it will use the LobHandler class.

Spring-web.jar it is the key to let the Tomcat container load the Spring configuration file. Because we need the container to load the configuration file for us and create a proxy object.

Slf4j-api.jar SLF4J (Simple logging Facade for Java) is not a real log implementation, but an abstraction layer that allows you to use any log class library in the background. If you are writing an API or a common class library that can be used internally and externally, you really do not want the client that uses your class library to use the log class library you selected. So to use log4j, we need to introduce the slf4j-log4j.jar package.

-------------------------------------- [Struts2 + Spring] integrated split line -------------------------------------------------------------------

Struts. xml:

<Struts> <constant name = "struts. devMode "value =" true "/> <package name =" User "namespace ="/User "extends =" struts-default "> <! -- Action instances are created by struts --> <action name = "AddUser" class = "king. action. userAction "method =" addUser "> <result name =" success "type =" redirect ">/success.html </result> </action> </package> </struts>

Web. xml:

<! -- The configuration in these two fields is Spring to integrate the Web, because it was manually loaded. xml file. Now Tomcat is required to start loading. xml file, so Spring needs to integrate the Web, let Tomcat load the configuration file, to implement injection, generate proxy and other functions. The spring-web.jar package is at work. --> <! -- Many Spring jar packages rely on the commons-logging.jar package Commons-logging.jar to provide a unified interface for "All Java log implementations. --> <! -- Configure the location of the spring configuration file --> <context-param> <param-name> contextConfigLocation </param-name> <param-value> classpath: applicationContext. xml </param-value> </context-param> <! -- If only spring listening is configured, the default position src/applicationContext. xml will be loaded to automatically assemble the configuration information of ApplicationContext when the Web container is started. --> <Listener-class> org. springframework. web. context. ContextLoaderListener </listener-class> </listener>
<! -- Struts filter --> <filter-name> struts2 </filter-name> <filter-class> org. apache. struts2.dispatcher. ng. filter. strutsPrepareAndExecuteFilter </filter-class> </filter> <filter-mapping> <filter-name> struts2 </filter-name> <url-pattern>/* </url-pattern> </filter-mapping>

UserAction class:

/*** ActionSupport from xwork-core.jar *** question: who injected userDao? * Answer: struts2-spring-plugin.jar in the struts-plugin.xml, set the default object factory for Spring, injected by Spring. ** @ Author King **/public class UserAction extends ActionSupport implements ModelDriven <User> {private static final long serialVersionUID = 1885943501464870512L; private User user = new User (); @ Override public User getModel () {return user;} private UserDao userDao; public void setUserDao (UserDao userDao) {this. userDao = userDao;} public String addUser () {boolean isOk = userDao. insert (user); if (isOk) {return "success" ;}else {return "fail ";}}}

In this way we achieve the Struts2 + Spring integration, the key lies in the web. xml configuration and struts2-spring-plugin.jar in the struts-plugin.xml, two configuration files.

Explanation:

  • 1

Struts2 has a series of configuration files loaded in certain Order 1: default. propertities 2: struts-default.xml 3: struts-plugin.xml 4: struts. xml.

While we introduced the struts2-spring-plugin.jar, where there is a struts-plugin.xml, which sets the object factory to be created by Spring. Therefore, the UserAction here is created by Struts2, but the UserDao object is injected by Spring. Note: <bean id = "userDao"> </bean> and private UserDao userDao in the Code; the name must be the same so that Spring can be injected. Otherwise, a null pointer exception occurs.

  • 2

In the previous test class, we manually loaded the applicationContext. xml file to obtain the bean, and integrated Struts2. We found that this process was not done, and Spring still works normally. Why?

This is the listener class we configured above.<Listener-class> ContextLoaderListener </listener-class>Purpose: load the applicationContext. xml file, so we didn't manually load the configuration file and Spring works normally. You can see that the package of this class isSpring-web.jar,So this package is also the key to integrating them.

 

Now, the three major SSH frameworks have been integrated.

 

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.