使用Idea2019創建ssh項目,Struts2+Spring+Hibernate+Maven整合

源碼下載地址:

鏈接:https://pan.baidu.com/s/1vDbBMgE1rJ9hbeVUoHkvgQ
提取碼:idfe

1、創建項目

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

2、在main文件夾下新建一個java文件夾,設置爲sourceRoot類型

在這裏插入圖片描述

3、在main文件夾下新建一個Resources文件夾,設置爲Resources Root類型

在這裏插入圖片描述

4、導入pom文件的相關依賴

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>ssh</groupId>
  <artifactId>ssh</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>ssh Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
      <!-- spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.0.RELEASE</version>
    </dependency>
    <!-- spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.1.0.RELEASE</version>
    </dependency>
    <!--spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.0.RELEASE</version>
    </dependency>
    <!-- spring-orm -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>5.1.0.RELEASE</version>
    </dependency>
    <!-- aop面向切面依賴的jar包 -->
    <!-- aspectjrt -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.9.1</version>
    </dependency>
    <!-- aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.1</version>
    </dependency>
    <!-- hibernate依賴 -->
    <!-- hibernate核心依賴 -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
      <version>5.2.17.Final</version>
    </dependency>
    <!-- mysql數據庫驅動依賴 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!-- c3p0連接池 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!-- struts2依賴 -->
    <!-- struts2 -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-core</artifactId>
      <version>2.3.35</version>
    </dependency>
    <!-- struts2-spring-plugin整合spring和struts2 -->
    <dependency>
      <groupId>org.apache.struts</groupId>
      <artifactId>struts2-spring-plugin</artifactId>
      <version>2.3.35</version>
    </dependency>
    <!-- servlet api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.1</version>
      <scope>provided</scope>
    </dependency>
    <!-- lombok -->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.0</version>
      <scope>provided</scope>
    </dependency>
    <!-- jstl -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>ssh</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
        </plugin>

        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-war-plugin</artifactId>
          <version>2.1.1</version>
          <configuration>
            <!-- http://maven.apache.org/plugins/maven-war-plugin/ -->
            <packagingExcludes>WEB-INF/web.xml</packagingExcludes>
          </configuration>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <configuration>
            <source>1.6</source>
            <target>1.6</target>
            <encoding>utf-8</encoding>
          </configuration>
        </plugin>
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <configuration>
            <encoding>utf-8</encoding>
          </configuration>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <configuration>
            <includes>
              <include>**/*Tests.java</include>
            </includes>
          </configuration>
        </plugin>

        <plugin>
          <groupId>org.mortbay.jetty</groupId>
          <artifactId>jetty-maven-plugin</artifactId>
          <version>8.1.5.v20120716</version>
          <configuration>
            <systemProperties>
              <systemProperty>
                <name>log4j.configuration</name>
                <value>file:${basedir}/src/main/resources/log4j.properties</value>
              </systemProperty>
              <systemProperty>
                <name>slf4j</name>
                <value>false</value>
              </systemProperty>
            </systemProperties>
            <scanIntervalSeconds>0</scanIntervalSeconds>
            <webAppSourceDirectory>${basedir}/src/main/webapp/</webAppSourceDirectory>
            <webAppConfig>
              <contextPath>/todo</contextPath>
              <descriptor>${basedir}/src/main/webapp/WEB-INF/web.xml</descriptor>
            </webAppConfig>
            <stopKey/>
            <stopPort/>
          </configuration>
          <dependencies>
            <dependency>
              <groupId>log4j</groupId>
              <artifactId>log4j</artifactId>
              <version>1.2.17</version>
            </dependency>
          </dependencies>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
  <repositories>
    <!-- For main Spring releases -->
    <repository>
      <id>org.springframework.maven.release</id>
      <name>Spring Maven Release Repository</name>
      <url>http://maven.springframework.org/release</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>

    <!-- For testing against latest Spring snapshots -->
    <repository>
      <id>org.springframework.maven.snapshot</id>
      <name>Spring Maven Snapshot Repository</name>
      <url>http://maven.springframework.org/snapshot</url>
      <releases>
        <enabled>false</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>

    <!-- For developing against latest Spring milestones -->
    <repository>
      <id>org.springframework.maven.milestone</id>
      <name>Spring Maven Milestone Repository</name>
      <url>http://maven.springframework.org/milestone</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>

    <!-- add JBOSS repository for easy access to Hibernate libraries -->
    <repository>
      <id>JBOSS</id>
      <name>JBoss repository</name>
      <url>https://repository.jboss.org/nexus/content/repositories/releases</url>
    </repository>
    <repository>
      <id>cloudhopper</id>
      <name>Repository for Cloudhopper</name>
      <url>http://maven.cloudhopper.com/repos/third-party/</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>
</project>

5、在Resources文件目錄下創建如下配置文件

1、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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">
    <!-- 引入資源文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 自動掃描與裝配bean-->
    <context:component-scan base-package="dao.*,service.*"/>
    <!--引入註解解析器-->
    <context:annotation-config/>
    <!-- 數據源連接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="minPoolSize" value="${jdbc.minPoolSize}"/>
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
    </bean>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="hibernateProperties">
            <props>
                <!--配置Hibernate的方言-->
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>

                <!--格式化輸出sql語句-->
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.use_sql_comments">false</prop>
            </props>
        </property>
        <!-- 自動掃描實體 -->
        <property name="packagesToScan"  value="entity" />
    </bean>
    <!-- 配置 HibernateTemplate 對象 -->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <!-- 注入 SessionFactory 對象 -->
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <!-- 用註解來實現事務管理 -->
    <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>
    <tx:annotation-driven transaction-manager="txManager"/>
</beans>

2、jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/hibernate?characterEncoding=utf-8&autoReconnect=true&useSSL=false
jdbc.user=root
jdbc.password=root
#連接池中保留的最小連接數
jdbc.minPoolSize=1
#連接池中保留的最大連接數
jdbc.maxPoolSize=20
#初始化連接數
jdbc.initialPoolSize=1

3、struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
        "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
    <!-- 開啓使用開發模式,詳細錯誤提示 -->
    <constant name="struts.devMode" value="true" />
    <!-- 將對象交給spring管理 -->
    <constant name="struts.objectFactory" value="spring" />
    <!-- 指定資源編碼類型 -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 指定每次請求到達,重新加載資源文件 -->
    <constant name="struts.i18n.reload" value="false" />
    <!-- 指定每次配置文件更改後,自動重新加載 -->
    <constant name="struts.configuration.xml.reload" value="false" />
    <!-- 默認後綴名 -->
    <constant name="struts.action.extension" value="action," />
    <!-- 指定上傳文件的大小上限 -->
    <constant name="struts.multipart.maxSize" value="209715200" />
    <!-- 瀏覽器是否緩存靜態內容,生產環境下需要設置爲true -->
    <constant name="struts.serve.static.browserCache" value="true" />
    <!-- 開啓動態方法調用 -->
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <!--package包作用是管理action 通常一個業務模塊 用一個包  在struts中包一定要繼承struts-default包
        還有一個namespace 作爲路徑的一部分 訪問路徑是項目名/命名空間/actionname
        result  name  action處理方法返回值 type  跳轉結果類型 標籤體   指定跳轉的頁面
     包名重複-->
    <package name="xuantest" extends="struts-default">
        <!-- name 訪問路徑   class 存儲的位置   method是 調用Action中的訪問方法-->
        <action name="login" class="action.TestAction" method="login">
            <!--result是返回的跳轉界面-->
            <result name="success">/WEB-INF/jsp/login.jsp</result>
        </action>
        <action name="logincontroller" class="action.TestAction" method="loginconrtoller">
            <!--result是返回的跳轉界面-->
            <result name="success">/WEB-INF/jsp/success.jsp</result>
            <result name="fail">/WEB-INF/jsp/fail.jsp</result>
        </action>
    </package>
</struts>

6、連接數據庫(以MySQL爲例)在連接數據庫之前,需創建好數據庫

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

7、生成持久化類

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

8、完善項目結構,如下圖,代碼在圖下面,根據圖去決定文件放置的位置,也可以下載源碼

在這裏插入圖片描述
1、TestAction

package action;

import entity.TestEntity;
import service.TestService;
import utils.Singleton;

import java.util.Arrays;

/**
 * @author Xuan
 * @date 2019/9/21 9:57
 */
