idea搭建SSM框架遇踩的坑(附完整過程)

首先說明這是我一個不熟悉idea和SSM框架的新手小白遇到的坑,適合用idea搭建SSM框架的小夥伴看一看,老鳥就不用看瞭。以下為詳細步驟(傻瓜教程,超級細節)

搭建SSM框架的前提當然是我們已經準備好一下環境

安裝好的intellige idea, java環境,tomcat服務器,maven倉庫,mysql數據庫。

打開idea,new一個project,選擇maven項目,如圖,註意不要選錯成上面那個webapp

點擊next繼續,

groupid一般是公司名,Artfactid一般為項目名,對於idea的項目目錄結構,我自己也沒弄明白,不過這並不影響我們的目標

點擊next繼續,

這裡我們使用自己的本地maven倉庫,註意setting.xml,repository路徑的修改。next繼續,然後finish。

第一次建web maven項目可能需要的時間比較長,耐心等待Maven execution finished。最後的項目結構如下圖

我們需要在main包下面新建一個java根目錄

然後將java目錄改成資源根目錄。

然後再java目錄下創建package  com.ssm 如圖

再在com.ssm下創建一個a.txt文件來分隔路徑 

然後在com.ssm 下創建一下6個package,然後刪除a.txt,最後如下

修改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>自己項目的groupId</groupId>
  <artifactId>自己項目對應</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>同上對應 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <!-- spring版本號 -->
    <spring.version>4.0.2.RELEASE</spring.version>
    <!-- mybatis版本號 -->
    <mybatis.version>3.2.6</mybatis.version>
    <!-- log4j日志文件管理包版本 -->
    <slf4j.version>1.7.7</slf4j.version>
    <log4j.version>1.2.17</log4j.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-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</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-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

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

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- mybatis核心包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- 導入java ee jar 包 -->
    <dependency>
      <groupId>javax</groupId>
      <artifactId>javaee-api</artifactId>
      <version>7.0</version>
    </dependency>
    <!-- 導入Mysql數據庫鏈接jar包 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- 導入dbcp的jar包,用來在applicationContext.xml中配置數據庫 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>1.2.2</version>
    </dependency>
    <!-- JSTL標簽類 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- 日志文件管理包 -->
    <!-- log start -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>


    <!-- 格式化對象,方便輸出日志 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.1.41</version>
    </dependency>


    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <!-- log end -->
    <!-- 映入JSON -->
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.13</version>
    </dependency>
    <!-- 上傳組件包 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.9</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
      <version>4.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-websocket</artifactId>
      <version>4.0.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.3.1</version>
    </dependency>

  </dependencies>

<!– 千萬不要遺漏下面的內容,我就是遺漏瞭,導致deploment的war包裡沒有mapper裡的xml文件 ,ecilpse中則不會出現這個問題–>

  <build>
    <finalName>ProjectMatch</finalName>
    <resources>
      <resource>
        <directory>${basedir}/src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

然後在resources目錄下新建如下4個文件如圖

jdbc.properties 內容如下,標紅的地方都需要按自己數據庫修改,test為數據庫名

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
username=root
password=123456
#定義初始連接數
initialSize=0
#定義最大連接數
maxActive=20
#定義最大空閑
maxIdle=20
#定義最小空閑
minIdle=1
#定義最長等待時間
maxWait=60000

log4j.properties內容如下,可完全復制

#定義LOG輸出級別
log4j.rootLogger=INFO,Console,File
#定義日志輸出目的地為控制臺
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以靈活地指定日志輸出格式,下面一行是指定具體的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到達指定尺寸的時候產生一個新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定輸出目錄
log4j.appender.File.File = logs/ssm.log
#定義文件最大大小
log4j.appender.File.MaxFileSize = 10MB
# 輸出所以日志,如果換成DEBUG表示輸出DEBUG以上級別日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

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.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自動掃描該包,使SpringMVC認為包下用瞭@controller註解的類是控制器 -->
    <context:component-scan base-package="com.qihang.controller" />
    <!--避免IE執行AJAX時,返回JSON出現下載文件 -->
    <bean id="mappingJacksonHttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </bean>

    <import resource="classpath:spring-mybatis.xml" />

    <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的映射 -->
    <bean
            class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 -->
            </list>
        </property>
    </bean>



    <!-- 定義跳轉的文件的前後綴 ,視圖模式配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 這裡的配置我的理解是自動給後面action的方法return的字符串加上前綴和後綴,變成一個 可用的url地址 -->
        <property name="prefix" value="/WEB-INF/page/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置文件上傳,如果沒有使用文件上傳可以不用配置,當然如果不配,那麼配置文件中也不必引入上傳組件包 -->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默認編碼 -->
        <property name="defaultEncoding" value="utf-8" />
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 內存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>

    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <!--<mvc:resources location="/" mapping="/js/**" />-->
    <!--<mvc:resources location="/css/" mapping="/css/**"/>-->
    <!--<mvc:resources location="/fonts/" mapping="/fonts/**"/>-->
    <!--<mvc:resources location="/resources/" mapping="/resources/**"/>-->
</beans>

