读书人

20100102日记 SSH整合之一

发布时间: 2012-09-15 19:09:29 作者: rapoo

20100102日志 SSH整合之一

SSH配置之一14:53 2011-1-2----------------------------在Myeclipse里增加Spring Hibernate struts capabilitiesAdd MyEclipse Spring Hibernate struts and User libraries to project在Myeclipse点击项目右键 再点列表里的Myeclipse 选 Spring Hibernate struts hibernate.hbm.xml1myeclipse - hibernateibm db2(Universal driver)myeclipse-spring (包冲突 只留一个asm2.23 utilcommonslogging)3+webhibernate添加struts2(dojo..)+spring-lib------------------------------------------------创建文件夹 conf   将applicationContext.xml放到conf下                                                    修改applicationContext.xml的在 - web.xml->conf/<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/applicationContext.xml</param-value></context-param>----------------------------------------划分三大框架com.zyl.hiber建包com.zyl.hiber.po逆向工程idetety------------------------------------------------------Users.javacom.zyl.hiber.po写usersname 和password的构造方法 方便测试所有字段toStringequals//添加映射User.hbm.xml到hibernate.hbm.xml//逆向工程的结果import java.util.Date;import java.util.HashSet;import java.util.Set;/** * Users entity. @author MyEclipse Persistence Tools */public class Users implements java.io.Serializable {// Fieldsprivate Long usersid;//---->容易自动生成long改成-->Longprivate String usersname;private String password;private Date regdate;// Constructors/** default constructor */public Users() {}/** full constructor */public Users( String usersname, String password,Date regdate) {this.usersname = usersname;this.password = password;this.regdate = regdate;}// Property accessorspublic Long getUsersid() {return this.usersid;}public void setUsersid(Long usersid) {this.usersid = usersid;}public String getUsersname() {return this.usersname;}public void setUsersname(String usersname) {this.usersname = usersname;}public String getPassword() {return this.password;}public void setPassword(String password) {this.password = password;}public Date getRegdate() {return this.regdate;}public void setRegdate(Date regdate) {this.regdate = regdate;}@Overridepublic String toString() {return "Users [password=" + password + ", regdate=" + regdate+ ", usersid=" + usersid + ", usersname=" + usersname + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result+ ((password == null) ? 0 : password.hashCode());result = prime * result + ((regdate == null) ? 0 : regdate.hashCode());result = prime * result + ((usersid == null) ? 0 : usersid.hashCode());result = prime * result+ ((usersname == null) ? 0 : usersname.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Users other = (Users) obj;if (password == null) {if (other.password != null)return false;} else if (!password.equals(other.password))return false;if (regdate == null) {if (other.regdate != null)return false;} else if (!regdate.equals(other.regdate))return false;if (usersid == null) {if (other.usersid != null)return false;} else if (!usersid.equals(other.usersid))return false;if (usersname == null) {if (other.usersname != null)return false;} else if (!usersname.equals(other.usersname))return false;return true;}}------------------------------------------------------IUsersDAO.javacom.zyl.hiber.dao interface -IUserDAO    public void saveUsers(Users users)throws HibernateException;//saveUsers是写保存用户是后集成的16:33 2011-1-2    public Users findUsersByProperties(String username,String password)throws HibernateException;------------------------------------------------------IUsersDAOImpl.javapackage com.zyl.hiber.daoimpl;import java.util.List;import org.hibernate.HibernateException;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;//编写实现 IUserDAOImplimport com.ibm.db2.jcc.am.u;public class IUsersDAOImpl extends HibernateDaoSupport implements IUsersDAO {public Users findUsersByProperties(String username, String password)throws HibernateException {Users users = new Users(username, null, null);List<Long> queryResult = this.getHibernateTemplate().find("select u.usersid from Users u where u.usersname =? and u.password= ?",new String[] { username, password });if (queryResult != null && queryResult.size() == 1) {users.setUsersid(queryResult.get(0));return users;} else {return users;}}//saveUsers是写保存用户是后集成的16:33 2011-1-2public void saveUsers(Users users) throws HibernateException {this.getHibernateTemplate().save(users);}}-------------------------------------------------------beans-dao.xml选 Schema http://www.springframework.org/schema/beans/spring-bean2.5.xsdroot elements 选beans 不要Prefix p <bean id="usersDao" });}@AfterClasspublic static void tearDownAfterClass() throws Exception {beanFactory = null;}@Beforepublic void setUp() throws Exception {usersDao = (IUsersDAO) beanFactory.getBean("usersDao");}@Afterpublic void tearDown() throws Exception {usersDao = null;}@Testpublic void testFindUsersByProperties() {Users users = usersDao.findUsersByProperties("gary1","1234");Assert.assertNotNull("HQL错误",users);Assert.assertNull("逻辑错误",users.getUsersid());System.out.println(users);}}---------------------------------------------------com.zyl.spring----------------------------------------------com.zyl.spring.service-------------------------------------------------------IUsersService.javacom.zyl.spring.serviceinterface-IusersService//业务方法public boolean findUsersByNameAndPass(Users users);public boolean saveUsers(Users users);---------------------------------com.zyl.spring.serviceIpml-------------------------------------------------------IusersServiceImpl.javacom.zyl.spring.serviceIpml实现IusersServiceIusersServiceImpl implemts IUSersService{private  userDaosetter and getter//核心业务方法findUsersBynameAndPass(users){//限制输入时.Users中不应该有ID!=nullusers =usersDao.findByProperties(users)//try catch//查询后User应该有 IDgetuserID}}实现saveUsersimport org.hibernate.HibernateException;public class IUsersServiceImpl implements IUsersService {private IUsersDAO usersDao;public IUsersDAO getUsersDao() {return usersDao;}public void setUsersDao(IUsersDAO usersDao) {this.usersDao = usersDao;}// 核心业务功能public boolean findUsersByNameAndPass(Users users) {if (users == null)return false;// 限制输入时,Users中不应该有IDif (users.getUsersid() != null)return false;try {users = usersDao.findUsersByProperties(users.getUsersname(), users.getPassword());} catch (HibernateException e) {e.printStackTrace();return false;}// 查询后User应该有IDif (users.getUsersid() != null)return true;elsereturn false;}public boolean saveUsers(Users users) {boolean isSaved = false;if (null == users)return false;if (null != users.getUsersid())return false;try {usersDao.saveUsers(users);isSaved = true;} catch (Exception e) {e.printStackTrace();isSaved = false;}return isSaved;}}---------------------------------com.zyl.spring.serviceIpml.test-------------------------------------------------------IusersServiceImplTestCase//测试核心业务private IUserService@beforesetup从bean中取 Usersservice对象TestFindUsersByNameAndIDnew Users("zyl" "123")断言 查询错误 conditionssyso conditionspublic class IUsersServiceImplTestCase {private static ApplicationContext beanFactory;private IUsersService usersService;@BeforeClasspublic static void setUpBeforeClass() throws Exception {beanFactory = new ClassPathXmlApplicationContext(new String[] {"conf/applicationContext.xml"});}@AfterClasspublic static void tearDownAfterClass() throws Exception {beanFactory = null;}@Beforepublic void setUp() throws Exception {   usersService = (IUsersService)beanFactory.getBean("usersServiceProxy");}@Afterpublic void tearDown() throws Exception {  usersService = null;}//@Testpublic void testFindUsersByNameAndPass() {Users users = new Users("gary","1234",null);boolean isFound = usersService.findUsersByNameAndPass(users);Assert.assertTrue("数据",isFound);System.out.println(isFound);}@Test public void testSaveUsers(){Users users = new Users("gg","123456",null);boolean isSaved = usersService.saveUsers(users);Assert.assertTrue("插入失败",isSaved);}}-------------------------------------------------------beans-service.xml<bean id="userService" class=IusersServiceImpl><property name="usersDao"><ref>//每一次都是new出来的</property>事物代理(具有增强功能的代理) id userServiceProxy 继承paretent txProxy          代理UserService taget<bean id="usersService" parent="txProxy">  <property name="target" ref="usersService"></property>  <property name="proxyTargetClass" value="false"></property>  <property name="proxyInterfaces">   <list><value>com.zyl.spring.service.IUsersService</value></list>  </property></bean>-------------------------------------------------------applicationContext.xml<!--通过代理工厂配置事物-->id=tx ref="sessionFactory"></property></bean><bean abstract="true" id="txProxy" ref="tx"></property>  <property name="transactionAttributes">    <props>      <prop key="save*">       PROPAGATION_REQUIRED,-Exception      </prop>      <prop key="find.*">       PROPAGATION_REQUIRED,readOnly,-Exception      </prop>    </props>  </property></bean><import resource="beans-dao.xml"/><import resource="beans-service.xml"></import> <import resource="beans-action.xml"></import>----------------------------------------com.zyl.struts集成框架右键dwrdojostruts2-spring Libertycore删除一些包就剩struts spring plug-------------------------------------------------------index.jsp1<%@ taglib uri="/struts-tags" prefix="s" %>2<body>-<s:form action="LoginAtion">-<S:textfield name="users.usersname" 如果国际化用KEY//动态方法调用 !login<S:actionerror<body>    <s:actionerror/>    <s:actionmessage/>    <s:form name="loginForm" action="LoginAction" namespace="/entrance" method="post">     <s:textfield name="users.usersname" label="用户名"></s:textfield>     <s:password name="users.password"  label="密码"></s:password>     <s:submit value="登录"></s:submit>    </s:form>  </body>-------------------------------文件夹jsp-------------------------------------------------------welcome.jsp <s:actionmessage/> 登录成功!<br>-------------------------------------------------------struts.xmlDTD.struts http://struts.apache.org/dtds/struts-2.1.dtdglobal   将login设成全局的在异常前边package name=entrancePck extends全局的异常映射 出现错误 到input视图上 -action"LoginAction" class--result /jsp/welcome---result input---result login<package name="entrancePack" namespace="/entrance" extends="struts-default">    <global-results>     <result name="login">/index.jsp</result>    </global-results>        <global-exception-mappings>      <exception-mapping result="input" exception="java.lang.Exception"></exception-mapping>    </global-exception-mappings>         <action name="LoginAction" method="login">      <result>/jsp/welcome.jsp</result>      <result name="input">/index.jsp</result>         </action>        <action name="LogOutAction" method="logout">      <result name="input">/index.jsp</result>    </action>      </package>-------------------------------------------------------struts.properties(lib包中的-core--default.property-65行 36行  IoC)struts.objectFactory=springstruts.configuration.xml.reload=truestruts.i18n.encode=UTF-8----------------------------------------com.zyl.struts.action-------------------------------------------------------EnterAction.javaEnterAction extends ActionSupportprivate Users usersprivate IUsersService产生settergetter登陆的方法{在session 里面保存一个标记保存登陆的信息ActionContext产生拦截器}退出的方法{使用invalidate对象返回到首页页面}import org.apache.struts2.ServletActionContext;import com.zyl.hiber.po.Users;import com.zyl.spring.service.IUsersService;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionSupport;public class EnterAction  extends ActionSupport{private Users users;private IUsersService usersService;public Users getUsers() {return users;}public void setUsers(Users users) {this.users = users;}public IUsersService getUsersService() {return usersService;}public void setUsersService(IUsersService usersService) {this.usersService = usersService;}public String login(){boolean isFound = usersService.findUsersByNameAndPass(users);if(isFound){ActionContext.getContext().getSession().put("loginUser",users.getUsersname());System.out.println(users.getUsersid());this.addActionMessage("欢迎"+users.getUsersname()+"");return SUCCESS;}else{this.addActionError("用户名密码不正确");return LOGIN;}}public String logout(){ServletActionContext.getRequest().getSession().invalidate();return LOGIN;}}-------------------------------------------------------beans-action.xml在bean容器里面声明你有声明样的对象映射为loginActionbean name loginAction        显示配置 prototype 使Action不是单例模式 是原形为UsersService赋值proxyweb三大核心 servlet 监听器 拦截器 <bean name="loginAction" scope="prototype">   <property name="usersService">    <ref bean="usersServiceProxy"/>   </property> </bean>  <bean name="logoutAction" scope="prototype">   <property name="usersService">     <ref bean="usersServiceProxy"></ref>   </property> </bean>  <bean name="saveUsersAction" scope="prototype">  <property name="usersService">   <ref bean="usersServiceProxy"/>  </property> </bean>-------------------------------------------------------web.xmlfilter ActionCLeanUpFilterDispatcher登陆验证信息 要更新 不是累加延迟加载<listenner><lis-class>ContextLoaderListener老的tomCat要配servlet而不是Listener参数<param-name>configContext<filter><filter-name>ActionContextCleanUp</filter-name><filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class></filter><filter-mapping><filter-name>ActionContextCleanUp</filter-name><url-pattern>/*</url-pattern>    </filter-mapping>    <filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.FilterDispatcher  </filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern>    </filter-mapping><context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:conf/applicationContext.xml</param-value></context-param><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>-------------------------------------------------------表单验证EnterAction-Validation.xmlcom.zyl.struts.actionOpenSympho xwork<validators> <field  <field name="users">    <field-validator type="visitor">      <param name="context">UsersContext</param>      <param name="appendPrefix">true</param>      <message>用户信息:</message>    </field-validator>  </field></validators>----------------------------------------PO中表单验证Users-UserContext-Validation.xml//OpenSymphony Group//XWork Validator 1.0.3//ENhttp://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd"com.zyl.hiber.po短路param trim >true<ognl表达式message>名称长度${minlength}-${maxlength}要配message-validation-cleanup<!--<validators>--><!--  <field name="usersname">--><!--    <field-validator type="requiredstring" short-circuit="true">--><!--      <param name="trim">true</param>--><!--      <message>名称不能为空</message>--><!--    </field-validator>--><!--    <field-validator type="stringlength">--><!--      <param name="trim">true</param>--><!--      <param name="minLength">4</param>--><!--      <param name="maxLength">10</param>--><!--      <message>名称长度${minLength}-${maxLength}之间</message>--><!--    </field-validator>--><!--  </field>--><!--  <field name="password">--><!--    <field-validator type="requiredstring" short-circuit="true">--><!--      <param name="trim">true</param>--><!--      <message>密码不能为空</message>--><!--    </field-validator>--><!--    <field-validator type="stringlength">--><!--      <param name="trim">true</param>--><!--      <param name="minLength">4</param>--><!--      <message>密码长度${minLength}以上</message>--><!--    </field-validator>--><!--  </field>--><!--</validators>-->---------------------------------增加操作-------------------------------------------------------UsersAdminAction.javacom.zyl.struts.actionprivatesaveUsers(){this.message}import com.opensymphony.xwork2.ActionSupport;public class UsersAdminAction extends ActionSupport {private Users users;private IUsersService usersService;public Users getUsers() {return users;}public void setUsers(Users users) {this.users = users;}public IUsersService getUsersService() {return usersService;}public void setUsersService(IUsersService usersService) {this.usersService = usersService;}public String saveUsers(){boolean isSaved = usersService.saveUsers(users);    System.out.println(isSaved);if(isSaved){this.addActionMessage("用户信息保存成功!,请重新登录");return SUCCESS;}else{this.addFieldError("users","用户添加失败!");return INPUT;}}}-------------------------------------------------------AddUsers.jsp    13:53 2011-1-2<%@ taglib uri="/struts-tags" prefix="s" %>    <s:fielderror>      <s:param name="users"></s:param>    </s:fielderror>    <s:form name="usersForm" action="saveUsersAction" namespace="/admin" method="post">     <s:textfield name="users.usersname" label="用户名"></s:textfield>     <s:password name="users.password"  label="密码"></s:password>     <s:submit value="保存"></s:submit>    </s:form>  </body><s:filederror写配置文件 配验证-------------------------------------------------------数据访问对象访问犯法业务功能app.xml事物代理dao配daoservice.xml  业务Action.xml struts 控制对象延迟加载Spring中opensesionInView---------------------------MyEclipse copy qualified namessh/ssh/srccom.zyl.hiber.dao/ssh/src/com/zyl/hiber/dao/IUsersDAO.javacom.zyl.hiber.daoimpl/ssh/src/com/zyl/hiber/daoimpl/IUsersDAOImpl.javacom.zyl.hiber.daoimpl.test/ssh/src/com/zyl/hiber/daoimpl/test/IUsersDAOImplTestCase.javacom.zyl.hiber.po/ssh/src/com/zyl/hiber/po/Users.java/ssh/src/com/zyl/hiber/po/Users-UsersContext-validation.xml/ssh/src/com/zyl/hiber/po/Users.hbm.xmlcom.zyl.spring.service/ssh/src/com/zyl/spring/service/IUsersService.javacom.zyl.spring.serviceimpl/ssh/src/com/zyl/spring/serviceimpl/IUsersServiceImpl.javacom.zyl.spring.serviceimpl.test/ssh/src/com/zyl/spring/serviceimpl/test/IUsersServiceImplTestCase.javacom.zyl.struts.action/ssh/src/com/zyl/struts/action/EnterAction.java/ssh/src/com/zyl/struts/action/UsersAdminAction.java/ssh/src/com/zyl/struts/action/EnterAction-validation.xml/ssh/src/com/zyl/struts/action/UsersAdminAction-validation.xmlcom.zyl.utilconf/ssh/src/log4j.properties/ssh/src/struts.properties/ssh/src/struts.xml/ssh/WebRoot/ssh/WebRoot/jsp/ssh/WebRoot/jsp/addusers.jsp/ssh/WebRoot/jsp/welcome.jsp/ssh/WebRoot/META-INF/ssh/WebRoot/WEB-INF/ssh/WebRoot/index.jsp-----------------------------------------------------USERS表主键USERSIDBIGINT8否USERSNAMEVARCHAR123是PASSWORDVARCHAR255是REGDATETIMESTAMP10是------------------------------------------------------用到的Lib/ssh/WebRoot/WEB-INF/lib/antlr-2.7.6.jar/ssh/WebRoot/WEB-INF/lib/aopalliance.jar/ssh/WebRoot/WEB-INF/lib/asm-2.2.3.jar/ssh/WebRoot/WEB-INF/lib/asm-commons-2.2.3.jar/ssh/WebRoot/WEB-INF/lib/asm-util-2.2.3.jar/ssh/WebRoot/WEB-INF/lib/aspectjlib.jar/ssh/WebRoot/WEB-INF/lib/aspectjrt.jar/ssh/WebRoot/WEB-INF/lib/aspectjweaver.jar/ssh/WebRoot/WEB-INF/lib/cglib-2.2.jar/ssh/WebRoot/WEB-INF/lib/cglib-nodep-2.1_3.jar/ssh/WebRoot/WEB-INF/lib/commons-attributes-api.jar/ssh/WebRoot/WEB-INF/lib/commons-attributes-compiler.jar/ssh/WebRoot/WEB-INF/lib/commons-codec.jar/ssh/WebRoot/WEB-INF/lib/commons-collections-3.1.jar/ssh/WebRoot/WEB-INF/lib/commons-fileupload.jar/ssh/WebRoot/WEB-INF/lib/commons-httpclient.jar/ssh/WebRoot/WEB-INF/lib/commons-io.jar/ssh/WebRoot/WEB-INF/lib/commons-logging.jar/ssh/WebRoot/WEB-INF/lib/db2jcc_license_cu.jar/ssh/WebRoot/WEB-INF/lib/db2jcc.jar/ssh/WebRoot/WEB-INF/lib/dom4j-1.6.1.jar/ssh/WebRoot/WEB-INF/lib/ehcache-1.2.3.jar/ssh/WebRoot/WEB-INF/lib/ejb3-persistence.jar/ssh/WebRoot/WEB-INF/lib/freemarker.jar/ssh/WebRoot/WEB-INF/lib/hibernate-annotations.jar/ssh/WebRoot/WEB-INF/lib/hibernate-commons-annotations.jar/ssh/WebRoot/WEB-INF/lib/hibernate-entitymanager.jar/ssh/WebRoot/WEB-INF/lib/hibernate-validator.jar/ssh/WebRoot/WEB-INF/lib/hibernate3.jar/ssh/WebRoot/WEB-INF/lib/iText-2.1.3.jar/ssh/WebRoot/WEB-INF/lib/jasperreports-2.0.5.jar/ssh/WebRoot/WEB-INF/lib/javassist-3.9.0.GA.jar/ssh/WebRoot/WEB-INF/lib/jta-1.1.jar/ssh/WebRoot/WEB-INF/lib/jxl.jar/ssh/WebRoot/WEB-INF/lib/log4j-1.2.14.jar/ssh/WebRoot/WEB-INF/lib/log4j-1.2.15.jar/ssh/WebRoot/WEB-INF/lib/persistence.jar/ssh/WebRoot/WEB-INF/lib/poi-3.0.1.jar/ssh/WebRoot/WEB-INF/lib/portlet-api.jar/ssh/WebRoot/WEB-INF/lib/slf4j-api-1.5.8.jar/ssh/WebRoot/WEB-INF/lib/slf4j-log4j12-1.5.8.jar/ssh/WebRoot/WEB-INF/lib/spring-agent.jar/ssh/WebRoot/WEB-INF/lib/spring-aop.jar/ssh/WebRoot/WEB-INF/lib/spring-aspects.jar/ssh/WebRoot/WEB-INF/lib/spring-beans.jar/ssh/WebRoot/WEB-INF/lib/spring-context.jar/ssh/WebRoot/WEB-INF/lib/spring-core.jar/ssh/WebRoot/WEB-INF/lib/spring-jdbc.jar/ssh/WebRoot/WEB-INF/lib/spring-orm.jar/ssh/WebRoot/WEB-INF/lib/spring-tomcat-weaver.jar/ssh/WebRoot/WEB-INF/lib/spring-tx.jar/ssh/WebRoot/WEB-INF/lib/spring-web.jar/ssh/WebRoot/WEB-INF/lib/spring-webmvc-portlet.jar/ssh/WebRoot/WEB-INF/lib/spring-webmvc-struts.jar/ssh/WebRoot/WEB-INF/lib/spring-webmvc.jar/ssh/WebRoot/WEB-INF/lib/struts.jar/ssh/WebRoot/WEB-INF/lib/velocity-1.5.jar/ssh/WebRoot/WEB-INF/lib/velocity-tools-view-1.4.jar

读书人网 >软件架构设计

热点推荐