使用Idea2019创建ssh(Spring+SpringMVC+Hibernate+Maven整合)项目

源码下载地址

链接:https://pan.baidu.com/s/135Uda58Fm3RJibSWQYHiKQ
提取码:c46g

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>spring+springmvc+hibernate</groupId>
  <artifactId>spring+springmvc+hibernate</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>spring+springmvc+hibernate 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>
        <spring.version>5.1.0.RELEASE</spring.version>
        <slf4j.version>1.6.4</slf4j.version>
        <log4j.version>1.2.17</log4j.version>
        <jackson.version>2.9.8</jackson.version>
        <druid.version>1.0.9</druid.version>
        <mysql.version>5.1.32</mysql.version>
        <jstl.version>1.2</jstl.version>
        <servlet-api.version>2.5</servlet-api.version>
        <jsp-api.version>2.0</jsp-api.version>
        <commons-io.version>1.3.2</commons-io.version>
        <commons-fileupload.version>1.3.1</commons-fileupload.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.0.RELEASE</version>
        </dependency>
        <!-- hibernate依赖 -->
        <!-- hibernate核心依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.17.Final</version>
        </dependency>
        <!-- 日志处理 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </dependency>

        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>

        <!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <!-- io包 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>

        <!-- 文件上传组件 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-fileupload.version}</version>
        </dependency>

        <!-- JSP相关 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>${servlet-api.version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

    <build>
        <finalName>ssm</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <!-- java编译插件 -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.2</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                        <encoding>UTF-8</encoding>
                    </configuration>
                </plugin>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <resources>
            <!--配置资源文件映射 -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>

            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

5、在Resources文件目录下创建如下配置文件

1、applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       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-4.2.xsd
						http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
    <!-- 加载数据库连接信息配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!--druid连接池  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${druid.driver}"/>
        <property name="url" value="${druid.url}"/>
        <property name="username" value="${druid.username}"/>
        <property name="password" value="${druid.password}"/>
    </bean>
    <context:component-scan base-package="xuan.dao.*,xuan.service.*"/>
    <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="xuan.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、springmvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="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/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- SpringMVC使用<mvc:annotation-driven>自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter -->
    <mvc:annotation-driven />
    <!-- 启动注解 -->
    <!-- 配置扫描注解  @Controller -->
    <context:component-scan base-package="xuan.controller"/>
    <!-- 配置静态资源映射 -->
    <!--
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/css/" mapping="/css/**"/>
     <mvc:resources location="/imgs/" mapping="/imgs/**"/>
     <mvc:resources location="/font/" mapping="/font/**"/>
     -->

    <!-- 配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp" />

    </bean>
</beans>

3、db.properties

druid.driver=com.mysql.jdbc.Driver
druid.url=jdbc:mysql://localhost:3306/xuan?characterEncoding=utf-8
druid.username=root
druid.password=root

6、连接数据库(以MySQL为例)在连接数据库之前,需创建好数据库

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

7、生成持久化类

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

8、完善项目结构,如下图,代码在图下面,根据图去决定文件放置的位置,也可以下载源码

在这里插入图片描述
1、TestController

package xuan.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import xuan.entity.TestEntity;
import xuan.service.TestService;
import xuan.utils.Singleton;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 控制层
 * @author Xuan
 * @date 2019/9/17 17:53
 */
@Controller
public class TestController {
    private TestService testService = (TestService) Singleton.GetApplicationContext().getBean("TestServiceImpl");

    /**
     * 获取所有数据并且返回到index.jsp页面
     * @param request
     * @return
     */
    @RequestMapping("/GetAll")
    public String test(HttpServletRequest request){
        System.out.println("来过");
        List<TestEntity> list = testService.GetAll();
        for (TestEntity arr:list) {
            System.out.println(arr.getId());
        }
        request.getSession().setAttribute("xuanlist",list);
        return "show";
    }
}

2、TestDaoImpl

package xuan.dao.impl;

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

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Xuan
 * @date 2019/10/2 3:23
 */
@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 List<TestEntity> GetAll() {
        return this.hibernateTemplate.loadAll(TestEntity.class);
    }
}

3、TestDao

package xuan.dao;

import xuan.entity.TestEntity;

import java.util.List;

/**
 * 映射类接口
 * @author Xuan
 * @date 2019/9/17 17:51
 */
public interface TestDao {
    /**
     * 查询所有列表
     * @return
     */
    List<TestEntity> GetAll();
}

4、TestEntity

package xuan.entity;

import javax.persistence.*;

/**
 * @author Xuan
 * @date 2019/10/2 4:35
 */
@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、TestServiceImpl

package xuan.service.impl;

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

import javax.annotation.Resource;
import java.util.List;

/**
 * Service服务层
 * @author Xuan
 * @date 2019/9/17 17:54
 */
@Service("TestServiceImpl")
public class TestServiceImpl implements TestService {

    @Autowired
    @Resource
    private TestDao testmapper;

    public TestDao getTestmapper() {
        return testmapper;
    }

    public void setTestmapper(TestDao testmapper) {
        this.testmapper = testmapper;
    }

    @Override
    public List<TestEntity> GetAll() {
        return testmapper.GetAll();
    }
}

6、TestService

package xuan.service;

import xuan.entity.TestEntity;

import java.util.List;

/**
 * @author Xuan
 * @date 2019/9/17 17:53
 */
public interface TestService {
    /**
     * 查询所有列表
     * @return
     */
    List<TestEntity> GetAll();
}

7、Singleton

package xuan.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、show.jsp

<%@ page import="java.util.List" %>
<%@ page import="xuan.entity.TestEntity" %><%--
  Created by IntelliJ IDEA.
  User: Xuan
  Date: 2019/9/17
  Time: 19:07
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        List<TestEntity> list = (List<TestEntity>) request.getSession().getAttribute("xuanlist");
        for (TestEntity arr :list) {
            response.getWriter().println("ID是"+arr.getId()+"姓名是:"+arr.getName());
        }
    %>
<%--    <c:forEach var="r" items="${xuanlist}"  varStatus="vs">--%>
<%--        ID是:${r}--%>
<%--        姓名是:${r.name}--%>
<%--    </c:forEach>--%>
</body>
</html>

9、配置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>
  <!-- 指定spring核心配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 处理POST提交乱码问题 -->
  <filter>
    <filter-name>encoding</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>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- spring监听器 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 配置前端控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 指定配置文件位置和名称 如果不设置,默认找/WEB-INF/<servlet-name>-servlet.xml -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

10、配置tomcat

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

11、启动tomcat,访问地址 http://localhost:1314/springspringmvchibernate_war/GetAll

1、我的数据库数据
在这里插入图片描述
2、访问效果
在这里插入图片描述

12、遇到困难可以评论(有信必回)小轩微信17382121839。

发布了47 篇原创文章 · 获赞 57 · 访问量 8864

猜你喜欢

转载自blog.csdn.net/qq_41741884/article/details/101889165
今日推荐