转载

idea中搭建ssm整合框架(超详细哦)

自从进入一家游戏公司以后,就抛弃了eclipse转战于idea,刚开始一直很不习惯,但是用了一周以后,在打开eclipse的时候,有一种想卸载掉的冲动,好吧,我是觉得idea比eclipse好用,关于它们的战争我们就不讨论了,下面介绍一下idea中怎么搭建ssm基于maven的整合框架吧。

作为一个优秀的框架,spring一直横穿整合javaee的世界,在学习javaweb的时候,由原来的servlet学习到spring框架,整个过程的时间大概也有2年了吧,在学校的时候,一直使用ssh(Struts2)这个框架。后来接触springmvc,springboot等,我还是喜欢spring的产品的。尽管它有那么点难懂,

在idea中首先我们建立一个maven项目

如图 idea中搭建ssm整合框架(超详细哦)

next->写上项目名

idea中搭建ssm整合框架(超详细哦)

继续下一步

idea中搭建ssm整合框架(超详细哦)

这个地方一定要添加一个 archetypeversion=release

创建完项目后创建对应的文件夹

源码路径,资源路径,webapp路径等如图所示

idea中搭建ssm整合框架(超详细哦)

创建完相应 的文件夹后然后点击右上角

idea中搭建ssm整合框架(超详细哦)

打开之后选择 modules添加spring,web等

idea中搭建ssm整合框架(超详细哦)

然后在添加war包,将项目打包成war。

idea中搭建ssm整合框架(超详细哦)

到此,有关界面上的操作就是这样了,然后来看整合文件了。

首先我们在resources文件加下创建一个spring子文件夹用于添加配置 如图所示

idea中搭建ssm整合框架(超详细哦)

在这里首先把jar引进来,由于项目是通过maven管理的,所以只要添加pom文件就可以了。

pom.xml

<?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>com.twjitm.web</groupId>
    <artifactId>twjitm</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
   <dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.3.9.RELEASE</version>
    </dependency>
       <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-core</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>

       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-beans</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-context</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-jdbc</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-tx</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-web</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>
       <dependency>
           <groupId>org.springframework</groupId>
           <artifactId>spring-test</artifactId>
           <version>4.3.9.RELEASE</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
       <dependency>
           <groupId>org.springframework.data</groupId>
           <artifactId>spring-data-redis</artifactId>
           <version>1.7.2.RELEASE</version>
       </dependency>


       <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis</artifactId>
           <version>3.3.0</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.38</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
       <dependency>
           <groupId>redis.clients</groupId>
           <artifactId>jedis</artifactId>
           <version>2.9.0</version>
       </dependency>


       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-core</artifactId>
           <version>2.8.5</version>
       </dependency>
       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-databind</artifactId>
           <version>2.8.5</version>
       </dependency>
       <dependency>
           <groupId>com.fasterxml.jackson.core</groupId>
           <artifactId>jackson-annotations</artifactId>
           <version>2.8.5</version>
       </dependency>

       <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
       <dependency>
           <groupId>commons-fileupload</groupId>
           <artifactId>commons-fileupload</artifactId>
           <version>1.3.1</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
       <dependency>
           <groupId>commons-io</groupId>
           <artifactId>commons-io</artifactId>
           <version>2.4</version>
       </dependency>
       <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
       <dependency>
           <groupId>org.mybatis</groupId>
           <artifactId>mybatis-spring</artifactId>
           <version>1.3.1</version>
       </dependency>

       <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
       <dependency>
           <groupId>com.mchange</groupId>
           <artifactId>c3p0</artifactId>
           <version>0.9.5.2</version>
       </dependency>
   </dependencies>

</project>

然后再是添加spring配置文件

