关闭

搭建基于注解方式的SSH项目框架

标签: ssh数据库连接池框架注解SSH
2852人阅读 评论(2) 收藏 举报
分类:

搭建基于注解方式的SSH项目框架

1. 项目目录以及数据表结构

2. 准备jar

下面是我开发项目准备的jar包,可能有一些是项目依赖的,例如其中的druid-1.0.13.jarftplet-api-1.0.6.jar ftpserver-core-1.0.6.jarjunit-4.1.1.jarslf4j-api-1.7.12这几个包就是根据需要添加的,分别是阿里巴巴开源数据库连接池、两个ftp文件服务器、单元测试以及slf4j用于log跟踪记录数据库操作信息,其他的都是SSH中的jar包,到百度共享下载下图中的所有包。

(jar包下载 链接: http://pan.baidu.com/s/1pJ42207 提取密码: c5yh)

 

3. 配置struts2

配置代码如下(所有的配置属性都可以在struts2-core-×××.jar包中org.apache.struts2下的default.properties中找到)

struts.xml

<?xml version="1.0"encoding="UTF-8" ?>

<!DOCTYPE struts PUBLIC

   "-//Apache Software Foundation//DTD StrutsConfiguration 2.3//EN"

   "http://struts.apache.org/dtds/struts-2.3.dtd">

 

<struts>

   <constant name="struts.enable.DynamicMethodInvocation"value="false" />

   <constant name="struts.devMode" value="true" />

   <!-- 指定由spring负责action对象的创建 -->

   <constant name="struts.objectFactory" value="spring" />

   <!-- 国际化设置,请求参数为utf-8编码 -->

   <constant name="struts.i18n.encoding" value="utf-8" />

   <!-- 指定被struts2处理的请求后缀类型,如果有多个,用逗号隔开 -->

   <constant name="struts.action.extension" value="action" />

   <!-- 指定上传文件的大小上限 -->

   <constant name="struts.multipart.maxSize" value="209715200" />

   <!-- 当配置文件改动后是否重新加载,生产环境下需要设置为false -->

   <constant name="struts.configuration.xml.reload" value="false" />

   <!-- 是否使用struts2的开发模式,生产环境下需要设置为false -->

   <constant name="struts.devMode" value="false" />

   <!-- 浏览器是否缓存静态内容,生产环境下需要设置为true -->

   <constant name="struts.serve.static.browserCache" value="true" />

   <!-- <includefile="example.xml"/> -->

</struts>


 

 

 

4. 配置Spring+Hibernate

4.1  编写Spring配置文件applicationContext.xml

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:aop="http://www.springframework.org/schema/aop"

    xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:task="http://www.springframework.org/schema/task"

    xsi:schemaLocation="

    http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd

    http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.1.xsd

    http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.1.xsd

   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd

    http://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-4.1.xsd">

   

   <!-- 扫描base-package下的文件,并注册bean,同时激活已注册的bean,就是扫描那些用@Service,@component,@Repositiry标识的那些类 -->

   <context:component-scan base-package="com.mlq.love" />

</beans>


 

 

4.2编写Hibernate配置文件applicationContext-hibernate.xml

首先编写配置文件dbconfig.properties,这样提取出来配置信息可以比较直观的查看和维护

dbconfig.properties

url=jdbc\:mysql\://localhost\:3306/test
driverClassName=com.mysql.jdbc.Driver
username=root
password=centerm
initialSize=10
minIdle=5
maxActive=50
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=100
validationQuery=SELECT'x'
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
maxOpenPreparedStatements=20
removeAbandoned=false
removeAbandonedTimeout=1800
logAbandoned=true

 

 

applicationContext-hibernate.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:aop="http://www.springframework.org/schema/aop"

   xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"

   xmlns:task="http://www.springframework.org/schema/task"

   xsi:schemaLocation="

    http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd

    http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-4.1.xsd

    http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-4.1.xsd

   http://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.1.xsd

    http://www.springframework.org/schema/taskhttp://www.springframework.org/schema/task/spring-task-4.1.xsd">

   <bean id="propertyConfigurer"  

        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  

        <property name="locations">  

            <list>  

                <value>/WEB-INF/classes/dbconfig.properties</value>  

            </list>  

        </property>  

   </bean>  

   

   <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">

      <property name="url" value="${url}"/>
      <!--可以省略这个driveerClassName的指定,因为Druid提供了N个数据库的支持-->
      <property name="driverClassName" value="${driverClassName}" />

      <property name="username" value="${username}"/>

      <property name="password" value="${password}"/>

      

      <!-- 配置初始化大小、最小、最大 -->

      <property name="initialSize" value="${initialSize}" />

      <property name="minIdle" value="${minIdle}"/>

      <property name="maxActive" value="${maxActive}"/>

 

      <!-- 配置获取连接等待超时的时间 -->

      <property name="maxWait" value="${maxWait}"/>

 

      <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->

      <property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis}" />

 

      <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->

      <property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis}" />

      

      <!-- 打开PSCache(PreparedStatementCache),并且指定每个连接上PSCache的大小 -->

      <property name="poolPreparedStatements" value="${poolPreparedStatements}" />

      <property name="maxPoolPreparedStatementPerConnectionSize"value="${maxPoolPreparedStatementPerConnectionSize}"/>

      

      <property name="validationQuery" value="${validationQuery}" />

      <property name="testWhileIdle" value="${testWhileIdle}" />

      <property name="testOnBorrow" value="${testOnBorrow}" />

      <property name="testOnReturn" value="${testOnReturn}" />

   </bean>

   <bean id="sessionFactory"

      class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

      <!-- entity包扫描范围 -->

      <property name="packagesToScan">

         <list>

            <value>com.mlq.love.entity</value>

         </list>

      </property>

      <property name="dataSource" ref="dataSource" />

      <property name="hibernateProperties">

         <props>

            <prop key="hibernate.hbm2ddl.auto">update</prop>

            <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>

            <prop key="hibernate.show_sql">true</prop>

            <prop key="hibernate.format_sql">true</prop>

            <prop key="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>

            <prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>

         </props>

      </property>

   </bean>

   

   <!-- 事务配置 -->

   <bean id="transactionManager"

      class="org.springframework.orm.hibernate4.HibernateTransactionManager">

      <property name="sessionFactory" ref="sessionFactory" />

   </bean>

   

   <!-- 开启注解配置事务 -->

   <tx:annotation-driven transaction-manager="transactionManager" />

