SSH使用总结(annotation配置方式)
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" 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" 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" ref="sessionFactory"></property> </bean> --></beans>
?
jdbc.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, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%nlog4j.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")public class UserAction extends ActionSupport implements ModelDriven{ private int 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() { return this.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 public void setUserService(UserService userService) { this.userService = userService; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public int getId() { return id; } public void setId(int id) { this.id = id; }}
?
UserDao.java
package com.anllin.registration.dao;import java.util.List;import com.anllin.registration.model.User;public interface UserDao{ public void add(User user); public void delete(User user); public void update(User user); public User getById(int id); public List<User> getAll(); public boolean 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")public class UserDaoImpl extends SuperDao implements UserDao{ @Override public void add(User user) { this.getHibernateTemplate().save(user); } @Override public void 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 public void update(User user) { this.getHibernateTemplate().update(user); } @SuppressWarnings("unchecked") @Override public boolean isExistsUser(String username) { List<User> u = this.getHibernateTemplate().find( "from User u where u.username='" + username + "'"); if (u != null && u.size() > 0) { return true; } return false; }}
?
SuperDao.java
package com.anllin.registration.dao.impl;import javax.annotation.Resource;import org.springframework.orm.hibernate3.HibernateTemplate;import org.springframework.stereotype.Component;@Componentpublic class SuperDao{ private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource public void 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;@Entitypublic class User{ private int id; private String username; private String password; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
?
UserService.java
package com.anllin.registration.service;import java.util.List;import com.anllin.registration.model.User;public interface UserService{ public void add(User user); public void delete(User user); public void update(User user); public User getById(int id); public List<User> getAll(); public boolean 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")public class UserServiceImpl implements UserService{ private UserDao userDao; public UserDao getUserDao() { return userDao; } @Resource public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void add(User user) { userDao.add(user); } @Override public void 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 public void update(User user) { userDao.update(user); } @Override public boolean 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 {@link http://hibernate.org/42.html }. */@SuppressWarnings("deprecation")public class 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. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new AnnotationConfiguration(); private static org.hibernate.SessionFactory sessionFactory; private static 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 */ public static 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 * */ public static void 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 */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateUtil.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; }}
?
UserInfo.java
package com.anllin.registration.vo;public class UserInfo{ private String username; private String password; private String psssword2; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPsssword2() { return psssword2; } public void 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>