1. 程式人生 > >基於註解的簡單SSH保存用戶小案例

基於註解的簡單SSH保存用戶小案例

trac 效果 web.xml配置 配置記錄 .org rate enc bean def

需求:搭建SSH框架環境,使用註解進行相關的註入(實體類的註解,AOP註解、DI註入),保存用戶信息

效果:

技術分享圖片

一、導依賴包

技術分享圖片

二、項目的目錄結構

技術分享圖片

三、web.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
5 version="3.1"> 6 7 <!--懶加載過濾器,解決懶加載問題--> 8 <filter> 9 <filter-name>openSession</filter-name> 10 <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class> 11 </filter> 12 <
filter-mapping> 13 <filter-name>openSession</filter-name> 14 <url-pattern>*.action</url-pattern> 15 </filter-mapping> 16 17 <!-- struts2的前端控制器 --> 18 <filter> 19 <filter-name>struts</filter-name> 20 <
filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 21 </filter> 22 <filter-mapping> 23 <filter-name>struts</filter-name> 24 <url-pattern>/*</url-pattern> 25 </filter-mapping> 26 27 <!-- spring 創建監聽器 --> 28 <listener> 29 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 30 </listener> 31 32 <context-param> 33 <param-name>contextConfigLocation</param-name> 34 <param-value>classpath:applicationContext.xml</param-value> 35 </context-param> 36 37 </web-app>

四、applicationContext.xml配置

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:tx="http://www.springframework.org/schema/tx"
 5        xmlns:contex="http://www.springframework.org/schema/context"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/tx
 9         http://www.springframework.org/schema/tx/spring-tx.xsd
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context.xsd">
12 
13     <!-- 打開註解掃描開關 -->
14     <contex:component-scan base-package="com.pri"/>
15 
16     <!-- 以下是屬於hibernate的配置 -->
17     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
18         <property name="driverClass" value="com.mysql.jdbc.Driver"/>
19         <property name="jdbcUrl" value="jdbc:mysql:///ssh_demo1?useSSL=false"/>
20         <property name="user" value="root"/>
21         <property name="password" value=""/>
22     </bean>
23 
24     <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
25         <!--1、核心配置-->
26         <property name="dataSource" ref="dataSource"/>
27 
28         <!-- 2、可選配置-->
29         <property name="hibernateProperties">
30             <props>
31                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
32                 <prop key="hibernate.show_sql">true</prop>
33                 <prop key="hibernate.format_sql">true</prop>
34                 <prop key="hibernate.hbm2ddl.auto">update</prop>
35             </props>
36         </property>
37         <!-- 3、掃描映射文件 -->
38         <property name="packagesToScan" value="com.pri.domain"></property>
39     </bean>
40 
41     <!--開啟事務控制-->
42     <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
43         <property name="sessionFactory" ref="sessionFactory"></property>
44     </bean>
45     <tx:annotation-driven transaction-manager= "transactionManager"/>
46 </beans>

五、log4j.properties配置

#設置日誌記錄到控制臺的方式
log4j.appender.std=org.apache.log4j.ConsoleAppender
#out以黑色字體輸出,err以紅色字體輸出
log4j.appender.std.Target=System.err
log4j.appender.std.layout=org.apache.log4j.PatternLayout
log4j.appender.std.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
#設置日誌記錄到文件的方式
log4j.appender.file=org.apache.log4j.FileAppender
#日誌文件路徑文件名
log4j.appender.file.File=mylog.log
#日誌輸出的格式
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
#日誌輸出的級別,以及配置記錄方案,級別:error > warn > info>debug>trace
log4j.rootLogger=info, std, file    

六、頁面代碼

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h3>添加客戶</h3>
  <form action="${ pageContext.request.contextPath }/customerAction_save" method="post">
      姓名:<input type="text" name="name" /><br/>
      年齡:<input type="text" name="age" /><br/>
      <input type="submit" value="提交"/><br/>
  </form>
  </body>
</html>

success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首頁</title>
</head>
<body>
    <h1>保存成功!</h1>
</body>
</html>

七、實體層代碼

 1 package com.pri.domain;
 2 
 3 import javax.persistence.*;
 4 
 5 
 6 @Entity
 7 @Table(name = "customer")
 8 public class Customer {
 9     @Id
10     @Column(name = "userId")
11     @GeneratedValue(strategy = GenerationType.IDENTITY)
12     private Integer userId;
13 
14     @Column(name = "name")
15     private String name;
16     @Column(name = "age")
17     private Integer age;
18 
19     public Integer getUserId() {return userId; }
20 
21     public void setUserId(Integer userId) {this.userId = userId;}
22 
23     public String getName() {return name;}
24 
25     public void setName(String name) {this.name = name;}
26 
27     public Integer getAge() {return age;}
28 
29     public void setAge(Integer age) {this.age = age;}
30 }

八、action層代碼

 1 package com.pri.action;
 2 
 3 import com.pri.domain.Customer;
 4 import com.pri.service.CustomerService;
 5 import com.opensymphony.xwork2.ActionSupport;
 6 import com.opensymphony.xwork2.ModelDriven;
 7 import org.apache.struts2.convention.annotation.Action;
 8 import org.apache.struts2.convention.annotation.Namespace;
 9 import org.apache.struts2.convention.annotation.ParentPackage;
10 import org.apache.struts2.convention.annotation.Result;
11 import org.springframework.context.annotation.Scope;
12 import org.springframework.stereotype.Controller;
13 import javax.annotation.Resource;
14 
15 
16 @Controller("customerAction")
17 @ParentPackage(value = "struts-default")
18 @Scope("prototype")
19 @Namespace(value = "/")
20 public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{
21 
22     private Customer customer;
23 
24     @Resource(name = "customerService")
25     private CustomerService customerService;
26 
27     @Override
28     public Customer getModel() {
29         if (customer == null ){
30             customer = new Customer();
31         }
32         return customer;
33     }
34 
35     @Action(value = "customerAction_save",
36             results = {@Result(name = SUCCESS,type = "redirect",location = "/success.jsp")})
37     public String save(){
38         customerService.save(customer);
39         return SUCCESS;
40     }
41 }

九、service層代碼

package com.pri.service;

import com.pri.domain.Customer;

public interface CustomerService {
    void save(Customer user);
}
//=======================================
package com.pri.service.impl;

import com.pri.domain.Customer;
import com.pri.dao.CustomerDao;
import com.pri.service.CustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("customerService")
@Transactional
public class CustomerServiceImpl implements CustomerService {

    @Resource(name = "customerDao")
    private CustomerDao customerDao;

    @Override
    public void save(Customer customer) {
        customerDao.save(customer);
    }
}

十、dao層代碼

package com.pri.dao;

import com.pri.domain.Customer;

public interface CustomerDao {
    void save(Customer customer);
}

//==================================================================
package com.pri.dao.impl; import org.hibernate.SessionFactory; import org.springframework.orm.hibernate5.support.HibernateDaoSupport; import org.springframework.stereotype.Component; import javax.annotation.Resource; @Component("myHibernateDaoSupport") public class MyHibernateDaoSupport extends HibernateDaoSupport { @Resource(name = "sessionFactory") public void setSuperSessionFactory(SessionFactory sessionFactory){ super.setSessionFactory(sessionFactory); } } //================================================= package com.pri.dao.impl; import com.pri.dao.CustomerDao; import com.pri.domain.Customer; import org.springframework.stereotype.Repository; @Repository("customerDao") public class CustomerDaoImpl extends MyHibernateDaoSupport implements CustomerDao { @Override public void save(Customer customer) { getHibernateTemplate().save(customer); } }

十一、Spring Beans Dependencies

技術分享圖片

基於註解的簡單SSH保存用戶小案例