正如上图所示:第一个文件

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:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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.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
        http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd">



    <!--自定义拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*.do"/>
            <bean class="com.twjitm.aop.TwjItmInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
    <!-- 切入点 -->

    <!--<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
    <!– spring事物管理 –>
    <tx:attributes>
        <tx:method name="add*" />
        <tx:method name="save*" />
        <tx:method name="Save*" />
        <tx:method name="update*" />
        <tx:method name="modify*" />
        <tx:method name="edit*" />
        <tx:method name="delete*" />
        <tx:method name="remove*" />
        <tx:method name="change*" />
        <tx:method name="repair" />
        <tx:method name="deleteAndRepair" />
        <tx:method name="login*" />
        <tx:method name="get*" propagation="SUPPORTS" />
        <tx:method name="find*" propagation="SUPPORTS" />
        <tx:method name="load*" propagation="SUPPORTS" />
        <tx:method name="search*" propagation="SUPPORTS" />
        <tx:method name="datagrid*" propagation="SUPPORTS" />
        <tx:method name="*" propagation="SUPPORTS" />
    </tx:attributes>
    </tx:advice>

    <aop:config proxy-target-class="true">
        <aop:pointcut id="transactionPointcut" expression="execution(* com.twjitm.*.service.Impl.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
                     advice-ref="transactionAdvice" />
    </aop:config>-->
</beans>

然后是 applicationContext-spring.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: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.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">

    <context:component-scan base-package="com.twjitm.*.*"/>

    <!-- 开启SpringMVC注解模式 -->
    <mvc:annotation-driven/>
    <!-- 静态资源默认servlet配置 -->
    <mvc:default-servlet-handler/>

    <bean name="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter"/> <!-- JSON转换器 -->
            </list>
        </property>
    </bean>
    <!-- 定义跳转的文件的前后缀 ,视图模式配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="order" value="1"/>
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--这里是对静态资源的映射-->
    <mvc:resources mapping="/js/**" location="/js/" />
    <mvc:resources mapping="/css/**" location="/css/" />
    <mvc:resources mapping="/img/**" location="/img/" />

    <!-- 文件上传配置 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="UTF-8"/>
        <!-- 上传文件大小限制为31M,31*1024*1024 -->
        <property name="maxUploadSize" value="32505856"/>
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="4096"/>
    </bean>
</beans>

然后是 applicationContext-mybatis.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: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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">


    <context:component-scan base-package="com.twjitm.*.service" use-default-filters="false"/>
    <!-- 配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc/jdbc.properties"/>


    <!--<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="location">
            <list>
                <value>classpath:jdbc/jdbc.properties</value>
            </list>
        </property>
        <property name="fileEncoding" value="utf-8"></property>
    </bean>-->
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
        <property name="minPoolSize" value="${c3p0.minPoolSize}"/>
        <property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
        <property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
        <property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
    </bean>

    <!-- 配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 扫描model包 使用别名 -->
        <property name="typeAliasesPackage" value="com.twjitm.*.entity"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <property name="configurationProperties">
            <props>
                <prop key="mapUnderscoreToCamelCase">true</prop>
            </props>
        </property>
    </bean>

    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.twjitm.*.dao"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

</beans>

然后是 applicationContext-redis.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.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">

    <context:property-placeholder location="classpath:redis/redis.properties" />

    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />

    </bean>

    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}"
          p:port="${redis.port}"
          p:password="${redis.pass}"
          p:pool-config-ref="poolConfig"/>

    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory"   ref="connectionFactory" />
    </bean>
</beans>

通过这种方式命名的话可以统一进行管理和进入到web.xml中。

jdbc配置文件

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/twjitm?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
#最大连接数
c3p0.maxPoolSize=30000
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2

redis.properties

redis.host=127.0.0.1
redis.port=6379
redis.pass=xx
redis.maxIdle=300
redis.testOnBorrow=true

最后就是关于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">
    <welcome-file-list>
        <welcome-file>jsp/index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext*.xml</param-value>
          <!--  <param-value>classpath:bean/applicationContext.xml</param-value>-->
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext*.xml</param-value>

    </context-param>


    <!-- 编码过滤器 -->
    <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监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 防止spring内存溢出监听器,比如quartz -->
    <listener>
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
    </listener>
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>
</web-app>