public class TestAction {
    //獲取前臺的id
    private Integer id;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    private TestService testService = (TestService) Singleton.GetApplicationContext().getBean("TestServiceImpl");
    /**
     * 進入登錄界面
     * @return
     */
    public String login(){
        return "success";
    }

    public String loginconrtoller(){
        System.out.println("來過");
        //根據id進行查詢
        TestEntity testEntity =  testService.findById(this.id);
        if (testEntity!=null){
            System.out.println("id是:"+testEntity.getId()+"\t"+"name是:"+testEntity.getName());
            return "success";
        }
        return "fail";
    }

}

2、TestDao

package dao;

import entity.TestEntity;

/**
 * Dao層
 * @author Xuan
 * @date 2019/9/21 9:46
 */
public interface TestDao {
    /**
     * 通過id獲取信息
     * @param id
     * @return
     */
    TestEntity findById(Integer id);
}

3、TestDaoImpl

package dao.impl;

import dao.TestDao;

import entity.TestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * Dao層實現類
 * @author Xuan
 * @date 2019/9/21 9:48
 */
@Repository
public class TestDaoImpl implements TestDao {
    //提供Hibernate模板
    @Autowired
    @Resource
    private HibernateTemplate hibernateTemplate;

    public HibernateTemplate getHibernateTemplate() {
        return hibernateTemplate;
    }

