利用maven/eclipse搭建ssm(spring+spring mvc+mybatis)

前言

  此種方式已過期,再也不推薦,當下推薦方式:自我救贖 → 利用 IDEA 和 Spring Boot 搭建 SSMhtml

  本文旨在利用maven搭建ssm環境,而關於maven的具體內容,你們能夠去閱讀《Maven 實戰》。其實園內這方面文章已有很多,那麼爲何我還要重複造輪子呢?我只是想記錄本身的實踐過程罷了,附帶着給別人以參考。對於別人的博文,看了當然好,要是能付之實踐,那就更好了!java

  一直在對整個工程作一些配置上的優化,具體代碼能夠從個人github下載mysql

  基於目前spring-boot的火熱,工程慢慢往springboot上轉,碼雲地址:https://gitee.com/youzhibing/spring-boot-2.0.3git

maven搭建

  安裝過程挺簡單的,去apache下載apache-maven的zip包,解壓到一個目錄下,以下圖github

  接下來配置windows環境,右擊個人電腦--》屬性--》高級系統設置--》環境變量--》系統變量--》新建,以下圖web

  就是你解壓的maven的home目錄;接着編輯系統變量的Path,如圖spring

  其實跟配置java環境是同樣的,最後幾個連續肯定以後就行了,這幾個肯定必定要點,否則配置不會保存,更不會生效! home路徑必定要寫本身的,別搬個人呀!路徑最好是拷貝,手動輸入太容易出錯了。sql

  接下來驗證環境是否配置成功,打開命令行,輸入mvn -v 若是出現下圖的信息,那麼恭喜你,配置成功了!固然,信息可能有些許出入,如版本不一樣等,這些不用在乎。數據庫

Eclipse(java ee版)集成maven

  通常而言,新的eclipse都已經集成了maven,若是沒有那麼就安裝,點擊eclipse菜單欄Help->Eclipse Marketplace搜索關鍵字maven到插件Maven Integration for Eclipse 並點擊安裝便可,接下來將eclipse集成的maven換成咱們本身的,而不用eclipse自帶的,從新定位,點擊Window -> Preference -> Maven -> Installation -> Add進行設置,以下圖apache

  設置完成,那麼eclipse配置maven就完成了,myeclipse配置和這個是同樣的。

建立ssm項目

  選擇創建Maven Project 選擇File -> New -> Other,在New窗口中選擇 Maven -> Maven Project;點擊next,以下圖

  選擇項目路徑,以下圖,而後next

  

  選擇項目類型 選擇Artifact Id爲maven-archetype-webapp那一項,以下圖

  輸入Group ID和 Artifact ID,以及Package,具體Group ID和 Artifact ID表明什麼,能夠去閱讀《Maven 實戰》,Group ID至關於一個組織,而Artifact ID至關於這個組織下的一個具體項目,Packege的話會根據你的Group ID和Artifact ID生成一個默認的名稱,就用默認的就能夠,以下圖

  點finish以後,項目結構以下圖

  若目錄結構和上面的有差異,那麼將perspective改爲Java模式就行了。上面的目錄結構離標準的maven web結構還有一點差異,少了一個文件夾src/test/resources,咱們手動建立下,右鍵項目根目錄點擊New -> Source Folder,建出這個文件夾,以下圖:

  Finish以後,項目結構圖以下所示:

  把項目變成Dynamic Web項目右鍵項目,properties --》Project Facets,點擊Convert to faceted fro,勾上Dynamic Web Module,並將Version爲2.3。(3.0爲Java7的)。

  設置部署程序集(Web Deployment Assembly)
        上面步驟設置完成後,點擊OK,再右鍵項目,選擇properties --》Deployment Assembly,以下圖

  此處列表是,部署項目時,文件發佈的路徑。

        (1)咱們刪除test的兩項,由於test是測試使用,並不須要部署。

        (2)設置將Maven的jar包發佈到lib下。

        Add -> JavaBuild Path Entries -> Maven Dependencies -> Finish

        設置完成效果圖

