- 准备工作
struts2 | ![]() |
spring3.1 | ![]() |
hibernate4 | ![]() |
数据库,连接池 | ![]() |
2.配置文件
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!--
- Licensed to the Apache Software Foundation (ASF) under one or more
- contributor license agreements. See the NOTICE file distributed with
- this work for additional information regarding copyright ownership.
- The ASF licenses this file to You under the Apache License, Version 2.0
- (the "License"); you may not use this file except in compliance with
- the License. You may obtain a copy of the License at
- http://www.apache.org/licenses/LICENSE-2.0
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- -->
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns="http://java.sun.com/xml/ns/javaee"
- xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
- xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
- metadata-complete="true" version="3.0">
- <!--Spring-->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>
- classpath*:applicationContext*.xml
- classpath*:*Context.xml
- </param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!-- 配置spiring security --><!--
- <filter>
- <filter-name>springSecurityFilterChain</filter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>springSecurityFilterChain</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>-->
- <!-- 配置spiring security结束 -->
- <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>*.action</url-pattern>
- </filter-mapping>
- <!--OpenSessionInViewFilter-->
- <filter>
- <filter-name>openSessionInViewFilter</filter-name>
- <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
- <init-param>
- <param-name>sessionFactoryBeanName</param-name>
- <param-value>sessionFactory</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>openSessionInViewFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
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" />
- <!-- 交给spring管理 -->
- <constant name="struts.objectFactory" value="spring" />
- <!--国际化语言文件编码-->
- <constant name="struts.i18n.encoding" value="UTF-8" />
- <!--国际化-->
- <constant name="struts.custom.i18n.resources" value="i18n.message" />
- <!--加载所有Struts2配置文件-->
- <include file="*/struts.xml"/>
- <package name="default" namespace="/" extends="struts-default">
- <action name="userAction" class="userAction" method="doUser">
- <result>/user.jsp</result>
- </action>
- </package>
- </struts>
Spring 配置文件
- 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:context="http://www.springframework.org/schema/context"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <!-- UT框架Spring Configer -->
- <!-- 配置使用注解 -->
- <context:annotation-config />
- <!-- 自动装在
- <context:component-scan base-package="cn.net.comsys.ut"/>
- -->
- </beans>
- databaseContext.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-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
- <!--加载数据库信息-->
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations" value="classpath:jdbc.properties"/>
- </bean>
- <!--数据源-->
- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="${jdbc.driverClassName}"/>
- <property name="url" value="${jdbc.url}"/>
- <property name="username" value="${jdbc.username}"/>
- <property name="password" value="${jdbc.password}"/>
- <property name="maxActive" value="${dbcp.maxActive}"/>
- <property name="maxIdle" value="${dbcp.maxIdle}"/>
- <property name="maxWait" value="${dbcp.maxWait}"/>
- </bean>
- <!-- SessionFactory-->
- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
- <property name="dataSource" ref="dataSource"/>
- <!--hibernate config-->
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">${hibernate.dialect}</prop>
- <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
- <prop key="connection.characterEncoding">${connection.characterEncoding}</prop>
- <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
- </props>
- </property>
- <!--映射-->
- <property name="annotatedClasses">
- <list>
- <value>cn.net.comsys.ut.model.Users</value>
- <value>cn.net.comsys.ut.model.Roles</value>
- </list>
- </property>
- </bean>
- <!-- 事务管理器 -->
- <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
- <property name="sessionFactory" ref="sessionFactory"/>
- </bean>
- <tx:advice id="txAdvice" transaction-manager="transactionManager">
- <tx:attributes>
- <tx:method name="save*" propagation="REQUIRED" />
- <tx:method name="add*" propagation="REQUIRED" />
- <tx:method name="update*" propagation="REQUIRED" />
- <tx:method name="del*" propagation="REQUIRED" />
- <!--hibernate4必须配置为开启事务 否则 getCurrentSession()获取不到-->
- <tx:method name="find*" propagation="REQUIRED" read-only="true" />
- </tx:attributes>
- </tx:advice>
- <aop:config expose-proxy="true">
- <!-- 只对业务逻辑层实施事务 -->
- <aop:pointcut id="txPointcut" expression="execution(* cn.net.comsys.ut.service.impl.*.*(..))" />
- <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
- </aop:config>
- </beans>
- jdbc.properties
- ######################### Mysql Config ##################################
- jdbc.driverClassName=org.gjt.mm.mysql.Driver
- jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8
- jdbc.username=ut
- jdbc.password=ut
- ######################### Hibernate Config ##################################
- #hibernate信息
- hibernate.dialect=org.hibernate.dialect.MySQLDialect
- hibernate.show_sql=true
- connection.characterEncoding=utf-8
- hibernate.current_session_context_class = org.springframework.orm.hibernate4.SpringSessionContext
- #hibernate.current_session_context_class = thread
- ######################### DBCP Config ##################################
- #配置连接池信息
- dbcp.maxActive=10
- dbcp.maxIdle=3
- dbcp.maxWait=10
- dbcp.whenExhaustedAction=1
- dbcp.validationQuery=select 1 from dual
- dbcp.testOnBorrow=true
- dbcp.testOnReturn=false
- daoContext.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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean id="userDao" class="cn.net.comsys.ut.dao.impl.UserDaoImpl"/>
- </beans>
- serviceContext.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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean id="userService" class="cn.net.comsys.ut.service.impl.UserServiceImpl"/>
- </beans>
- actionContext.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"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <bean id="userAction" class="cn.net.comsys.ut.action.UserAction" scope="prototype"/>
- </beans>
3.编码
- Users.java
- package cn.net.comsys.ut.model;
- import java.io.Serializable;
- import java.util.Set;
- import javax.persistence.Basic;
- import javax.persistence.CascadeType;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.JoinColumn;
- import javax.persistence.JoinTable;
- import javax.persistence.ManyToMany;
- import javax.persistence.Table;
- import javax.persistence.Transient;
- @Entity
- @Table(name="ut_users")
- public class Users implements Serializable{
- /**
- * serialVersionUID
- */
- private static final long serialVersionUID = 1L;
- /**
- * 用户编号
- */
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- private int userId;
- /**
- * 账号
- */
- private String loginId;
- /**
- * 密码
- */
- private String password;
- /**
- * 姓名
- */
- private String name;
- /**
- * 手机
- */
- private String phone;
- /**
- * 邮箱
- */
- private String email;
- /**
- * 身份证
- */
- private String cardId;
- /**
- * 管理员标识
- */
- private int isDepartAdmin;
- /**
- * @aggregation
- * @clientCardinality 1
- * @supplierCardinality 0..*
- */
- @ManyToMany(targetEntity=cn.net.comsys.ut.model.Roles.class,
- cascade={CascadeType.PERSIST, CascadeType.MERGE},
- fetch=FetchType.EAGER)
- @JoinTable(name="ut_user_role",
- joinColumns={@JoinColumn(name="userId")},
- inverseJoinColumns={@JoinColumn(name="roleId")})
- private Set<Roles> role;
- public int getUserId() {
- return userId;
- }
- public void setUserId(int userId) {
- this.userId = userId;
- }
- public String getLoginId() {
- return loginId;
- }
- public void setLoginId(String loginId) {
- this.loginId = loginId;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPhone() {
- return phone;
- }
- public void setPhone(String phone) {
- this.phone = phone;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public String getCardId() {
- return cardId;
- }
- public void setCardId(String cardId) {
- this.cardId = cardId;
- }
- public int getIsDepartAdmin() {
- return isDepartAdmin;
- }
- public void setIsDepartAdmin(int isDepartAdmin) {
- this.isDepartAdmin = isDepartAdmin;
- }
- public Set<Roles> getRole() {
- return role;
- }
- public void setRole(Set<Roles> role) {
- this.role = role;
- }
- }
- Roles.java
- package cn.net.comsys.ut.model;
- import java.io.Serializable;
- import java.util.Set;
- import javax.persistence.Basic;
- import javax.persistence.CascadeType;
- import javax.persistence.Entity;
- import javax.persistence.FetchType;
- import javax.persistence.GeneratedValue;
- import javax.persistence.GenerationType;
- import javax.persistence.Id;
- import javax.persistence.ManyToMany;
- import javax.persistence.Table;
- import javax.persistence.Transient;
- @Entity
- @Table(name="ut_roles")
- public class Roles implements Serializable{
- /**
- * serialVersionUID
- */
- private static final long serialVersionUID = 1L;
- /**
- * 角色编号
- */
- @Id
- @GeneratedValue(strategy=GenerationType.AUTO)
- private int roleId;
- /**
- * 角色名称
- */
- private String roleName;
- /**
- * 状态:禁用(0),激活(1)
- */
- private int status;
- /**
- * 描述
- */
- private String description;
- private int parentId;
- @ManyToMany(
- cascade={CascadeType.PERSIST,CascadeType.MERGE},
- mappedBy="role",
- targetEntity=cn.net.comsys.ut.model.Users.class
- )
- private Set<Users> user;
- public int getRoleId() {
- return roleId;
- }
- public void setRoleId(int roleId) {
- this.roleId = roleId;
- }
- public String getRoleName() {
- return roleName;
- }
- public void setRoleName(String roleName) {
- this.roleName = roleName;
- }
- public int getStatus() {
- return status;
- }
- public void setStatus(int status) {
- this.status = status;
- }
- public String getDescription() {
- return description;
- }
- public void setDescription(String description) {
- this.description = description;
- }
- public int getParentId() {
- return parentId;
- }
- public void setParentId(int parentId) {
- this.parentId = parentId;
- }
- public Set<Users> getUser() {
- return user;
- }
- public void setUser(Set<Users> user) {
- this.user = user;
- }
- }
- DAO层
- IUserDao.java
- package cn.net.comsys.ut.dao.interfaces;
- import java.util.List;
- import cn.net.comsys.ut.model.Users;
- public interface IUserDao{
- public List<Users> findUser();
- public List<Users> findUser(String loginId);
- }
- UserDaoImpl.java
- package cn.net.comsys.ut.dao.impl;
- import java.util.List;
- import javax.annotation.Resource;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import cn.net.comsys.ut.dao.interfaces.IUserDao;
- import cn.net.comsys.ut.model.Users;
- public class UserDaoImpl implements IUserDao {
- @Resource
- private SessionFactory sessionFactory;
- @Override
- public List<Users> findUser() {
- Session session = sessionFactory.getCurrentSession();
- List<Users> userList = session.createQuery("from Users").list();
- return userList;
- }
- @Override
- public List<Users> findUser(String loginId) {
- Session session = sessionFactory.getCurrentSession();
- List<Users> userList = session.createQuery("from Users user where user.loginId= :loginId").setString("loginId", loginId).list();
- return userList;
- }
- }
- 业务层
- IUserService.java
- package cn.net.comsys.ut.service.interfaces;
- import java.util.List;
- import cn.net.comsys.ut.model.Users;
- public interface IUserService {
- public List<Users> findUser();
- public List<Users> findUser(String loginId);
- }
- UserServiceImpl.java
- package cn.net.comsys.ut.service.impl;
- import java.util.List;
- import javax.annotation.Resource;
- import cn.net.comsys.ut.dao.interfaces.IUserDao;
- import cn.net.comsys.ut.model.Users;
- import cn.net.comsys.ut.service.interfaces.IUserService;
- public class UserServiceImpl implements IUserService{
- @Resource
- private IUserDao userDao;
- public List<Users> findUser() {
- List<Users> userList = userDao.findUser();
- return userList;
- }
- @Override
- public List<Users> findUser(String loginId) {
- List<Users> userList = userDao.findUser(loginId);
- return userList;
- }
- }
- action
- UserAction.action
- package cn.net.comsys.ut.action;
- import java.util.List;
- import javax.annotation.Resource;
- import cn.net.comsys.ut.model.Users;
- import cn.net.comsys.ut.service.interfaces.IUserService;
- import com.opensymphony.xwork2.ActionSupport;
- public class UserAction extends ActionSupport {
- /**
- * serialVersionUID
- */
- private static final long serialVersionUID = 1L;
- @Resource
- private IUserService userService;
- private List<Users> userList;
- public String doUser() {
- userList = userService.findUser();
- return SUCCESS;
- }
- public List<Users> getUserList() {
- return userList;
- }
- public void setUserList(List<Users> userList) {
- this.userList = userList;
- }
- }
4.页面
- user.jsp
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- 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=UTF-8">
- <title>用户</title>
- </head>
- <body>
- <table border="1">
- <s:iterator value="userList">
- <tr>
- <td><s:property value="loginId"/> </td>
- <td>
- <s:iterator value="role">
- <s:property value="roleName"/>
- </s:iterator>
- </td>
- </tr>
- </s:iterator>
- </table>
- <s:debug></s:debug>
- </body>
- </html>
5.结果
![](http://dl.iteye.com/upload/attachment/0070/6507/307d474e-f7a5-34d5-9266-9ea3aa3f2a47.png)