1. 程式人生 > >eclipse+maven+ssm環境搭建

eclipse+maven+ssm環境搭建

1.安裝Eclipse

下載完成後,開啟eclipse-inst-win64.exe

選擇 Eclipse IDE for Java EE Developers,直至安裝完成

2.安裝JDK

選擇對應作業系統版本

下載完成後安裝,需要安裝在空目錄資料夾下,建議為JDK單獨設立一個Java路徑

3.安裝Tomcat

下載後解壓,如圖:

4.安裝及配置maven

4.2下載完成後解壓,放在D:\Java路徑下 

4.3設定環境變數

4.3.1我的電腦→右擊→屬性→高階系統設定→高階→環境變數

4.3.2新增系統變數名:MAVEN_HOME,變數值:D:\Java\apache-maven-3.5.4-bin

(變數值為maven路徑)

4.3.3在Path中追加(win7和win10有區別)

Win7中在Path中追加:%MAVEN_HOME%\bin;

Win10中在Path中追加:D:\Java\apache-maven-3.5.4-bin\bin 

4.3.4在命令列視窗中輸入:mvn –v,出現如圖所示版本資訊則maven安裝配置完畢

5.Maven倉庫設定

Maven的倉庫有三類,簡單來說三個倉庫的關係:

5.1編輯setting.xml檔案maven倉庫位置在類似下圖

因為眾所周知的原因,直接訪問maven公共倉庫的速度比較慢,所以推薦使用阿里的maven倉庫映象

5.2找到<mirrors>節點新增映象倉庫

5.3節點中加入如下內容,注意請寫在註釋之外

<mirror>
  <id>nexus-aliyun</id>
  <mirrorOf>*</mirrorOf>
  <name>Nexus aliyun</name>
  <url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>

5.4找到<localRepository>節點,加入

如下內容(新增本地倉庫)

<localRepository>D:/Java/maven_repo/localrepo</localRepository>

加入程式碼後如圖所示:

5.5找到<profile>節點,加入如下內容(將預設JDK1.4設定為1.8)

    <id>jdk-1.8</id>
    <activation>
        <activeByDefault>true</activeByDefault>
        <jdk>1.8</jdk>
    </activation>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
    </properties>

6.Eclipse整合Maven

開啟Eclipse→Window→Preferences

設定順序如下:

接著選擇Installations→Add,新增maven路徑,勾選並Apply

7.使用Maven建立SSM專案

7.1 File→new→project,找到Maven project,選擇web型別

7.2設定完兩個id,點選finish

Group ID:相當於一個組織

Artifact ID:相當於這個組織下的一個具體專案

Packege:根據Group ID和Artifact ID生成一個預設的名稱

7.3等待一會,此時會開始載入一些檔案,右下角顯示進度

載入完畢後,本地倉庫出現一些檔案

7.4回到Eclipse,專案建立完成

報的錯誤如下:

7.5在eclipse中設定Server為Tomcat

選擇對應的 Tomcat 版本

找到本地 Tomcat 目錄,注意JRE設定為安裝的JDK的jre

7.6在工程上右鍵,檢視工程屬性properties,找到Java Build Path,新增Server Runtime為Tomcat

點選 Finish,並 Apply後

工程錯誤消失,如圖所示:

7.7還是在專案上右鍵,檢視專案資訊properties),選擇project facets

預設的Dynamic Web Module為2.3,使用Tomcat 9,需要修改為4.0

這裡無法直接選擇修改成4.0,因為我們需要經過以下幾個步驟的設定:

(1)maven工程.setting下org.eclipse.wst.common.project.facet.core.xml

開啟後如下所示:

主要修改第4,第5行,改為

<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="java" version="1.8"/>
  <installed facet="jst.web" version="4.0"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
</faceted-project>

   (2)maven工程目錄\src\main\webapp\WEB-INF的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_4_0.xsd"
       version="3.1" metadata-complete="true">
</web-app>

修改為如圖示:

  (3)maven工程目錄下的pom.xml檔案中修改build節點,新增如下內容

<plugins>
       <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <configuration>
                     <source>1.8</source>
                     <target>1.8</target>
              </configuration>
       </plugin>
</plugins>

修改完如圖示:

(4)修改後,在專案上右鍵,點選Maven屬性下的Update Project,

5選擇該專案進行更新,如果怕不能強制更新,可以勾選Force Update of Snapshots/Releases

右下角有更新進度,更新用時大約三分鐘

   (6)點選OK後更新maven專案,再觀察專案屬性,Module已經變為4.0

8.下載 SSM 所需的 jar 包

修改maven工程目錄下的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>xyz.fowee</groupId>
    <artifactId>ssm</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>ssm Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!-- Spring版本號 -->
        <spring.version>4.3.8.RELEASE</spring.version>
    </properties>
    <dependencies>
        <!-- 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>

        <!-- AOP相關包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.0</version>
        </dependency>

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

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

        <!-- 單元測試相關包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>ssm</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

直接複製上述內容至pom.xml檔案,覆蓋原先所有內容

儲存後右擊Maven專案,點選refresh,可以看到相關jar包被下載至本地倉庫 

9.完善專案結構

由於服務端maven專案的標準結構有四個子包:src/main/java、src/main/resources、src/test/java、src/test/resources,這裡缺少了src/test/resources,所以手動補上。

在專案中新建Source Folder

建立src/test/resources目錄後,工程如下圖所示

右鍵檢視專案屬性properties,點選Deployment Assembly,移除test和target

移除之後如圖所示:

10.建立專案用的配置檔案