構建框架

  在pom.xml中添加所須要的jar包,內容以下圖

<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.lee.mvnbook</groupId>
    <artifactId>maven-ssm-web</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>maven-ssm-web Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- spring版本號 -->
        <spring.version>4.0.2.RELEASE</spring.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <!-- 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>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!-- 阿里巴巴的數據庫鏈接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</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.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.6.4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.7</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>maven-ssm-web</finalName>
    </build>
</project>
View Code

  若是依賴不知道怎麼寫,好比groupId、artifactId、version不知道填什麼,那麼直接上http://search.maven.org/搜,對應着填寫就能夠了,以下圖

  保存pom.xml,maven就會幫咱們下載咱們配置的全部jar包了,jar包依賴的jar包也會自動下載,是否是很方便!固然,這個下載可能須要較長的時間,不要急,當eclipse右下角的百分比進度沒有了,就下載好了。jar包下載完成後,項目結構圖以下

  配置文件

  web.xml

<?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_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SSM configuration</display-name>
    <!-- 解決工程編碼過濾器 -->
    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    <!-- 配置文件所在位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:mybatis-spring.xml</param-value>
    </context-param>
    <!-- Spring配置(監聽器) -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <!-- SpringMVC配置 -->
    <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
View Code

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

    <!-- 自動注入 -->
    <context:component-scan base-package="com.huawei.service.impl" />
    <!-- 加載properties文件  -->
    <!--  <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:mysqldb.properties</value>
            </list>
        </property>
    </bean> -->
</beans>
View Code

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

    <!-- 配置數據源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 基本屬性 url、user、password -->  
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
        <property name="url" value="jdbc:mysql://192.168.1.100:3306/mybatis" />  
        <property name="username" value="root" />  
        <property name="password" value="root" />  
        <property name="initialSize" value="1" />  
        <property name="minIdle" value="1" />   
        <property name="maxActive" value="20" />  
        <property name="maxWait" value="60000" />
        <!-- 超過期間限制是否回收 -->
        <property name="removeAbandoned" value="true" />
        <!-- 超過期間限制多長; -->
        <property name="removeAbandonedTimeout" value="180" />
        <!-- 配置間隔多久才進行一次檢測,檢測須要關閉的空閒鏈接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一個鏈接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <!-- 用來檢測鏈接是否有效的sql,要求是一個查詢語句-->
        <property name="validationQuery" value="SELECT 1" />
        <!-- 申請鏈接的時候檢測 -->
        <property name="testWhileIdle" value="true" />
        <!-- 申請鏈接時執行validationQuery檢測鏈接是否有效,配置爲true會下降性能 -->
        <property name="testOnBorrow" value="false" />
        <!-- 歸還鏈接時執行validationQuery檢測鏈接是否有效,配置爲true會下降性能  -->
        <property name="testOnReturn" value="false" />
    </bean>

    <!-- Mybatis文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml" /> 
        <property name="dataSource" ref="dataSource" />
        <!-- 映射文件路徑 -->
        <!--  <property name="mapperLocations" value="com/huawei/mapping/*.xml" />-->
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.huawei.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>

    <!-- 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>
View Code

  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.0.xsd  
     ">

    <!-- 啓用spring mvc 註解 -->
    <context:annotation-config />
    
    <!-- 設置使用註解的類所在的jar包 -->
    <context:component-scan base-package="com.huawei.controller" />

    <!-- 完成請求和註解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <!-- 對轉向頁面的路徑解析。prefix:前綴, suffix:後綴 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/" p:suffix=".jsp" />

</beans>
View Code

   mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration  
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  "http://mybatis.org/dtd/mybatis-3-config.dtd">  
      
<configuration>  
    <!-- 全局別名設置,在映射文件中只需寫別名,而沒必要寫出整個類路徑  -->  
    <typeAliases>    
         <typeAlias type="com.huawei.model.Person" alias="Person"/>  
    </typeAliases>     
      <mappers>  
        <mapper resource="com/huawei/mapping/PersonMapper.xml" />  
    </mappers>
