SSH2环境搭建
一、创建SSH2项目,导入Struts2并测试。
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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>*.action</url-pattern> </filter-mapping></web-app>
default.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>default page</title> </head> <body> default page </body> </html>
UserAction.java
package com.cwq.action; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { @Override public String execute() throws Exception { // TODO Auto-generated method stub //return super.execute(); return SUCCESS; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="cwq" extends="struts-default"> <action name="showUsers" class="com.cwq.action.UserAction"> <result name="success">default.jsp</result> </action> </package> </struts>
发布项目,启动Tomcat,运行结果:
二、导入Spring包,配置数据源
三,Spring与Hibernate整合
在web.xml中加入
<!-- 必须放在顶上 -->
<!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 对Spring容器进行实例化 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" 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_3_0.xsd"> <!-- 必须放在顶上 --> <!-- 指定spring的配置文件,默认从web根目录寻找配置文件,我们可以通过spring提供的classpath:前缀指定从类路径下寻找 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 对Spring容器进行实例化 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <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>*.action</url-pattern> </filter-mapping></web-app>
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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/sdu"></property> <property name="username" value="root"></property> <property name="password" value="064417"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> </bean></beans>
测试,发布,启动Tomcat,如果启动成功则整合成功。
四、根据数据库反向生成代码
Users.java
package com.cwq.model; import java.sql.Timestamp; /** * Users entity. @author MyEclipse Persistence Tools */ public class Users implements java.io.Serializable { // Fields private Integer id; private String username; private String password; private Timestamp birthdate; // Constructors /** default constructor */ public Users() {} /** full constructor */ public Users(String username, String password, Timestamp birthdate) { this.username = username; this.password = password; this.birthdate = birthdate; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Timestamp getBirthdate() { return this.birthdate; } public void setBirthdate(Timestamp birthdate) { this.birthdate = birthdate; } }
user.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="com.cwq.model.Users" table="users" catalog="sdu"> <id name="id" type="java.lang.Integer"> <column name="id" /> <generator class="identity" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="45" not-null="true"/> </property> <property name="password" type="java.lang.String"> <column name="password" length="45" not-null="true" /> </property> <property name="birthdate" type="java.sql.Timestamp"> <column name="birthdate" length="23" not-null="true" /> </property> </class> </hibernate-mapping>
UserDao.java
package com.cwq.dao; import java.sql.Timestamp; import java.util.List; import org.hibernate.LockMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.cwq.model.Users; /** * A data access object (DAO) providing persistence and search support for Users * entities. Transaction control of the save(), update() and delete() operations * can directly support Spring container-managed transactions or they can be * augmented to handle user-managed Spring transactions. Each of these methods * provides additional information for how to configure it for the desired type * of transaction control. * @see com.cwq.model.Users * @author MyEclipse Persistence Tools */ public class UsersDAO extends HibernateDaoSupport { private static final Logger log = LoggerFactory.getLogger(UsersDAO.class); // property constants public static final String USERNAME = "username"; public static final String PASSWORD = "password"; protected void initDao() { // do nothing } public void save(Users transientInstance) { log.debug("saving Users instance"); try { getHibernateTemplate().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Users persistentInstance) { log.debug("deleting Users instance"); try { getHibernateTemplate().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Users findById(java.lang.Integer id) { log.debug("getting Users instance with id: " + id); try { Users instance = (Users) getHibernateTemplate().get("com.cwq.model.Users", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Users instance) { log.debug("finding Users instance by example"); try { List results = getHibernateTemplate().findByExample(instance); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Users instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Users as model where model." + propertyName + "= ?"; return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByUsername(Object username) { return findByProperty(USERNAME, username); } public List findByPassword(Object password) { return findByProperty(PASSWORD, password); } public List findAll() { log.debug("finding all Users instances"); try { String queryString = "from Users"; return getHibernateTemplate().find(queryString); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Users merge(Users detachedInstance) { log.debug("merging Users instance"); try { Users result = (Users) getHibernateTemplate().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Users instance) { log.debug("attaching dirty Users instance"); try { getHibernateTemplate().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Users instance) { log.debug("attaching clean Users instance"); try { getHibernateTemplate().lock(instance, LockMode.NONE); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public static UsersDAO getFromApplicationContext(ApplicationContext ctx) { return (UsersDAO) ctx.getBean("UsersDAO"); } }
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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/sdu"></property> <property name="username" value="root"></property> <property name="password" value="064417"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> <property name="mappingResources"> <list> <value>com/cwq/model/Users.hbm.xml</value></list> </property></bean> <bean id="UsersDAO" class="com.cwq.dao.UsersDAO"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean></beans>
五、Struts整合Spring
UserAction.java
package com.cwq.action; import java.util.List; import com.cwq.dao.UsersDAO; import com.cwq.model.Users; import com.opensymphony.xwork2.ActionSupport; public class UserAction extends ActionSupport { private List<Users> users = null; private UsersDAO userDao; public void setUserDao(UsersDAO userDao) { this.userDao = userDao; } @Override public String execute() throws Exception { // TODO Auto-generated method stub //return super.execute(); users = userDao.findAll(); return SUCCESS; } public List<Users> getUsers() { return users; } public void setUsers(List<Users> users) { this.users = users; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
applicationContext.xml
加入
<bean id="userAction" class="com.cwq.action.UserAction">
<property name="userDao"><!-- 依赖注入(单例),在UserAction中必须要有一个userDao的属性有其set方法 -->
<ref bean="UsersDAO"/>
</property>
</bean>
<?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/sdu"></property> <property name="username" value="root"></property> <property name="password" value="064417"></property> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource"> <ref bean="dataSource" /> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> </props> </property> <property name="mappingResources"> <list> <value>com/cwq/model/Users.hbm.xml</value></list> </property></bean> <bean id="UsersDAO" class="com.cwq.dao.UsersDAO"> <property name="sessionFactory"> <ref bean="sessionFactory"/> </property> </bean> <bean id="userAction" class="com.cwq.action.UserAction"> <property name="userDao"><!-- 依赖注入(单例),在UserAction中必须要有一个userDao的属性有其set方法 --> <ref bean="UsersDAO"/> </property> </bean> </beans>
struts.xml
加入
<!-- 由Spring来代理控制层 -->
<constant name="struts.objectFactory" value="spring" />
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 由Spring来代理控制层 --> <constant name="struts.objectFactory" value="spring" /> <package name="cwq" extends="struts-default"> <!-- <action name="showUsers" class="com.cwq.action.UserAction"> --> <action name="showUsers" class="userAction"><!-- Spring中的userAction --> <result name="success">default.jsp</result> </action> </package> </struts>
default.jsp
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!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>default page</title> </head> <body> default page<p> <!-- UserAction中的users --> <c:forEach var='user' items='${users}'> ${user.username}--${user.password}--${user.birthdate} </br> </c:forEach> </body> </html>
如果要指定进入某个action加入下面代码
<script type="text/javascript">
document.location.href = "showUsers.action";
</script>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> document.location.href = "showUsers.action"; </script> </head> <body> This is my JSP page. <br> </body> </html>