最近自己华了几天的时间,搭了一个ssh的架构,现在写出来。
版本:struts2.0,spring2.6,hibernate3.4
数据库:oracle
1web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>rachel</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/config/spring/applicationContext-persistence.xml /WEB-INF/config/spring/applicationContext-business.xml </param-value> </context-param> <context-param> <param-name>webAppRootKey</param-name> <param-value>rachel.root</param-value> </context-param> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/config/log4j.properties</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.request.RequestContextListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.util.Log4jConfigListener </listener-class> </listener> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <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> <filter> <filter-name>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>Encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
2 jdbc.properties
jdbc.jdbcUrl=jdbc:oracle:thin:@172.16.4.37:1521:xe jdbc.user=exchange_user jdbc.password=exchange_user jdbc.driverClass=oracle.jdbc.driver.OracleDriver jdbc.initialPoolSize=5 jdbc.maxPoolSize=5
3 log4j.properties
### direct log messages to 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 ### direct messages to file log ### log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.File=${capaa2.3.root}/WEB-INF/log/rachel.log log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### set log levels - for more verbose logging change 'info' to 'debug' ### log4j.rootLogger=info,stdout
spring配置文件
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config/> <tx:annotation-driven transaction-manager="transactionManager"/> <context:component-scan base-package="com.mchz.common.business" /> </beans>
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <import resource="applicationContext-propertyConfigurer.xml" /> <!-- c3p0 datasource --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" p:driverClass="${jdbc.driverClass}" p:jdbcUrl="${jdbc.jdbcUrl}" p:user="${jdbc.user}" p:password="${jdbc.password}"> <property name="initialPoolSize" value="${jdbc.initialPoolSize}" /> <property name="maxPoolSize" value="${jdbc.maxPoolSize}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <!-- <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop> <prop key="hibernate.cache.use_second_level_cache">true</prop> <prop key="hibernate.cache.use_query_cache">true</prop> <prop key="hibernate.cache.use_structured_entries">true</prop> <prop key="hibernate.connection.release_mode">auto</prop> --> </props> </property> <property name="packagesToScan" value="com.mchz.common.domain.persistence" /> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
<?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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="ignoreResourceNotFound" value="true"/> <property name="locations"> <list> <value>/WEB-INF/config/jdbc.properties</value> </list> </property> </bean> <!-- bean id="propertyConfigurer" class="org.jasypt.spring.properties.EncryptablePropertyPlaceholderConfigurer"> <constructor-arg ref="configurationEncryptor" /> <property name="locations"> <list> <value>/WEB-INF/config/system.properties</value> <value>/WEB-INF/config/jdbc.properties</value> </list> </property> </bean --> </beans>
struts配置文件
<?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> <include file="struts-default.xml" /> <constant name="struts.enable.DynamicMethodInvocation" value="true" /> <include file="struts-default.xml" /> <package name="default" extends="struts-default"> <interceptors> <interceptor-stack name="s2Stack"> <interceptor-ref name="model-driven" /> <interceptor-ref name="params" /> </interceptor-stack> </interceptors> <action name="user_login" class="com.mchz.common.web.controller.LoginAction"> <result name="input">index.jsp</result> <result name="sucess">sucess.jsp</result> <result name="error">error.jsp</result> <interceptor-ref name="s2Stack" /> </action> <action name="user_reg" class="com.mchz.common.web.controller.LoginAction" method="userReg"> <result name="input">index.jsp</result> <result name="sucess">sucess.jsp</result> <result name="error">error.jsp</result> </action> </package> </struts>
struts.properties
struts.devMode=false struts.xml.reload=true struts.objectFactory = spring struts.objectFactory.spring.autoWire = type
index.jsp
<%@ page language="java" contentType="text/html; charset=GB2312" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!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=ISO-8859-1"> <title>这是一个登录页面</title> </head> <body> <table border="1" align="center" > <s:form validate="true" name="form1" method="post" action="user_login.action"> <tr> <td>用户名</td> <td><s:textfield name="user.userName"></s:textfield></td> </tr> <tr> <td>密码</td> <td><s:password name="user.passWord"></s:password></td> </tr> <tr> <td>修改</td> <td><a href="<s:url action="Login_login.reg"><s:param name="##" value="123"></s:param></s:url>"> 超链接</a></td> </tr> <tr> <td colspan="2"><s:submit>提交</s:submit></td> </tr> </s:form> <hr></hr> </table> </body> </html>
struts的action
import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.interceptor.ServletRequestAware; import org.springframework.beans.factory.annotation.Autowired; import com.mchz.common.dao.Page; import com.mchz.common.business.UserDaoManager; import com.mchz.common.util.CommonInterf; import com.mchz.common.domain.persistence.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public class LoginAction extends ActionSupport implements ModelDriven<User>, ServletRequestAware, CommonInterf { private static final long serialVersionUID = 1L; User user; @Autowired private UserDaoManager userDaoManager; private HttpServletRequest request; @Override public User getModel() { return user; } @Override public void setServletRequest(HttpServletRequest request) { this.request = request; } @SuppressWarnings("unchecked") @Override public String execute() throws Exception { System.out.println("这里执行的是方法一"); List userList = this.userDaoManager.checkLogin(user.getUserName(), user .getPassWord()); if (userList != null) { if (userList.size() == 1) { ActionContext.getContext().getSession().put("userObject", userList); return SUCESS; } else { return ERRORS; } } return ERRORS; }
public String userReg() throws Exception { System.out.println(user.getUserName()); this.userDaoManager.save(user); return SUCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public void validate() { if (user.getUserName() == null || user.getUserName().trim().equals("")) { this.addFieldError("username", "用户名必须输入"); } if (user.getPassWord() == null || user.getPassWord().trim().equals("")) { this.addFieldError("password", "密码必须输入"); } }
import java.util.List; import com.mchz.common.dao.Page; import com.mchz.common.domain.persistence.User; public interface UserDaoManager { public List checkLogin(String username, String password); public void save(User user); public void deleteById(Integer id); public void update(User user); public Page queryByPage(Page page); }
import java.util.Iterator; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mchz.common.business.UserDaoManager; import com.mchz.common.dao.BaseDaoManager; import com.mchz.common.dao.Page; import com.mchz.common.domain.persistence.User; @Service @Transactional public class UserDaoManagerImpl extends BaseDaoManager implements UserDaoManager { @SuppressWarnings("unchecked") @Override public List checkLogin(String username, String password) { List list = getHibernateTemplate().find( "from User where username=? and password=?", new Object[] { username, password });// 这里只是测试代码,会有sql注入问题 return list; } @Override public void deleteById(Integer id) { } @Override public void save(User user) { this.getHibernateTemplate().save(user);// 数据库的默认的时间没有被加上 } @Override public void update(User user) { }
public Page queryByPage(Page page) { page.setTotalCount(getTotalCount(page)); Session session = this.getSession(); Query qlist = session.createQuery("from User"); qlist.setFirstResult(page.getStartNumber()); qlist.setMaxResults(page.getEndNumber()); List list = qlist.list(); page.setItems(list); for (int i = 0; i < list.size(); i++) { User user = (User) list.get(0); System.out.println(user.getUserName()); } return page; } public Integer getTotalCount(Page page) { Session session = this.getSession(); Query q = session.createQuery("select count(*) from User"); Integer totalCount = ((Number) (q.uniqueResult())).intValue(); return totalCount; }
Page.java
package com.mchz.common.dao; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class Page { public static final int DEFAULT_PAGE_SIZE = 10;// 默认每页大小 private Collection<Object> items = new ArrayList<Object>(); private int currentPage = 1; private int totalCount; // 总记录数 private String orderField; // 排序字段 private boolean ascend; // 是否升序 private Map<Object, Object> searchParameters = new HashMap<Object, Object>(); private int pageSize = DEFAULT_PAGE_SIZE; // 每页大小 private boolean paged = true; private int totalPage; public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public Collection<Object> getItems() { return items; } public void setItems(Collection<Object> items) { this.items = items; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } // 设置当前页 public void setCurrentPage(String currentPage) { int tempCurrentPage; if (currentPage == null || "".equals(currentPage) || currentPage.equals("1")) { tempCurrentPage = 1; this.setCurrentPage(tempCurrentPage); } else { try { this.setCurrentPage(Integer.parseInt(currentPage)); } catch (NumberFormatException e) { e.printStackTrace(); } } } public int getTotalCount() { return totalCount; } public void setTotalCount(int count) { this.totalCount = count; } public String getOrderField() { return orderField; } public void setOrderField(String orderField) { this.orderField = orderField; } public boolean isAscend() { return ascend; } public void setAscend(boolean ascend) { this.ascend = ascend; } public Map<Object, Object> getSearchParameters() { return searchParameters; } public void setSearchParameters(Map<Object, Object> searchParameters) { this.searchParameters = searchParameters; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } /*---------- 计算开始和结束位置---------------------------------*/ public int getStartNumber() { return (this.currentPage - 1) * pageSize + 1; } public int getEndNumber() { if (this.currentPage * pageSize > this.totalCount) { return getStartNumber() + this.totalCount % pageSize - 1; } else { return getStartNumber() + pageSize - 1; } } /*--------------/trustuser/precreate.do------------------------------*/ public int getTotalPage() { int totalPage = (totalCount / pageSize); if (totalCount % pageSize != 0) { totalPage++; } return totalPage; } /** --------------计算总页数------------------- */ public int getPreviewPage() { if (this.currentPage == 1) { return this.currentPage; } else { return currentPage - 1; } } public int getNextPage() { if (this.currentPage == getTotalPage()) { return this.currentPage; } else { return currentPage + 1; } } public void addSearchParameter(Object key, Object value) { if (value instanceof String) { String stringValue = (String) value; value = stringValue.trim(); } this.searchParameters.put(key, value); } public boolean isPaged() { return paged; } public void setPaged(boolean paged) { this.paged = paged; } }
public class BaseDaoManager extends HibernateDaoSupport { @Autowired public void setMySessionFactory(SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } }
@Entity @Table(name = "mc$exchange_user") public class User { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_usermanager") @SequenceGenerator(name = "seq_usermanager", sequenceName = "seq_usermanager") private Integer id; private String userName; private String passWord; private Integer roleId; private Date regTime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public Date getRegTime() { return regTime; } public void setRegTime(Date regTime) { this.regTime = regTime; } 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 interface CommonInterf { public static final String ERRORS="error"; public static final String SUCESS="sucess"; public static final String NONE="none"; public String execute()throws Exception; }