SSH使用总结(annotation配置方式)
所需的jar包
beans.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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><!-- 开启注解方式使用IOC --><context:annotation-config /><context:component-scan base-package="com.anllin"/><!-- 开启注解方式使用AOP --><!--<aop:aspectj-autoproxy/>--><!-- 自动读取jdbc.properties里的配置 --><!--<context:property-placeholder location="classpath:jdbc.properties"/>--><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="locations"><value>classpath:jdbc.properties</value></property></bean><!-- 配置dataSource --><!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/spring" /> <property name="username" value="root" /> <property name="password" value="123" /> </bean> --><bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"><property name="driverClassName" value="${jdbc.driverClassName}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!-- 配置sessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><property name="dataSource" ref="dataSource"/><property name="packagesToScan"><list><value>com.anllin.registration.model</value></list></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></props></property></bean><!-- spring事务的annotation配置 ,需要多个配置时会比较繁琐,少量配置时会方便很多--><!-- <tx:annotation-driven transaction-manager="txManager"/>--><!-- 开启事务管理 --><bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/></bean><!--xml方式配置切面 --><!-- <bean id="userService" class="com.anllin.service.UserService"></bean> <bean id="logInterceptor" class="com.anllin.aop.LogInterceptor"></bean> <aop:config> <aop:aspect id="logAspect" ref="logInterceptor"> <aop:pointcut expression="execution(* com.anllin.registration.service..*.*(..))" id="servicePointCut" /> <aop:before method="before" pointcut-ref="servicePointCut" /> </aop:aspect> </aop:config> --><!-- spring事务的xml配置 ,建议使用--><aop:config><aop:pointcut id="bussinessService" expression="execution(* com.anllin.registration.service..*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="bussinessService"/></aop:config><!-- 对不同的方法进行不同的事务管理 --><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="get*" read-only="true" propagation="NEVER"/><tx:method name="isExists*" read-only="true" propagation="NEVER"/><tx:method name="*" propagation="REQUIRED" read-only="false"/></tx:attributes></tx:advice><!-- 实现hibernateTemplate注入 --><bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"><property name="sessionFactory" ref="sessionFactory"/></bean><!--实现HibernateDaoSupport注入 --><!-- <bean id="abstractDao" class="com.anllin.dao.impl.AbstractDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> --></beans>
jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/spring jdbc.username=root jdbc.password=123
log4j.properties
# # Hibernate, Relational Persistence for Idiomatic Java # # Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as # indicated by the @author tags or express copyright attribution # statements applied by the authors. All third-party contributions are # distributed under license by Red Hat Middleware LLC. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # Lesser General Public License, as published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this distribution; if not, write to:# Free Software Foundation, Inc. # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301 USA # #log4j.rootLogger=info, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=warn, stdout #log4j.logger.org.hibernate=debug #log4j.logger.org.hibernate.test=info ### log schema export/update ### log4j.logger.org.hibernate.tool.hbm2ddl=debug #log4j.logger.org.hibernate.sql.ordering.antlr.OrderByFragmentTranslator=trace #log4j.logger.org.hibernate.ejb=debug #log4j.logger.org.hibernate.ejb.packaging=debug #log4j.logger.org.hibernate.reflection=debug #log4j.logger.org.hibernate.hql.ast.QueryTranslatorImpl=trace #log4j.logger.org.hibernate.hql.ast.HqlSqlWalker=trace #log4j.logger.org.hibernate.hql.ast.SqlGenerator=trace #log4j.logger.org.hibernate.hql.ast.AST=trace #log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=trace #log4j.logger.org.hibernate.type.BasicTypeRegistry=trace #log4j.logger.org.hibernate.engine.Cascades=debug #log4j.logger.org.hibernate.hql=debug ### log just the SQL #log4j.logger.org.hibernate.SQL=debug ### log JDBC bind parameters ### #log4j.logger.org.hibernate.type=info #log4j.logger.org.hibernate.type=trace ### log HQL parse trees #log4j.logger.org.hibernate.hql=debug ### log cache activity ### #log4j.logger.org.hibernate.cache=debug ### log JDBC resource acquisition #log4j.logger.org.hibernate.jdbc=debug ### enable the following line if you want to track down connection ### ### leakages when using DriverManagerConnectionProvider ### #log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace #log4j.logger.org.jgroups=info #log4j.logger.org.jboss.cache=trace #log4j.logger.org.jboss.cache.RegionManager=info #log4j.logger.org.jboss.cache.lock=info #log4j.logger.org.jboss.cache.interceptors.PessimisticLockInterceptor=info #log4j.logger.org.jboss.cache.interceptors.UnlockInterceptor=info
struts.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"><struts><!-- <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <constant name="struts.devMode" value="false" /> <package name="default" namespace="/" extends="struts-default"> <default-action-ref name="index" /> <global-results> <result name="error">/error.jsp</result> </global-results> <global-exception-mappings> <exception-mapping exception="java.lang.Exception" result="error"/> </global-exception-mappings> <action name="index"> <result type="redirectAction"> <param name="actionName">HelloWorld</param> <param name="namespace">/example</param> </result> </action> </package> <include file="example.xml"/> --><package name="registration" namespace="/" extends="struts-default"><action name="u" class="u"><result name="success">/registerSuccess.jsp</result><result name="fail">/registerFail.jsp</result><result name="list">/userlist.jsp</result><result name="load">/user.jsp</result></action></package></struts>
UserAction.java
package com.anllin.registration.action; import java.util.List; import javax.annotation.Resource; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.anllin.registration.model.User; import com.anllin.registration.service.UserService; import com.anllin.registration.vo.UserInfo; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; //使用struts2-spring-plugin.jar后就不用使用@Component了,因为这个插件会默认按名初始化bean //如果在配置文件中指定了name和class为user,那么UserAction就会交给spring管理,这样方便测试。 //但是要指定@Scope("prototype"),不然默认是singleton //使用ModelDriven必须使用private UserInfo userInfo = new UserInfo();@SuppressWarnings("unchecked") @Component("u") @Scope("prototype") publicclass UserAction extends ActionSupport implements ModelDriven { privateint id; private UserInfo userInfo =new UserInfo(); private UserService userService; private User user; private List<User> users; @Override public String execute() throws Exception { System.out.println(userInfo.getUsername()); User user =new User(); user.setUsername(userInfo.getUsername()); user.setPassword(userInfo.getPassword()); if (userService.isExistsUser(userInfo.getUsername())) { return"fail"; } userService.add(user); return"success"; } @Override public Object getModel() { returnthis.userInfo; } public String list() { this.users = userService.getAll(); return"list"; } public String load() { this.user = userService.getById(id); return"load"; } public UserService getUserService() { return userService; } @Resource publicvoid setUserService(UserService userService) { this.userService = userService; } public UserInfo getUserInfo() { return userInfo; } publicvoid setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public User getUser() { return user; } publicvoid setUser(User user) { this.user = user; } public List<User> getUsers() { return users; } publicvoid setUsers(List<User> users) { this.users = users; } publicint getId() { return id; } publicvoid setId(int id) { this.id = id; } }
UserDao.java
package com.anllin.registration.dao; import java.util.List; import com.anllin.registration.model.User; publicinterface UserDao { publicvoid add(User user); publicvoid delete(User user); publicvoid update(User user); public User getById(int id); public List<User> getAll(); publicboolean isExistsUser(String username); }
UserDaoImpl.java
package com.anllin.registration.dao.impl; import java.util.List; import org.springframework.stereotype.Component; import com.anllin.registration.dao.UserDao; import com.anllin.registration.model.User; @Component("userDao") publicclass UserDaoImpl extends SuperDao implements UserDao { @Override publicvoid add(User user) { this.getHibernateTemplate().save(user); } @Override publicvoid delete(User user) { this.getHibernateTemplate().delete(user); } @SuppressWarnings("unchecked") @Override public List<User> getAll() { return (List<User>)this.getHibernateTemplate().find("from User"); } @Override public User getById(int id) { return (User) this.getHibernateTemplate().load(User.class, id); } @Override publicvoid update(User user) { this.getHibernateTemplate().update(user); } @SuppressWarnings("unchecked") @Override publicboolean isExistsUser(String username) { List<User> u =this.getHibernateTemplate().find( "from User u where u.username='"+ username +"'"); if (u !=null&& u.size() >0) { returntrue; } returnfalse; } }
SuperDao.java
package com.anllin.registration.dao.impl; import javax.annotation.Resource; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; @Component publicclass SuperDao { private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource publicvoid setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } }
User.java
package com.anllin.registration.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity publicclass User { privateint id; private String username; private String password; @Id @GeneratedValue publicint getId() { return id; } publicvoid setId(int id) { this.id = id; } public String getUsername() { return username; } publicvoid setUsername(String username) { this.username = username; } public String getPassword() { return password; } publicvoid setPassword(String password) { this.password = password; } }
UserService.java
package com.anllin.registration.service; import java.util.List; import com.anllin.registration.model.User; publicinterface UserService { publicvoid add(User user); publicvoid delete(User user); publicvoid update(User user); public User getById(int id); public List<User> getAll(); publicboolean isExistsUser(String username); }
UserServiceImpl.java
package com.anllin.registration.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Component; import com.anllin.registration.dao.UserDao; import com.anllin.registration.model.User; import com.anllin.registration.service.UserService; @Component("userService") publicclass UserServiceImpl implements UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } @Resource publicvoid setUserDao(UserDao userDao) { this.userDao = userDao; } @Override publicvoid add(User user) { userDao.add(user); } @Override publicvoid delete(User user) { userDao.delete(user); } @Override public List<User> getAll() { return userDao.getAll(); } @Override public User getById(int id) { return userDao.getById(id); } @Override publicvoid update(User user) { userDao.update(user); } @Override publicboolean isExistsUser(String username) { return userDao.isExistsUser(username); } }
HibernateUtil.java
package com.anllin.registration.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.AnnotationConfiguration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@linkhttp://hibernate.org/42.html }. */ @SuppressWarnings("deprecation") publicclass HibernateUtil { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */privatestatic String CONFIG_FILE_LOCATION ="/hibernate.cfg.xml"; privatestaticfinal ThreadLocal<Session> threadLocal =new ThreadLocal<Session>(); privatestatic Configuration configuration =new AnnotationConfiguration(); privatestatic org.hibernate.SessionFactory sessionFactory; privatestatic String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateUtil() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */publicstatic Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session ==null||!session.isOpen()) { if (sessionFactory ==null) { rebuildSessionFactory(); } session = (sessionFactory !=null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */publicstaticvoid rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */publicstaticvoid closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session !=null) { session.close(); } } /** * return session factory * */publicstatic org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */publicstaticvoid setConfigFile(String configFile) { HibernateUtil.configFile = configFile; sessionFactory =null; } /** * return hibernate configuration * */publicstatic Configuration getConfiguration() { return configuration; } }
UserInfo.java
package com.anllin.registration.vo; publicclass UserInfo { private String username; private String password; private String psssword2; public String getUsername() { return username; } publicvoid setUsername(String username) { this.username = username; } public String getPassword() { return password; } publicvoid setPassword(String password) { this.password = password; } public String getPsssword2() { return psssword2; } publicvoid setPsssword2(String psssword2) { this.psssword2 = psssword2; } }
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"><display-name>User registration</display-name><!-- 把session的关闭延迟到jsp页面显示之后,在配在struts2上面。 --><filter><filter-name>OpenSessionInView</filter-name><filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class></filter><filter-mapping><filter-name>OpenSessionInView</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 使用spring过滤器解决中文乱码问题 --><filter><filter-name>encodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>GBK</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><!-- 使用struts2必须有的配置 --><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><!-- spring 与 struts2 整合时需要的配置 ,实现在action中依赖注入功能--><context-param><param-name>contextConfigLocation</param-name><!-- <param-value>/WEB-INF/daoContext.xml /WEB-INF/applicationContext.xml</param-value>--><param-value>classpath:beans.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener></web-app>
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration><session-factory><property name="hbm2ddl.auto">create</property><property name="dialect">org.hibernate.dialect.MySQL5Dialect</property><property name="connection.url">jdbc:mysql://localhost:3306/test</property><property name="connection.username">root</property><property name="connection.password">123</property><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="myeclipse.connection.profile">mysql5.5-jdbc5.0.8</property><property name="show_sql">true</property><property name="format_sql">true</property><mapping class="com.anllin.registration.model.User"/></session-factory></hibernate-configuration>
register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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>用户注册</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"></head><body><form action="u.action" method="post"> 用户名:<input type="text" name="username" size="20"/><br/> 密 码:<input type="password" name="password" size="20"/><br/> 确认密码:<input type="password" name="psssword2" size="20"/><br/><input type="submit" value="提交"/></form><br></body></html>
error.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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>error</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"></head><body><h1>出错了</h1><br></body></html>
registerFail.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%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>register fail</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"></head><body><h1>register failed.</h1></body></html>
registerSuccess.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@taglib prefix="s" uri="/struts-tags"%><%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>register success</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"></head><body><h1>register sucess!</h1> username: ${userInfo.username }<br/> password: ${userInfo.password }<br/><s:debug></s:debug></body></html>
user.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><%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>error</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"></head><body><s:property value="user.username"/><br/><s:property value="user.password"/><br/><s:debug></s:debug></body></html>
userlist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><%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>error</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><style type="text/css"> table { margin:0 auto; width:60%; border-collapse: collapse;} table tr td { border:1px solid black;}</style></head><body><table ><s:iterator value="users"><tr><td><s:property value="username"/></td><td><s:property value="password"/></td></tr></s:iterator></table><s:debug></s:debug></body></html>