到这整合搭建到是完成了,我们编写一个测试类进行测试

在数据库中执行sql脚本:

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  `email` varchar(255) NOT NULL COMMENT '用户邮箱',
  `password` varchar(255) NOT NULL COMMENT '用户密码',
  `username` varchar(255) NOT NULL COMMENT '用户昵称',
  `role` varchar(255) NOT NULL COMMENT '用户身份',
  `status` int(1) NOT NULL COMMENT '用户状态',
  `regTime` datetime NOT NULL COMMENT '注册时间',
  `regIp` varchar(255) NOT NULL COMMENT '注册IP',
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'xxx', 'xxxxx', 'xxxxx', 'root', '0', '2017-03-28 09:40:31', '127.0.0.1');
SET FOREIGN_KEY_CHECKS=1;

获得一张表,然后编写mapper映射文件

user.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- 设置为IUserDao接口方法提供sql语句配置 -->
<mapper namespace="com.twjitm.user.dao.IUserDao">
<resultMap id="userList" type="com.twjitm.user.entity.User">

<id column="id" property="id" ></id>
    <id column="email" property="email" ></id>
    <id column="password" property="password" ></id>
    <id column="username" property="username" ></id>
    <id column="role" property="role" ></id>
    <id column="status" property="status" ></id>
    <id column="regTime" property="regTime" ></id>
    <id column="regIp" property="regIp" ></id>
</resultMap>
    <select id="getAllUser" resultMap="userList">
        SELECT * FROM user
    </select>

</mapper>

再dao中创建一个方法,如代码所示

package com.twjitm.user.dao;

import com.twjitm.user.entity.User;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Administrator on 2017/8/26.
 */
@Repository
public interface IUserDao {
    public List<User> getAllUser();
}
idea中搭建ssm整合框架(超详细哦)

注意这个地方和ssh不一样的是,dao中只有接口的定义,没有实现。在接口上添加repository注解。

然后添加service层,如代码所示

package com.twjitm.user.service;

import com.twjitm.user.entity.User;

import java.util.List;

/**
 * Created by twjitm on 2017/8/26.
 */
public interface IUserService {

    public List<User>  getUser();
 }

实现类

idea中搭建ssm整合框架(超详细哦)
package com.twjitm.user.service.Impl;

import com.twjitm.user.dao.IUserDao;
import com.twjitm.user.entity.User;
import com.twjitm.user.service.IUserService;
import org.springframework.stereotype.Service;

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

/**
 * Created by Administrator on 2017/8/26.
 */
@Service("userService")
public class UserServiceImpl implements IUserService{
    @Resource
    private IUserDao userDao;
    public List<User> getUser() {
        return userDao.getAllUser();
    }
}

然后写一个controller了,如图所示

idea中搭建ssm整合框架(超详细哦)

UserController.java

package com.twjitm.user.controller;

import com.twjitm.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * Created by Administrator on 2017/8/26.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
  public IUserService userService;
    @RequestMapping("info")
    @ResponseBody
    public List userInfor(){
        System.out.println("----------------------------------------------");
        System.out.println( userService.getUser().size());
        return userService.getUser();
    }
}

最后就是发布项目了添加tomcat,点击右上角的小图标

idea中搭建ssm整合框架(超详细哦)

然后点击+ 找到local

idea中搭建ssm整合框架(超详细哦)

然后进行配置,把打好的war包添加到tomcat中

idea中搭建ssm整合框架(超详细哦)

然后运行tomcat,若是看到successful等字样就是运行成功了,

idea中搭建ssm整合框架(超详细哦) 然后在浏览器中运行 idea中搭建ssm整合框架(超详细哦)

简单的环境搭建就是这样,各位研究吧

原文  http://blog.csdn.net/baidu_23086307/article/details/77602778
正文到此结束
Loading...