    public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
        this.hibernateTemplate = hibernateTemplate;
    }

    @Override
    public TestEntity findById(Integer id) {
        return this.hibernateTemplate.get(TestEntity.class, id);
    }
}

4、TestEntity

package entity;

import javax.persistence.*;

/**
 * @author Xuan
 * @date 2019/9/21 9:40
 */
@Entity
@Table(name = "test", schema = "hibernate")
public class TestEntity {
    private int id;
    private String name;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

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

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        TestEntity that = (TestEntity) o;

        if (id != that.id) return false;
        if (name != null ? !name.equals(that.name) : that.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}

5、TestService

package service;

import entity.TestEntity;

/**
 * @author Xuan
 * @date 2019/9/21 9:51
 */
public interface TestService {
    /**
     * 通過id獲取信息
     * @param id
     * @return
     */
    TestEntity findById(Integer id);
}

6、TestServiceImpl

package service.impl;

import dao.impl.TestDaoImpl;
import entity.TestEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.TestService;

import javax.annotation.Resource;

/**
 * @author Xuan
 * @date 2019/9/21 9:51
 */
@Service("TestServiceImpl")
public class TestServiceImpl implements TestService {
    @Autowired
    @Resource
    private TestDaoImpl testDao;

    public TestDaoImpl getTestDao() {
        return testDao;
    }

    public void setTestDao(TestDaoImpl testDao) {
        this.testDao = testDao;
    }

    @Override
    public TestEntity findById(Integer id) {
        return testDao.findById(id);
    }
}

7、Singleton (這個在utils包下)

package utils;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * 單列雙檢索模式
 * @author Xuan
 *
 */
public class Singleton {
	/**
	 * 進行訪問控制
	 */
	private Singleton(){
		
	}
	private volatile static ApplicationContext applicationcontext;
	/**
	 * 得到ApplicationContext對象的方法
	 * @return
	 */
	public static ApplicationContext GetApplicationContext(){
		if (applicationcontext==null) {
			synchronized (Singleton.class) {
				if (applicationcontext==null) {
					applicationcontext = new ClassPathXmlApplicationContext("applicationContext.xml");
				}
			}
		}
		return applicationcontext;
	}
}

8、login.jsp

<%--
  Created by IntelliJ IDEA.
  User: Xuan
  Date: 2019/9/21
  Time: 9:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="./logincontroller" method="post">
        請輸入id:<input type="text" name="id"><br>
        <input type="submit">
    </form>
</body>
</html>

9、success.jsp

<%--
  Created by IntelliJ IDEA.
  User: Xuan
  Date: 2019/9/21
  Time: 9:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>成功查詢到數據</h1>
</body>
</html>

10、fail.jsp

<%--
  Created by IntelliJ IDEA.
  User: Xuan
  Date: 2019/9/21
  Time: 9:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>沒有查詢到該數據</h1>
</body>
</html>

11、web.xml (這裏去修改一下web.xml就行了)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <!-- 多個配置文件,使用逗號隔開 -->
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- struts2核心過濾器,過濾所有的請求 -->
  <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>
  <!-- 上下文監聽器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

9、配置tomcat

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

10、啓動tomcat,訪問地址 http://localhost:8080/ssh_war/login

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述

11、遇到困難可以評論(有信必回)小軒微信17382121839。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章