</configuration> 
View Code

  log4j.properties

log4j.rootLogger=DEBUG, stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
View Code

  mysqldb.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.1.100:3306/mybatis
jdbc.username=root
jdbc.password=root
jdbc.initialSize=1
jdbc.minIdle=1
jdbc.maxActive=20
jdbc.maxWait=60000
jdbc.removeAbandoned=true
jdbc.removeAbandonedTimeout=180
jdbc.timeBetweenEvictionRunsMillis=60000
jdbc.minEvictableIdleTimeMillis=300000
jdbc.validationQuery=SELECT 1
jdbc.testWhileIdle=true
jdbc.testOnBorrow=false
jdbc.testOnReturn=false
View Code

   項目結構圖以下

  java文件與jsp文件

  PersonController.java

package com.huawei.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.huawei.model.Person;
import com.huawei.service.IPersonService;

@Controller
@RequestMapping("/personController")
public class PersonController {
    
    private IPersonService personService;
    
    public IPersonService getPersonService() {
        return personService;
    }

    @Autowired
    public void setPersonService(IPersonService personService) {
        this.personService = personService;
    }

    @RequestMapping("/showPerson")
    public String showPersons(Model model){
        List<Person> persons = personService.loadPersons();
        model.addAttribute("persons", persons);
        return "showperson";
    }
}
View Code

  PersonMapper.java

package com.huawei.dao;

import java.util.List;

import com.huawei.model.Person;

public interface PersonMapper {
    /**
     * 插入一條記錄
     * @param person
     */
    void insert(Person person);
    
    /**
     * 查詢全部
     * @return
     */
    List<Person> queryAll();
}
View Code

  PersonMapper.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.huawei.dao.PersonMapper">
    <!-- 查詢全部person -->  
    <select id="queryAll" resultType="Person" >  
        select * from person  
    </select>
</mapper>
View Code

  Person.java

package com.huawei.model;

/**
 * person 實體
 * @author Administrator
 *
 */
public class Person {

    private int id;
    private String name;
    private int age;
    
    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;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + "]";
    }
}
View Code

  IPersonService.java

package com.huawei.service;

import java.util.List;

import com.huawei.model.Person;

public interface IPersonService {

    /**
     * 加載所有的person
     * @return
     */
    List<Person> loadPersons();
}
View Code

  PersonServiceImpl.java

package com.huawei.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huawei.dao.PersonMapper;
import com.huawei.model.Person;
import com.huawei.service.IPersonService;

@Service("personService")
public class PersonServiceImpl implements IPersonService {
    
    private PersonMapper personMapper;

    public PersonMapper getPersonMapper() {
        return personMapper;
    }
    @Autowired
    public void setPersonMapper(PersonMapper personMapper) {
        this.personMapper = personMapper;
    }

    @Override
    public List<Person> loadPersons() {
        return personMapper.queryAll();
    }
    
}
View Code

  showperson.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
     pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>person list</title>
    </head>
    <body>
        <table>
            <tr>
                <th>姓名</th>
                <th>年齡</th>
            </tr>
            <c:forEach items="${persons}" var="person">
                <tr>
                    <td>${person.name }</td>
                    <td>${person.age }</td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>
View Code

mysql數據庫表

最終效果

  

  那麼恭喜你,也恭喜我,搭建ssm成功了!

後話

  用心的小夥伴應該發現了,前面的windows配置maven和咱們用eclipse搭建ssm沒有一點關係,確實和ssm搭建沒有什麼卵關係,我寫出來是爲何了,就是有時候咱們不用IDE工具,而在dos命令下利用maven搭建咱們的項目的時候,那麼windows配置maven就需用到了!

  搭建過程當中若是有什麼問題,能夠試着在評論區找答案,或者在關於利用maven搭建ssm的博客,咱們一塊兒來探討下問的最多的問題中找答案

相關文章
相關標籤/搜索