</beans>


 

5. 修改web.xml文件

主要是增加Struts2Spring的配置信息

web.xml

<?xml version="1.0"encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaeehttp://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">

   <display-name>SSH搭建(注解)</display-name>

   <welcome-file-list>

      <welcome-file>index.html</welcome-file>

   </welcome-file-list>

  <!-- spring配置文件路径 -->

   <context-param>

      <param-name>contextConfigLocation</param-name>

      <param-value>/WEB-INF/classes/applicationContext*.xml</param-value>

   </context-param>

 

   <!-- spring监听器 -->

   <listener>

      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

   </listener>

 

   <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>

</web-app>

 

 

6. 编写实体类、DAO类、Service类以及Action

User.java

@Entity
@Table(name="user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name="userid")
	private Integer userId;
	@Column(name="username")
	private String userName;
	@Column(name="password")
	private String passWord;
	@Column(name="birthday")
	private Date birthday;
	@Column(name="age")
	private Integer age;
	@Column(name="sex")
	private String sex;
       
        getters setters......
}

 

BaseDao.java

public class BaseDao<T> {
	@Resource(name = "sessionFactory")
    protected SessionFactory sessionFactory;
    
	protected Class<?> entityClass;
	
	public BaseDao()
	{
		ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass();
		entityClass = (Class<?>)type.getActualTypeArguments()[0];
	}
	
    protected Session getSession()
    {
    	return sessionFactory.getCurrentSession();
    }
    
    public Serializable save(T t){
    	return getSession().save(t);
    }
}

UserDao.java

@Repository("userDao")
public class UserDao extends BaseDao<User>{
	@SuppressWarnings("unchecked")
	public User checkUser(User user){
		String hql = "from User where userId = :id and password = :password";
		
		Query query = getSession().createQuery(hql)
						.setParameter("id", user.getUserId())
						.setParameter("password", user.getPassWord());
		
		List<User> userList = (List<User>)query.list();
		if(userList != null && userList.size() > 0){
			System.out.println("wocao");
			return userList.get(0);
		}
		return null;
	}
}

UserService.java

@Service("userService")
public class UserService {
	@Resource
	private UserDao userDao;
	
	public Serializable save(User user){
		return userDao.save(user);
	}
	
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public User checkUser(User user){
		return userDao.checkUser(user);
	}
}

LoginAction.java

 

@Controller("loginAction")
@Scope("prototype")
@Namespace("")
@ParentPackage("struts-default")
public class LoginAction extends ActionSupport implements SessionAware{
	private static final long serialVersionUID = 6473585621724667329L;
	
	@Resource(name = "userService")
	private UserService userService;
	
	private Map<String, Object> session;
	private String id;
	private String password;
	
	@Action
	(
		value="login",
		results =
			{
				@Result(name = "success", location = "/main.jsp"),
				@Result(name = "error", location = "/login.jsp")
			}
	)
	public String login(){
		User user = (User)session.get("user");
		
		if(user == null){
			user = new User();
			user.setUserId(Integer.parseInt(id));
			user.setPassWord(password);
		}
		user = userService.checkUser(user);
		
		if(user == null){
			return "error";
		}else {
			session.put("user", user);
			return "success";
		}
	}

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}

 

7. 测试页面

login.java

<body>
    <form action="login.action" method="post">
	<label>姓名:</label><input name="id" type="text" value="" />
	<label>密碼:</label><input name="password" type="password" value="" />
	<input type="submit" value="登陆" />
    </form>
</body>

 

main.java

<body>
    <label>姓名: ${sessionScope.user.userName}</label>
    <label>出生日期 : ${sessionScope.user.birthday}</label>
    <label id="skill">展示技能</label>
</body>


至此,基于注解方式的SSH框架搭建完成~

 

 

2
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:79530次
    • 积分:1218
    • 等级:
    • 排名:千里之外
    • 原创:37篇
    • 转载:4篇
    • 译文:0篇
    • 评论:115条
    文章分类
    最新评论