基於註解的簡單SSH儲存使用者小案例

來源:互聯網
上載者:User

基於註解的簡單SSH儲存使用者小案例

需求:搭建SSH架構環境,使用註解進行相關的注入(實體類的註解,AOP註解、DI注入),儲存使用者資訊

效果:

一、導依賴包

二、項目的目錄結構

三、web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">

    <!--懶載入過濾器,解決懶載入問題-->
    <filter>
        <filter-name>openSession</filter-name>
        <filter-class>org.springframework.orm.hibernate5.support.OpenSessionInViewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>openSession</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>

    <!-- struts2的前端控制器 -->
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring 建立監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

</web-app>

四、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:tx="http://www.springframework.org/schema/tx"
      xmlns:contex="http://www.springframework.org/schema/context"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 開啟註解掃描開關 -->
    <contex:component-scan base-package="com.pri"/>

    <!-- 以下是屬於hibernate的配置 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///ssh_demo1?useSSL=false"/>
        <property name="user" value="root"/>
        <property name="password" value=""/>
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <!--1、核心配置-->
        <property name="dataSource" ref="dataSource"/>

        <!-- 2、可選配置-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <!-- 3、掃描對應檔 -->
        <property name="packagesToScan" value="com.pri.domain"></property>
    </bean>

    <!--開啟事務控制-->
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <tx:annotation-driven transaction-manager= "transactionManager"/>
</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>

七、實體層代碼

package com.pri.domain;

import javax.persistence.*;


@Entity
@Table(name = "customer")
public class Customer {
    @Id
    @Column(name = "userId")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer userId;

    @Column(name = "name")
    private String name;
    @Column(name = "age")
    private Integer age;

    public Integer getUserId() {return userId; }

    public void setUserId(Integer userId) {this.userId = userId;}

    public String getName() {return name;}

    public void setName(String name) {this.name = name;}

    public Integer getAge() {return age;}

    public void setAge(Integer age) {this.age = age;}
}

八、action層代碼

package com.pri.action;

import com.pri.domain.Customer;
import com.pri.service.CustomerService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import javax.annotation.Resource;


@Controller("customerAction")
@ParentPackage(value = "struts-default")
@Scope("prototype")
@Namespace(value = "/")
public class CustomerAction extends ActionSupport implements ModelDriven<Customer>{

    private Customer customer;

    @Resource(name = "customerService")
    private CustomerService customerService;

    @Override
    public Customer getModel() {
        if (customer == null ){
            customer = new Customer();
        }
        return customer;
    }

    @Action(value = "customerAction_save",
            results = {@Result(name = SUCCESS,type = "redirect",location = "/success.jsp")})
    public String save(){
        customerService.save(customer);
        return SUCCESS;
    }
}

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

 

本文永久更新連結地址:https://www.bkjia.com/Linux/2018-02/151099.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.