在 src/main/resources 下建立5個檔案,分別為log4j.propertiesmybatis-config.xmlspring-mvc.xmlspring-mybatis.xmlspring-tx.xml如圖:

log4j.properties檔案,內容如下:

#USE THIS SETTING FOR OUTPUT MYBATIS`s SQL ON THE CONSOLE
log4j.rootLogger=DEBUG, Console

#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

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>
        <package name="xyz.fowee.domain" />
    </typeAliases>
</configuration>

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

    <!-- 啟動自動掃描 -->
    <context:component-scan base-package="xyz.fowee.*" />

    <!-- 註冊MVC註解驅動 -->
    <mvc:annotation-driven />

    <!-- 靜態資源可訪問的設定方式 -->
    <mvc:default-servlet-handler />

    <!-- 配置檢視解析器,可以顯式設定,也可以不設定,不設定會依據SpringMVC的預設設定 -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>
</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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- 定義資料來源Bean -->
    <!-- Druid -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/test" />
        <property name="username" value="root" />
        <property name="password" value="sa" />
    </bean>

    <!-- 註冊SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自動掃描mappers.xml檔案 -->
        <property name="mapperLocations" value="classpath:xyz/fowee/dao/*.xml" />
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>
    
    <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="xyz.fowee.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    </bean>
</beans>

spring-tx.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">

    <!-- 開啟AOP註解掃描 -->
    <aop:aspectj-autoproxy proxy-target-class="true" />

    <!-- 事務管理器,依賴於資料來源 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
    <!-- 編寫通知:對事務進行增強(通知),需要編寫對切入點和具體執行事務細節 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <!--
                為切入點方法新增事務詳情
                name:方法名,*表示任意方法名稱
                propagation:設定傳播行為
                isolation:設定隔離級別
                read-only:是否只讀
            -->
            <tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="Exception" />
            <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="Exception" />
            <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" read-only="false" rollback-for="Exception" />
        </tx:attributes>
    </tx:advice>
    
    <!-- 設定AOP,讓Spring自動對目標生成代理,需要使用AspectJ表示式 -->
    <aop:config proxy-target-class="true">
        <!-- 切面:整合切入點和通知 -->
        <aop:advisor advice-ref="txAdvice" pointcut="within(xyz.fowee.web..*)" />
    </aop:config>
</beans>

11.服務端

建立如下幾個package 和 method

User實體類,程式碼如下:

package xyz.fowee.domain;

/**
 * 使用者資訊
 */
public class User {
    // 成員變數
    private Integer userid;
    private String username;
    private String password;

    // 建構函式
    public User() {
        super();
    }

    public User(Integer userid, String username, String password) {
        super();
        this.userid = userid;
        this.username = username;
        this.password = password;
    }

    // 成員方法
    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

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

UserController控制器,程式碼如下:

package xyz.fowee.web;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import xyz.fowee.dao.UserDao;
import xyz.fowee.domain.User;

/**
 * 使用者控制器
 */
@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Resource
    private UserDao userDao;

    @RequestMapping("/view")
    public String view() {
        return "main/login";
    }

    @RequestMapping("/indexview")
    public String index() {
        return "main/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(User model, HttpSession session) {
        User user = userDao.findByUsername(model.getUsername());

        if (user == null || !user.getPassword().equals(model.getPassword())) {
            return new ModelAndView("redirect:/login.jsp");
        } else {
            session.setAttribute("user", user);
            ModelAndView mav = new ModelAndView();
            mav.setViewName("index");
            return mav;
        }
    }
}

UserDao資料訪問層介面,程式碼如下:

package xyz.fowee.dao;

import xyz.fowee.domain.User;

public interface UserDao {
    public abstract User findByUsername(String username);
}

UserMapper.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="xyz.fowee.dao.UserDao">
    <select id="findByUsername" parameterType="string" resultType="User">
        SELECT * FROM userinfo WHERE username=#{username}
    </select>
</mapper>

12.客戶端

在webapp目錄下建立 index.jsp和login.jsp

login.jsp登入頁,程式碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>登入</title>
</head>
<body>
<form action="user/login" method="post">
<label>賬號:</label>
<input type="text" id="txtUsername" name="username" placeholder="請輸入賬號" /><br/>
<label>密碼:</label>
<input type="password" id="txtPassword" name="password" placeholder="請輸入密碼" /><br/>
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</body>
</html>

index.jsp主頁,程式碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>主頁</title>
</head>
<body>
<h3>歡迎,${user.username }</h3>
</body>
</html>

修改WEB-INF下的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_4_0.xsd"
       version="4.0" metadata-complete="true">
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
            classpath*:/spring-mybatis.xml,
        classpath*:/spring-tx.xml
    </param-value>
  </context-param>
        
   <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener </listener-class>
  </listener>
    
    
   <servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/classes/spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
  </servlet>
   
  <servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>20</session-timeout>
  </session-config>   
</web-app>
</web-app>

13.使用Maven構建專案

在專案上右鍵,找到Maven屬性的Update Project,也可以Alt+F5操作

專案上右鍵,找到Run As屬性,找到Maven install

點選執行,效果如下說明構建成功

專案執行還是使用web工程的部署執行方式

點選Finish

執行專案,觀察是否報錯

登入頁面:http://localhost:8080/ssm/login.jsp

只是測試,帳號密碼隨便輸,點選提交

發現網頁完成重定向動作

至此,基本完成了 Eclipse下Maven+SSM 的框架搭建

-------------------------------------------------------------------------------------------------------------------------------------------------------------------

主要參考: