天天看點

SSH架構模闆

SSH:

S:SpringMVC —– S:Spring —– H:Hibernate

引入的包:

antlr-.jar
aopalliance.jar
asm-.jar
aspectjrt.jar
aspectjweaver.jar
c3p0-.jar
cglib-.jar
classmate-.jar
commons-codec-.jar
commons-dbcp2-.jar
commons-dbutils-.jar
commons-fileupload-.jar
commons-io-.jar
commons-logging-.jar
commons-pool2-.jar
dom4j-.jar
hibernate-commons-annotations-.Final.jar
hibernate-core-.Final.jar
hibernate-envers-.Final.jar
hibernate-jpa--api-.Final.jar
hibernate-jpamodelgen-.Final.jar
jandex-.Final.jar
javassist--GA.jar
jboss-logging-.Final.jar
jboss-transaction-api_1_spec-.Final.jar
jsp-api.jar
jstl-.jar
mysql-connector-java--bin.jar
servlet-api.jar
spring-aop-.RELEASE.jar
spring-beans-.RELEASE.jar
spring-context-.RELEASE.jar
spring-core-.RELEASE.jar
spring-expression-.RELEASE.jar
spring-jdbc-.RELEASE.jar
spring-orm-.RELEASE.jar
spring-tx-.RELEASE.jar
spring-web-.RELEASE.jar
spring-webmvc-.RELEASE.jar
           

配置檔案:

web.xml
<!-- Spring 相關配置 -->
    <!-- needed for ContextLoaderListener -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/config/bean-*.xml</param-value>
    </context-param>
    <!-- Bootstraps the root web application context before servlet initialization -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Spring MVC -->
    <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
           
bean-base.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--将Hibernate中的連接配接資料庫的相關資訊配置到Spring中來 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="acquireIncrement" value="2"></property>
        <property name="maxPoolSize" value="100"></property>
        <property name="minPoolSize" value="2"></property>
        <property name="maxStatements" value="100"></property>
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///test01"></property>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
    <!--Spring和Hibernate整合的關鍵點是SessionFactory的建立問題 -->
    <bean id="sessionFactory"  class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!--下面我要将hibernate的配置檔案寫到這個裡面來-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="current_session_context_class">thread</prop>
            </props>
        </property>
        <!--編寫hibernate的映射配置-->
        <property name="mappingDirectoryLocations">
            <list>
                 <!--配置mapping映射檔案的根路徑就好了-->
            <value>classpath:com/wc/hrm/pojo</value>
            </list> 
        </property>
    </bean>
   <!--配置aop的掃描-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
           
spring-mvc.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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--配置的是檔案上傳的類  前面的檔案名字必須是 multipartResolver   别的名字好像不行-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <!-- 配置視圖解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean> 
     <!--配置IOC/DI的掃描器-->
   <context:component-scan base-package="com.wc.hrm">
    </context:component-scan>
    <!-- 設定mvc的注解的驅動 -->
    <mvc:annotation-driven></mvc:annotation-driven> 
    <!--    配置事務 -->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
     <!--應用這個事務-->
     <tx:annotation-driven transaction-manager="txManager"/>
</beans>
           
User.java
/**
 * 實體管理者類
 * @author Administrator
 *
 */
public class User {
    private Integer id;//管理者id
    private String  loginName;//登入名
    private String password;//密碼
    private int status;//狀态
    private String username;//使用者名
    private String createDate;//建立時間
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getLoginName() {
        return loginName;
    }
    public void setLoginName(String loginName) {
        this.loginName = loginName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getCreateDate() {
        return createDate;
    }
    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }
    public User(String loginName, String password, int status, String username) {
        super();
        this.loginName = loginName;
        this.password = password;
        this.status = status;
        this.username = username;
    }
    public User() {
        super();
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", loginName=" + loginName + ", password=" + password + ", status=" + status
                + ", username=" + username + ", createDate=" + createDate + "]";
    }   
}
           
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
 <!--package是否可以省略?
            可以
            省略之後類的名字 編寫全路徑就OK了       
 -->       
 <hibernate-mapping  package="com.wc.hrm.pojo"  default-lazy="false"> 
    <!--一個class就相當于對應了一張表
         name:表示的是我們對應資料庫表的那個對象的名字  這個名字如果上面沒有配置package的話那麼是需要全路徑的
         table:這個标簽是我們的JAVA對象  在資料庫表中對應的這個表名
         abstract:這個用在繼承映射的時候 這個類是否在資料庫對應表的問題
         lazy:是否這個對象支援懶惰形加載 (我們隻有在使用這個資料的時候那麼 才加載這個資料  如果我們不需要使用這個資料的話 那麼就不會加載)
         abstract="true" lazy="true"
         table:是否可以省略?
                        可以的
                        省略之後預設的表明就是實體的名字
    -->
    <class name="User" table="u_user">
       <!--配置的主鍵
          id:是用來配置這個主鍵的(每一個表都有主鍵) 值直接寫我們實體裡面的主鍵屬性 
          column:這個是用來定義這個列的列名的
          type:表示的是目前的這個類中的屬性的資料格式是什麼  這裡可以寫java裡面的類型的全路徑 也可以寫hibernate中支援的資料類型
          column:可以省略 預設的字段就是屬性的名字  
          type:也可以省略:預設的類型和實體的資料類型是一樣的
        -->
        <id name="id" column="ID">
            <generator class="native"></generator>
        </id>
        <!--配置的是普通的列
            property:設定的是普通的列  
            column:列名(目前對象的屬性在資料庫中對應的列名)  可以省略
            lazy:是否支援懶惰性的加載  :也預設值
            not-null:是否可以為null
            unique:是否這個列的值是唯一的
            type:可以省略 預設資料類型和實體中的屬性的類型一直
            length:設定的是長度(有點必須的)-->
        <property name="loginName" column="loginname"></property>
         <property name="password" column="PASSWORD"></property>
          <property name="status" column="STATUS"></property>
           <property name="username"></property>
            <property name="createDate"></property>
    </class>
</hibernate-mapping>
           
IUserDao.java
/**
 * 持久層接口:管理者
 * @author Administrator
 *
 */
