1. 程式人生 > >IntelliJ IDEA整合SSM框架

IntelliJ IDEA整合SSM框架

SSM框架整合(IntelliJ IDEA + maven + Spring + SpringMVC + MyBatis)

1. 建立maven專案

1.1 File–>New Module,進入建立專案視窗

這裡寫圖片描述

1.2 點選Next,填寫GroupId、ArtifactId和Version

這裡寫圖片描述

1.3 在Properties中新增一個引數 archetypeCatalog=internal,不加這個引數,在maven生成骨架的時候將會非常慢,有時候直接卡住。

這裡寫圖片描述

1.4 填寫Module name

這裡寫圖片描述

1.5 生成maven的專案骨架之後,我們還需要手動在 src/main 下建立 java目錄。完整的專案結構如下圖

這裡寫圖片描述

1.6 這裡的目錄建好之後還需要設定一下,讓idea識別目錄作用,選擇File-Project Structure

這裡寫圖片描述

到此為止,專案的框架基本搭建完成

2. 專案配置檔案

2.1 這裡使用maven來引入專案所需要的jar包,所以也就不需要手動來管理jar包了

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>com.web</groupId>
<artifactId>ssm</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>ssm Maven Webapp</name>
<url>http://maven.apache.org</url>

<properties>
    <!-- 設定專案編碼編碼 -->
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <!-- spring版本號 -->
    <spring.version>4.3.5.RELEASE</spring.version>
    <!-- mybatis版本號 -->
    <mybatis.version>3.4.1</mybatis.version>
</properties>

<dependencies>

    <!-- java ee -->
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>7.0</version>
    </dependency>

    <!-- 單元測試 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <!-- 實現slf4j介面並整合 -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.2.2</version>
    </dependency>

    <!-- JSON -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.7</version>
    </dependency>


    <!-- 資料庫 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.41</version>
        <scope>runtime</scope>
    </dependency>

    <!-- 資料庫連線池 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</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.3.1</version>
    </dependency>

    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</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-context</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-tx</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-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

<build>
    <finalName>ssm</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <!-- 設定JDK版本 -->
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>

</build>
</project>

2.2 這裡可以控制輸出格式和內容,有興趣的可以自己設定

logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="debug">
        <appender-ref ref="STDOUT"/>
    </root>
</configuration>

2.3 新建jdbc.properties檔案

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
#資料庫地址
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8&useSSL=false
#使用者名稱
jdbc.username=root
#密碼
jdbc.password=201314
#最大連線數
c3p0.maxPoolSize=30
#最小連線數
c3p0.minPoolSize=10
#關閉連線後不自動commit
c3p0.autoCommitOnClose=false
#獲取連線超時時間
c3p0.checkoutTimeout=10000
#當獲取連線失敗重試次數
c3p0.acquireRetryAttempts=2

2.4 新建log4j配置檔案

log4j.properties

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=[%p][%t][%d{yyyy-MM-dd HH:mm:ss}][%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][%t][%d{yyyy-MM-dd HH:mm:ss}][%C] - %m%n

2.5 新建spring和mybatis整合所需的配置檔案

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: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">

<!-- 掃描service包下所有使用註解的型別 -->
<context:component-scan base-package="com.ssm.service"/>

<!-- 配置資料庫相關引數properties的屬性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>

<!-- 資料庫連線池 -->
<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.ssm.model"/>
    <!-- 掃描sql配置檔案:mapper需要的xml檔案 -->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

<!-- 配置掃描Dao介面包,動態實現Dao介面,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <!-- 注入sqlSessionFactory -->
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    <!-- 給出需要掃描Dao介面包 -->
    <property name="basePackage" value="com.ssm.dao"/>
</bean>

<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入資料庫連線池 -->
    <property name="dataSource" ref="dataSource"/>
</bean>

<!-- 配置基於註解的宣告式事務 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

2.6 新建springmvc配置檔案

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: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-3.0.xsd">

<!-- 掃描web相關的bean -->
<context:component-scan base-package="com.ssm.controller"/>

<!-- 開啟SpringMVC註解模式 -->
<mvc:annotation-driven/>

<!-- 靜態資源預設servlet配置 -->
<mvc:default-servlet-handler/>

<!-- 配置jsp 顯示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
    <property name="prefix" value="/WEB-INF/views/"/>
    <property name="suffix" value=".jsp"/>
</bean>

</beans>

2.7 新建web.xml配置檔案

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">

<display-name>ssm</display-name>
<description>SSM_Alpha_0.0.1</description>

<!-- 編碼過濾器 -->
<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>

<!-- 配置DispatcherServlet -->
<servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springMVC需要載入的配置檔案-->
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-*.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>
    <!-- 匹配所有請求,此處也可以配置成 *.do 形式 -->
    <url-pattern>/</url-pattern>
</servlet-mapping>

<welcome-file-list>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

</web-app>

3.0 測試

3.1 建立資料庫表

3.2 配置類

User

package com.ssm.model;

public class User {

private Integer id;
private String username;
private String password;


public Integer getId() {
    return id;
}

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

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;
}

@Override
public String toString() {
    return "User{" +
            "id=" + id +
            ", username='" + username + '\'' +
            ", password='" + password + '\'' +
            '}';
}
}

IUserDao

package com.ssm.dao;

import com.ssm.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class IUserDaoTest {

    @Autowired
    private IUserDao dao;

    @Test
    public void testSelectUser(){
        Integer id = 1;
        User user = dao.selectUser(id);
        System.out.println(user);

    }
}

UserDao.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.ssm.dao.IUserDao">

<select id="selectUser" resultType="User" parameterType="Integer">
    SELECT * FROM user WHERE id = #{id}
</select>

</mapper>

IUserService

package com.ssm.service;

import com.ssm.model.User;

public interface IUserService {

    User selectUser(Integer userId);
}

UserServiceImpl

package com.ssm.service.impl;

import com.ssm.dao.IUserDao;
import com.ssm.model.User;
import com.ssm.service.IUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("userService")
public class UserServiceImpl implements IUserService{
@Resource
private IUserDao userDao;

public User selectUser(Integer userId){
    return this.userDao.selectUser(1);
}

}

UserController

package com.ssm.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssm.model.User;
import com.ssm.service.IUserService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserController {

@Resource
private IUserService userService;

@RequestMapping("/showUser.do")
public void selectUser(HttpServletRequest request, HttpServletResponse response) throws IOException {

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    Integer userId = Integer.parseInt(request.getParameter("id"));
    User user = this.userService.selectUser(userId);
    ObjectMapper mapper = new ObjectMapper();
    response.getWriter().write(mapper.writeValueAsString(user));

}
}

IUserDaoTest(測試mybatis)

package com.ssm.dao;

import com.ssm.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:spring-mybatis.xml"})
public class IUserDaoTest {

@Autowired
private IUserDao dao;

@Test
public void testSelectUser(){
    Integer id = 1;
    User user = dao.selectUser(id);
    System.out.println(user);

}
}

3.3 新建個頁面來測試springmvc和mybatis

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<script>
function selectUser() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("test").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST", "user/showUser.do", true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("id=1");
}
</script>
<body>
<p id="test">Hello World!</p>
<button type="button" onclick="selectUser()">onclick test</button>
</body>
</html>

3 在伺服器上部署專案

3.1 新增專案

File–>Project Structure–>Artifacts–> + –>Web Application:Exploded–>Form Modules
這裡寫圖片描述

3.2 新增伺服器

run–>Edit Configurations–> + –>TomcatServer
這裡寫圖片描述

3.3 部署專案

這裡寫圖片描述

4 執行專案

以DeBug模式執行專案