Structs1+spring+Hibernate
Structs 相当于mvc设计模式中V.C,即jsp页面和Servlet;
spring 管理业务逻辑,即Service;
Hibernate 管理DAO,持久层;
首先讲一下Hibernate和spring的整合:
1.加入相关的jar:mysql的 mysql-connector-java-5.1.13-bin.jar;
Hibernate的就不一一列出的(上一篇文章有提到);特别注意的是要导slf4j相关的底层实现包 slf4j-nop-1.5.8.jar
spring的相关jar(spring\reqlib底下所有,spring\spring-framework-3.1.0.RC1-with-docs\spring-framework-3.1.0.RC1\dist底下所有);
2.提供spring的配置文件。applicationContext.xml;
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:annotation-config /> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <context:component-scan base-package="com"></context:component-scan> </beans>
3.配置数据库连接池。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:annotation-config /> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <context:component-scan base-package="com"></context:component-scan> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> </beans>
此时,写个测试类,测试下。(前提是数据库已存在表格t_user);
package Test; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbcp.BasicDataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class T { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); BasicDataSource dataSource = ac.getBean("myDataSource",BasicDataSource.class); Connection conn; try { conn = dataSource.getConnection(); conn.createStatement().executeUpdate("insert into t_user values(null,'arron','1234')"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
4.配置sessionFactory;
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:annotation-config /> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <context:component-scan base-package="com"></context:component-scan> <!--配置数据库连接池--> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!--配置sessionFactory--> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="myDataSource"/> <property name="packagesToScan" value="com.kebin.pojo"> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> </bean> </beans>
配置完成了,写了User pojo类,和测试类,测试下。
package com.kebin.pojo; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="t_user") public class User { private int id; private String name; private String password; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
package Test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.kebin.pojo.User; public class T { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); SessionFactory sf = ac.getBean("mySessionFactory",SessionFactory.class); Session session = sf.getCurrentSession(); Transaction ts = session.beginTransaction(); ts.begin(); User user = new User(); user.setName("admin"); user.setPassword("123456"); session.save(user); ts.commit(); } }
接着往下写业务逻辑层。
package com.kebin.dao; import com.kebin.pojo.User; public interface UserDao { public void save(User user); }
package com.kebin.dao; import org.springframework.stereotype.Component; import com.kebin.pojo.User; @Component("userDao") public class UserDaoImpl implements UserDao { public void save(User user) { // TODO Auto-generated method stub } }
package com.kebin.service; import com.kebin.pojo.User; public interface UserService { public void add(User user); }
书写一个DaoSupport类继承自HibernateTemplate;
package com.kebin.dao; import javax.annotation.Resource; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; @Component public class DaoSupport extends HibernateTemplate { private SessionFactory sessionFactory; @Resource(name="mySessionFactory") public void setSessionFactory(SessionFactory sessionFactory) { super.setSessionFactory(sessionFactory); } }
package com.kebin.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.kebin.dao.DaoSupport; import com.kebin.dao.UserDao; import com.kebin.pojo.User; import com.kebin.service.UserService; @Service("userService") public class UserServiceImpl extends DaoSupport implements UserService { private UserDao userDao; @Resource(name="userDao") public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void add(User user) { this.save(user); } }
最后写个测试类T.java,进行测试下。这样hibernate和spring就配置好了。
package Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.kebin.pojo.User; import com.kebin.service.UserService; public class T { public static void main(String[] args) { ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml"); UserService userService = ac.getBean("userService",UserService.class); User user = new User(); user.setName("kebin"); user.setPassword("1111111"); userService.add(user); } }
接下来,讲一下Spring 和 Struts 的整合
我这里用的是Struts1,可能很多公司都已经不用了的。
1.导入Struts的包,struts1\struts-1.3.10-all\struts-1.3.10\lib底下所有的包。
(有两个包和hibernate重复了,删除就可以了。commons-logging.jar 和 antlr-2.7.6.jar 留下版本高的);
2.拷入struts-config.xml配置文件;
(将struts-config.xml和applicationContext.xml都放在WEB-INF的底下)
3.书写UserAction.java和index.jsp页面。代码我直接贴出;
package com.kebin.action; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.DynaActionForm; import org.apache.struts.actions.DispatchAction; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import com.kebin.pojo.User; import com.kebin.service.UserService; @Controller @Qualifier("/user") public class UserAction extends DispatchAction { private UserService userService; @Resource(name = "userService") public void setUserService(UserService userService) { this.userService = userService; } public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { DynaActionForm df = (DynaActionForm) form; // 配置了注解,直接将userService注入,这段读取的代码就不用了; // ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServlet().getServletContext()); // UserService userService = ac.getBean("userService",UserService.class); User user = new User(); user.setName(df.getString("username")); user.setPassword(df.getString("password")); userService.add(user); return mapping.findForward("success"); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Insert title here</title> </head> <body> <form action="user.do?command=login" method="post"> username:<input type="text" name="username"/><br> password:<input type="text" name="password"/><br> <input type="submit" value="tijiao"> </form> </body> </html>
4.配置web.xml;(注意中文乱码的配置);
<?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"> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <!-- 配置spring的监听器,用以实现依赖注射 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 配置spring的配置文件的读取路径 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <!-- 借用spring 实现对中文乱码的修改 --> <filter> <filter-name>Set Character Encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>Set Character Encoding</filter-name> <url-pattern>*.do</url-pattern> </filter-mapping> <!-- action 的配置 --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
5.配置applicationContext.xml;(这里只要加个bean标签,来代替action-mappings里面的action中type="");
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <context:annotation-config /> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <context:component-scan base-package="com"></context:component-scan> <!--配置数据库连接池 --> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mysql" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!--配置sessionFactory --> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="myDataSource" /> <property name="packagesToScan" value="com.kebin.pojo"> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.current_session_context_class">thread</prop> </props> </property> </bean> <!-- 用注解来代替struts-config.xml配置文件中action的type="com.kebin.action.UserAction" --> <bean name="/user" class="com.kebin.action.UserAction"></bean> </beans>
6.配置struts-config.xml;
<?xml version="1.0" encoding="UTF-8" ?> <!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> <form-beans> <form-bean name="login" type="org.apache.struts.action.DynaActionForm"> <form-property name="username" type="java.lang.String"></form-property> <form-property name="password" type="java.lang.String"></form-property> </form-bean> </form-beans> <action-mappings> <action path="/user" name="login" parameter="command"> <forward name="success" path="/ok.jsp"></forward> </action> </action-mappings> <!-- 用注解来代替action-mappings配置中action标签对里的type="com.kebin.action.UserAction(此处)" --> <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"> </controller> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" /> </plug-in> </struts-config>
以上给出简单列子的配置,基本的配置已经完成。谢谢各位大牛给出宝贵的评价。