天天看點

idea搭建ssm架構(超詳細) - Java樂享

idea搭建ssm架構(超詳細)

一。建立項目

先附上測試的資料庫

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) COLLATE utf8_bin DEFAULT NULL,
  `password` varchar(10) COLLATE utf8_bin DEFAULT NULL,
  `remark` varchar(50) COLLATE utf8_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (\'1\', \'zhangsan\', \'123456\', null);
INSERT INTO `user` VALUES (\'2\', \'lisi\', \'123\', null);
INSERT INTO `user` VALUES (\'3\', \'wangan\', \'456\', null);
INSERT INTO `user` VALUES (\'4\', \'xinxi\', \'000\', null);      

1.new->project出現如下

idea搭建ssm架構(超詳細) - Java樂享

點選next後出現如下填寫GroupId和ArtifactId在點選next直至finish

idea搭建ssm架構(超詳細) - Java樂享

2.建構目錄結構

在main下建立java和resources目錄如下并将java目錄标記為Sources Root,resources标記為Resources Root

idea搭建ssm架構(超詳細) - Java樂享
idea搭建ssm架構(超詳細) - Java樂享

在java下建立如下包package

idea搭建ssm架構(超詳細) - Java樂享

二。Spring MVC

1.首先引入Spring MVC依賴

<!-- Spring相關包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</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-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-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>      

并添加<properties><spring.version>4.3.8.RELEASE</spring.version></properties>

2.在controller建立TestController類,在WEB-INF下建立static目錄,還在WEB-INF下建立jsp目錄并建立test.jsp頁面

idea搭建ssm架構(超詳細) - Java樂享

3.在web.xml添加dispatcherServlet

<?xml version="1.0" encoding="UTF-8"?>
<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"
         id="WebApp_ID" version="3.0">

  <display-name>SSM2</display-name>
  

  <!-- 設計路徑變量值
  <context-param>
      <param-name>webAppRootKey</param-name>
      <param-value>springmvc.root</param-value>
  </context-param>
  -->

  <!-- Spring字元集過濾器 -->
  <filter>
    <filter-name>SpringEncodingFilter</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SpringEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>



  <!-- springMVC核心配置 -->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--spingMVC的配置路徑   如果是classspath:資源是在resources下面-->
      <param-value>/WEB-INF/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 攔截設定 -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


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

4.在WEB-INF下建立spring-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       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-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 掃描controller(controller層注入) -->
    <context:component-scan base-package="com.exp.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

    </context:component-scan>

    <mvc:annotation-driven />

    <!-- 内容協商管理器  -->
    <!--1、首先檢查路徑擴充名(如my.pdf);2、其次檢查Parameter(如my?format=pdf);3、檢查Accept Header-->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 擴充名至mimeType的映射,即 /user.json => application/json -->
        <property name="favorPathExtension" value="true"/>
        <!-- 用于開啟 /userinfo/123?format=json 的支援 -->
        <property name="favorParameter" value="true"/>
        <property name="parameterName" value="format"/>
        <!-- 是否忽略Accept Header -->
        <property name="ignoreAcceptHeader" value="false"/>

        <property name="mediaTypes"> <!--擴充名到MIME的映射;favorPathExtension, favorParameter是true時起作用  -->
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            </value>
        </property>
        <!-- 預設的content type -->
        <property name="defaultContentType" value="text/html"/>
    </bean>


    <!-- 當在web.xml 中   DispatcherServlet使用 <url-pattern>/</url-pattern> 映射時,能映射靜态資源 -->
    <mvc:default-servlet-handler />
    <!-- 靜态資源映射 -->
    <mvc:resources mapping="/static/**" location="/WEB-INF/static/"/>


    <!-- 對模型視圖添加前字尾 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>


</beans>      

5.部署

點選如下圖

idea搭建ssm架構(超詳細) - Java樂享

點選+号找到Local

idea搭建ssm架構(超詳細) - Java樂享

接下來修改名字,選擇Deployment點選+号,選擇ssm2:war exploded,另外Application context填寫的如果是ssm2,那麼通路的時候就是localhost:8080/ssm2,部署結束。

idea搭建ssm架構(超詳細) - Java樂享

6.啟動測試

啟動後預設通路的是index.jsp頁面,可以通路http://localhost:8080/ssm2/test

idea搭建ssm架構(超詳細) - Java樂享

如果頁面亂碼在頭部加上<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>

三。Spring與Mybatis

1.引入相關依賴

<!-- MyBatis相關包 -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.3.0</version>
      </dependency>
      <!-- MySQL相關包 -->
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.26</version>
      </dependency>
      <!-- 資料庫連接配接池 -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>druid</artifactId>
          <version>1.0.20</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
      <dependency>
          <groupId>com.alibaba</groupId>
          <artifactId>fastjson</artifactId>
          <version>1.2.31</version>
      </dependency>

      <!-- Spring內建MyBatis -->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.3</version>
      </dependency>

      <!-- JSP标準标簽庫 -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>jstl</artifactId>
          <version>1.2</version>
      </dependency>

      <!-- 日志相關包 -->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>
      <dependency>
          <groupId>org.slf4j</groupId>
          <artifactId>slf4j-api</artifactId>
          <version>1.7.21</version>
      </dependency>      

2.生成實體與mybatis配置檔案

在resources下建立generator目錄并建立generatorConfig.xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
    <!--本地的資料庫連接配接驅動位址-->
    <classPathEntry
            location="D:\OfficeWave\configdata\repository\mysql\mysql-connector-java\5.1.26\mysql-connector-java-5.1.26.jar"/>
    <context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <property name="beginningDelimiter" value="`"/>
        <property name="endingDelimiter" value="`"/>
        <property name="mergeable" value="false"></property>
        <!--資料庫連接配接位址-->
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/user"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <!--生成實體類(注意修改包路徑)-->
        <javaModelGenerator targetPackage="com.exp.model" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!--生成mapper.xml-->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>

        <!--生成mapper.java(注意修改包路徑)-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.exp.mapper"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>

            <!--資料庫中的表名稱和對應的實體類名稱-->
        </javaClientGenerator>
        <table tableName="user" domainObjectName="User"></table>

    </context>
</generatorConfiguration>      
idea搭建ssm架構(超詳細) - Java樂享

在pom.xml中的<pluginManagement>标簽下添加如下

<plugins>
          <plugin>
              <groupId>org.mybatis.generator</groupId>
              <artifactId>mybatis-generator-maven-plugin</artifactId>
              <version>1.3.2</version>
              <configuration>
                  <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
                  <overwrite>true</overwrite>
                  <verbose>true</verbose>
              </configuration>
          </plugin>
      </plugins>      

輕按兩下運作即可

idea搭建ssm架構(超詳細) - Java樂享

3.web.xml中引入spring相關配置

<!-- 讀取spring配置檔案 -->
   <listener>
           <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
   <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
</context-param>      

4.在resources下建立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: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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
">
    <!-- 1.配置jdbc檔案 -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:jdbc.properties"/>
    </bean>

    <!-- 2.掃描的包路徑,這裡不掃描被@Controller注解的類 --><!--使用<context:component-scan/> 可以不在配置<context:annotation-config/> -->
    <context:component-scan base-package="com.exp">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

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

</beans>      

5.在resources下建立jdbc.properties檔案和spring-mybatis.xml

jdbc.properties

jdbc_driverClassName =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=utf8
jdbc_username=root
jdbc_password=root      

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

    <!-- 3.配置資料源 ,使用的alibba的資料庫-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->
        <property name="driverClassName" value="${jdbc_driverClassName}"/>
        <property name="url" value="${jdbc_url}"/>
        <property name="username" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>

        <!-- 配置初始化大小、最小、最大 -->
        <property name="initialSize" value="10"/>
        <property name="minIdle" value="10"/>
        <property name="maxActive" value="50"/>

        <!-- 配置擷取連接配接等待逾時的時間 -->
        <property name="maxWait" value="60000"/>
        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接配接,機關是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />

        <!-- 配置一個連接配接在池中最小生存的時間,機關是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />

        <property name="validationQuery" value="SELECT \'x\'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />

        <!-- 打開PSCache,并且指定每個連接配接上PSCache的大小  如果用Oracle,則把poolPreparedStatements配置為true,mysql可以配置為false。-->
        <property name="poolPreparedStatements" value="false" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />

        <!-- 配置監控統計攔截的filters -->
        <property name="filters" value="wall,stat" />
    </bean>

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


    <!-- DAO接口所在包名,Spring會自動查找其下的類 ,自動掃描了所有的XxxxMapper.xml對應的mapper接口檔案,隻要Mapper接口類和Mapper映射檔案對應起來就可以了-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.exp.mapper" />
        <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>

    <!--======= 事務配置 End =================== -->
    <!-- 配置基于注解的聲明式事務 -->
    <!-- enables scanning for @Transactional annotations -->
    <tx:annotation-driven transaction-manager="transactionManager" />


</beans>      

6.編寫代碼

在service下建立接口UserService

package com.exp.service;

import com.exp.model.User;

import java.util.List;

public interface UserService {

    List<User> selectAll();
}      

 在UserServiceImpl下建立類UserServiceImpl

package com.exp.service.impl;

import com.exp.mapper.UserMapper;
import com.exp.model.User;
import com.exp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> selectAll() {
        List<User> userList = userMapper.selectAll();
        return userList;
    }
}      
類TestController      
package com.exp.controller;

import com.exp.model.User;
import com.exp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/")
public class TestController {

    @Autowired
    private UserService userService;

    @RequestMapping("/test")
    public String test(){
        List<User> userList = userService.selectAll();
        for (User user:userList){
            System.out.println(user);
        }
        return "test";
    }
}      

7.測試

通路http://localhost:8080/ssm2/test

在server列印如下即搭建成功

idea搭建ssm架構(超詳細) - Java樂享