spring-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: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.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
    <!-- 自動掃描 -->
    <context:component-scan base-package="com.qihang" />
    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化連接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 連接池最大數量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 連接池最大空閑 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 連接池最小空閑 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 獲取連接最大等待時間 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:/mybatis-config.xml"></property>
        <!-- 自動掃描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/qihang/mapper/*.xml"></property>
    </bean>

    <!--&lt;!&ndash; spring和MyBatis完美整合,不需要mybatis的配置映射文件 &ndash;&gt;-->
    <!--<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">-->
        <!--<property name="dataSource" ref="dataSource" />-->
        <!--<property name="configLocation" value="classpath:/mybatis-config.xml"></property>-->
        <!--&lt;!&ndash; 自動掃描mapping.xml文件 &ndash;&gt;-->
        <!--<property name="mapperLocations" value="classpath:com/qihang/mapper/*.xml"></property>-->
    <!--</bean>-->

    <!-- DAO接口所在包名,Spring會自動查找其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.qihang.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事務管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

</beans>

然後項目的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 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <!-- Spring和mybatis的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>

  <!--Log4j配置-->
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>60000</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>

  <!-- 編碼過濾器 -->
  <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監聽器 ApplicationContext 載入 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 防止Spring內存溢出監聽器 -->
  <listener>
    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
  </listener>

  <!-- Spring MVC 核心配置開始 -->
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 可以通過contextConfigLocation來自定義SpringMVC配置文件的位置,如不指定,則默認在WEB-INF目錄下,名稱為[<servlet-name>]-servlet.xml,
         此時文件名必須為[<servlet-name>]-servlet.xml,否則會出錯-->
    <!--以下init-param是自定義SpringMVC的配置文件的位置 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>


  <!-- 攔截設置 -->
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <!-- 此處可以可以配置成*.do,對應struts的後綴習慣 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!-- Spring MVC 核心配置結束 -->

  <!-- 配置SESSION超時,單位是分鐘 -->
  <session-config>
    <session-timeout>15</session-timeout>
  </session-config>

</web-app>

然後我們就可以編寫測試瞭。

在數據庫中創建user表,有兩條記錄,如圖

在pojo包中創建user類

package com.qihang.pojo;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class user {

    @Column(name = "username")
    String username;

    @Column(name = "password")
    String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在dao包中創建userDao接口

package com.qihang.dao;

import com.qihang.pojo.user;

public interface userDao {
    public user selectByUserId(String username);

    public int insertUser(user user);
}

在mapper包中創建userMapping.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">
<mapper namespace="com.qihang.dao.userDao" >
    <resultMap id="BaseResultMap" type="com.qihang.pojo.user" ><!--對應的實體類位置 -->
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
    </resultMap>

    <sql id="userAtr">
        #{username},#{password}
    </sql>

    <select id="selectByUserId" parameterType="String" resultMap="BaseResultMap">
        SELECT
        *
        FROM user
        WHERE 1=1
        <if test="_parameter != null">
            AND username = #{username}
        </if>
    </select>

    <insert id="insertUser" parameterType="java.util.HashMap">
        INSERT  INTO user
        VALUE(<include refid="userAtr"></include>)
    </insert>
</mapper>

在services包中創建userService接口

package com.qihang.services;

import com.qihang.pojo.user;

public interface userService {
    public user querybyUsername(String username);

    public int insert(user user);
}

在servicesImp中創建userServiceImp類

package com.qihang.servicesImp;

import com.qihang.pojo.user;
import com.qihang.services.userService;
import com.qihang.dao.userDao;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service("userServiceImp")
public class userServiceImp implements userService {

    @Autowired
    private userDao userDao;
    public int insert(user user) {
        return userDao.insertUser(user);
    }

    public user querybyUsername(String username) {
        return userDao.selectByUserId(username);
    }
}

在WEB-INF下創建page包,然後在page包中創建test.jsp文件 如圖

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
用戶名<h1>${user.username}</h1>
密碼<h1>${user.password}</h1>
</body>
</html>

然後在controller包下創建userController類

package com.qihang.controller;

import com.qihang.pojo.user;
import com.qihang.services.userService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class UserController {
    @Autowired
    private userService userService;

    @RequestMapping("/query")
    public String query(@RequestParam(value = "username",required = true) String username, Model model){
        user user = new user();
        user = userService.querybyUsername(username);
        model.addAttribute("user",user);
        return "test";

做到這裡就把測試domo寫完瞭,下一步將項目部署到服務器。

如圖點擊配置

點擊 +

將本地tomcat配置好,按如圖deployment 

配置好就完成瞭。點擊運行,在瀏覽器上輸入

http://localhost:8080/query?username=lisi

看到如下就說明我們配置ok瞭

謝謝你們,看到這裡也是幸苦瞭,如果還沒有成功的再認真看看還有哪裡是不是遺漏瞭,也可以在樓下留言,千萬別灰心,程序員工作就是與bug作鬥爭的過程,也是在這些坑中慢慢學習的。

對於新手小白,經常會花很多時間在這些框架的搭建上或是一些工具的配置,而且由於不熟悉,會踩很多坑,花大量時間在這上面確實很不值得的。寫這篇博客也是為大傢能在學習的路上能更順利些,當然也是給自己的踩坑路做個記錄吧

總結

到此這篇關於idea搭建SSM框架遇踩的坑的文章就介紹到這瞭,更多相關idea搭建SSM框架內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: