基于spring+springmvc+hibernate的maven项目搭建

1.新建一个maven项目

(1)选择工作区间
这里写图片描述

(2)选择maven-archetype-webapp
这里写图片描述

(3)输入Group id(包名的前缀)和Artifact Id(项目名),然后finish
这里写图片描述

(4)完成上面的步骤,项目的目录如下:
这里写图片描述

(5)修改Dynamic Web Module和java的版本
这里写图片描述
(有人可能不理解这个Dynamic Web Module,其实就是:java的web系统有多种类型,比如静态的和动态的,然后动态的java web project要设置dynamic web module,也就是动态网页模型,他必须要和对应的服务器搭配好了才能跑,版本对应如下
dynamic web module 2.4 对应Tomcat 5.5
dynamic web module 2.5 对应Tomcat 6.0
dynamic web module 3.0 对应Tomcat 7.0或更高)

2.配置3个xml文件

web.xml
web.xml主要配置:ContextLoaderListener和DispatcherServer,代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <!-- 配置web.xml,使其具有springmvc特性,主要配置两处,一个是ContextLoaderListener,一个是DispatcherServlet -->

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <!-- 配置ContextLoaderListener表示,该工程要以spring的方式启动。启动时会默认在/WEB-INF目录下查找applicationContext.xml
作为spring容器的配置文件,该文件里可以初始化一些bean -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <filter>
       <filter-name>SpringOpenSessionInViewFilter</filter-name>
       <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
     </filter>
  <filter-mapping>
    <filter-name>SpringOpenSessionInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
    <!-- 字符集过滤器 -->  
    <filter>
        <filter-name>encodingFilter</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>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!-- spring mvc 配置 -->
    <!-- 配置DispatcherServlet表示,该工程将采用springmvc的方式。启动时也会默认在/WEB-INF目录下查找XXX-servlet.xml作为配置文件,
        XXX就是DispatcherServlet的名字,该文件中将配置两项重要的mvc特性:HandlerMapping,负责为DispatcherServlet这个前端控制器的请求查找Controller;
        ViewResolver,负责为DispatcherServlet查找ModelAndView的视图解析器。
        此处使用指定的配置文件spring-mvc.xml -->
    <servlet>
        <servlet-name>contacts</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <!--<param-value>/WEB-INF/classes/spring-mvc-servlet.xml</param-value>-->
            <param-value>classpath*:/spring-mvc.xml</param-value>
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>
    <servlet-mapping>
        <servlet-name>contacts</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>

    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>

applicationContext.xml
配置ContextLoaderListener表示,该工程要以spring的方式启动。启动时会默认在/WEB-INF目录下查找 applicationContext.xml作为spring容器的配置文件,这里可以初始化一些bean,如DataSource等。代码如下:

<?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:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">


    <context:component-scan base-package="ssh.demo"></context:component-scan>

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:database.properties</value>
            </list>

        </property>
    </bean>


    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- Hibernate session factory -->
     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
       <property name="dataSource" ref="dataSource"/>

       <property name="packagesToScan">
         <list>
           <value>ssh.demo</value>
         </list>
       </property>
<!-- 
        <property name="mappingLocations">
          <list>
            <value>classpath:**/*.hbm.xml</value>
          </list>
        </property>
-->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
                <prop key="hibernate.current_session_context_class">
                   org.springframework.orm.hibernate4.SpringSessionContext
                </prop>
                <prop key="hibernate.jdbc.batch_size">50</prop>
                <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
            </props>
        </property>
     </bean>   

    <!-- 实例化jdbcTemplate,同时注入数据源 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
        p:dataSource-ref="dataSource" />

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean> 

    <!-- 事务扫描开始(开启@Tranctional) -->
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> 

</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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"
default-lazy-init="true">

<!-- 此行语句使得resource autowired 等四个注解可以使用 -->
   <context:annotation-config />
   <context:component-scan base-package="ssh.demo" >
   </context:component-scan>  

</beans>

3.添加必须的包依赖到pom.xml

pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>ssh.demo</groupId>
  <artifactId>ssh_Demo</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>ssh_Demo Maven Webapp</name>
  <url>http://maven.apache.org</url>
 <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <!-- <spring.ver>4.1.8.RELEASE</spring.ver> -->
        <spring.ver>4.2.5.RELEASE</spring.ver>
        <hibernate.ver>4.3.11.Final</hibernate.ver>
        <hibernate.common.anno.ver>5.0.0.Final</hibernate.common.anno.ver>
        <hibernate.validator.ver>5.1.3.Final</hibernate.validator.ver>
        <mysql.connector.ver>5.1.36</mysql.connector.ver>
        <aspectj.ver>1.8.6</aspectj.ver>
        <jackson.ver>2.6.4</jackson.ver>
        <commons-file.ver>1.3.1</commons-file.ver>
        <common.csv.ver>1.2</common.csv.ver>        
        <reflection.ver>0.9.10</reflection.ver>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.6.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.ver}</version>
            <scope>test</scope>
        </dependency>
        <!-- json config section -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.ver}</version>
        </dependency>

        <!-- spring configure section -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.ver}</version>
        </dependency>

        <!-- AspectJ -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.ver}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.ver}</version>
        </dependency>

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>${commons-file.ver}</version>
        </dependency>
        <!-- hibernate configure section -->

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-c3p0</artifactId>
            <version>${hibernate.ver}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>${hibernate.common.anno.ver}</version>
        </dependency>

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

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-csv</artifactId>
            <version>${common.csv.ver}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>2.4.3</version>
        </dependency>

    </dependencies>
  <build>
    <finalName>ssh_Demo</finalName>
  </build>
</project>

4.写一个简单的新增功能验证项目

User.java

package ssh.demo.domain;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class User {

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;

    private String name;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "User:[id="+id+",name="+name+"]";
    }
}

UserDao.java

package ssh.demo.dao;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import ssh.demo.domain.User;

@Repository
public class UserDao {

    @Autowired
    private SessionFactory sessionFactory;


    public Session getCurrentSession(){
        return sessionFactory.getCurrentSession();
    }

    public void save(User u){
        getCurrentSession().save(u);
    }

    public User getByName(String name){
        return (User) getCurrentSession().createCriteria(User.class)
                .add(Restrictions.eq("name", name)).uniqueResult();
    }

    public User getById(int id){
        return (User) getCurrentSession().createCriteria(User.class)
                .add(Restrictions.eq("id", id)).uniqueResult();
    }

}

Test.java

package ssh.demo.test;

import java.util.Date;

import javax.annotation.Resource;

import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import ssh.demo.dao.UserDao;
import ssh.demo.domain.User;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class Test {
    @Resource
    private UserDao userDao;



    @org.junit.Test
    public void saveStu(){
        User stu=new User();
        stu.setName("zs");
        userDao.save(stu);
    }
}

测试结果:

这里写图片描述
这里写图片描述

这个项目搭建其实还是挺简单,不过中途会遇到一些问题,耐心点,慢慢研究下,代码就不放到github啦,自己试一次,印象深刻很多的。

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页