public interface IUSerDao {
    /**
     * 增加方法
     * @param user
     * @throws Exception
     */
    public void  insert(User user)throws Exception;
    /**
     * 修改方法
     * @param user
     * @throws Exception
     */
    public void update(User user) throws Exception;
    /**
     * 删除方法
     * @param id
     * @throws Exception
     */
    public void delete(Integer id)throws Exception;
    /**
     *  id查詢方法
     * @param id
     * @return
     * @throws Exception
     */
    public User query(Integer id )throws Exception;
    /**
     * username,status查詢方法
     * @param username
     * @param status
     * @return
     * @throws Exception
     */
    public List<User> query(String  username,Integer status) throws Exception ;
    /**
     * 登入查詢方法
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public User query(String username,String password) throws Exception ;
}
           
UserDao.java
/**
 * 持久層實作:管理者
 * 
 * @author Administrator
 *
 */
@Repository
public class UserDao implements IUSerDao {
    @Autowired
    private SessionFactory sessionFactory = null;
    @Override
    public void insert(User user) throws Exception {
        user.setCreateDate(DateUtils.getDate3());// 設定建立時間(工具類)
        sessionFactory.openSession().save(user);
    }
    @Override
    public void update(User user) throws Exception {
        Session session = sessionFactory.getCurrentSession();
        session.update(user);
    }
    @Override
    @Transactional
    public void delete(Integer id) throws Exception {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("delete from User as u where u.id=:id");
        query.setParameter("id", id);
        query.executeUpdate();
        System.out.println("delete");
    }
    @Override
    public User query(Integer id) throws Exception {
        Session session = sessionFactory.openSession();
        User user = session.get(User.class, id);
        return user;
    }
    @SuppressWarnings("rawtypes")
    @Override
    public User query(String loginname, String password) throws Exception {
        Session session = sessionFactory.openSession();
        System.out.println(loginname);
        System.out.println(password);
        Query query = session.createQuery("select u from User u where u.loginName=:username AND u.password=:password");
        query.setParameter("username", loginname);
        query.setParameter("password", password);
        User user = null;
        if (query.list().size() != ) {
            user = (User) query.list().get();
        }
        return user;
    }
    @Override
    public List<User> query(String username, Integer status) throws Exception {
        Session session = sessionFactory.openSession();
        Query query = null;
        String hql = "select u from User u where 1=1";
        if (username == null || username == "" || username == " ") {
            if (status != null) {
                hql = hql + " AND u.status=:status";
                query = session.createQuery(hql);
                query.setParameter("status", status);
            } else {
                query = session.createQuery(hql);
            }
        } else {
            if (status != null) {
                hql = hql + " AND u.status=:status AND u.username like :username";
                query = session.createQuery(hql);
                query.setParameter("username", "%" + username + "%");
                query.setParameter("status", status);
            } else {
                hql = hql + " AND u.username like :username";
                query = session.createQuery(hql);
                query.setParameter("username", "%" + username + "%");
            }
        }
        return query.list();
    }
}
           
IUserService.java
/**
 * 業務邏輯層接口:管理者
 * @author Administrator
 *
 */
public interface IUserService {
    /**
     * 增加方法
     * @param employee
     * @throws Exception
     */
    public void  insert(User user)throws Exception;
    /**
     * 修改方法
     * @param employee
     * @throws Exception
     */
    public void update(User user) throws Exception;
    /**
     * 删除方法
     * @param employee
     * @throws Exception
     */
    public void delete(Integer id)throws Exception;
    /**
     * 查詢方法
     * @param id
     * @return
     * @throws Exception
     */
    public User query(Integer id )throws Exception;
    /**
     * 查詢方法
     * @return
     * @throws Exception
     */
    public List<User> query(String username,Integer status)throws Exception;
    /**
     * 查詢方法
     * @param username
     * @param password
     * @return
     * @throws Exception
     */
    public User query(String username,String password )throws Exception;
}
           
UserService.java
/**
 * 業務邏輯層實作:管理者
 * @author Administrator
 *
 */
@Service
@Transactional
public class UserService implements IUserService{
    @Autowired
    private IUSerDao userDao=null;
    @Override
    public void insert(User user) throws Exception {
        userDao.insert(user);
    }
    @Override
    public void update(User user) throws Exception {
        userDao.update(user);
    }
    @Override
    public void delete(Integer id) throws Exception {
        if(id!=null) {
            userDao.delete(id);
        }
    }
    @Override
    public User query(Integer id) throws Exception {
        User user=null;
        if(id!=null) {
            user=userDao.query(id);
        }
        return user;
    }
    @Override
    public User query(String loginname, String password) throws Exception {
        User user=userDao.query(loginname,password);
        System.out.println("service"+user);
        return user;
    }
    @Override
    public List<User> query(String username, Integer status) throws Exception {
        List<User> users=userDao.query(username,status);
        return users;
    }
}
           
UserControll.java
/**
 * 控制層:管理者
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/user")
public class UserControll {
    @Resource
    private IUserService userService=null;
    /**
     * 使用者查詢
     * @param username
     * @param status
     * @return
     * @throws Exception
     */
    @RequestMapping("/selectUser.action")
    public ModelAndView selectUser(String  username,Integer status) throws Exception {
        List<User> users=userService.query(username,status);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("user/user");
        modelAndView.addObject("users",users);
        return modelAndView;    
    }   
    /**
     * 添加使用者跳轉
     * @return
     */
    @RequestMapping("/addUser.action")
    public String addUser() {
        return "user/showAddUser";
    }   
    /**
     * 添加使用者送出
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping("/addUserF.action")
    public  ModelAndView addUser(User user) throws Exception {
        userService.insert(user);
        return selectUser(null,null);   
    }   
    /**
     *  修改使用者跳轉
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/updateUser.action")
    public  ModelAndView updateUser(int id) throws Exception {
        User user=userService.query(id);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("user/showUpdateUser");
        modelAndView.addObject("user",user);
        return modelAndView;
    }   
    /**
     * 修改使用者送出
     * @param user
     * @return
     * @throws Exception
     */
    @RequestMapping("/updateUserF.action")
    public ModelAndView updateUser(User user) throws Exception {
        userService.update(user);
        return selectUser(null,null);
    }   
    /**
     * 删除使用者
     * @return
     * @throws Exception 
     */
    @RequestMapping("/removeUser.action")
    public ModelAndView removeUser(int[] ids ) throws Exception {
        for(int i:ids) {
            userService.delete(i);
        }
        return selectUser(null,null);
    }   
}
           

繼續閱讀