【小白第一篇】maven搭建ssm專案

Yang_zg_發表於2018-06-30

第一遍部落格,記錄在學習IT路上的的一些總結

工具:eclipse,jdk1.8

雖然maven作為Java構建工具和Gradle比已經要涼了,但作為剛入行的可以瞭解一下


第一步

建一個maven專案,在這裡我用的是maven3.5.3,下圖


settings.xml用的阿里倉庫

       <mirror>  
            <!--id, name是該映象的唯一定義符。id用來區分不同的mirror元素。 -->  
            <id>aliyun</id>  
            <name>aliyun maven</name>  
            <!--url是該映象的URL。構建系統會優先考慮使用該URL,而非使用預設的伺服器URL。 -->  
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
            <!--<mirrorOf>的值為星號,表示該配置是匹配所有遠端倉庫。   -->  
            <mirrorOf>*</mirrorOf>  
        </mirror> 

maven的下載,配置,eclipse外掛就不說了,百度有的是


然後開始建專案


(具體怎麼搭建,每一個幹什麼,百度上已經有很多大佬分享了)

因為建立的simple project,packaging是war包,報了個錯

加一個這個就好了

再把這個修改一下我用的1.8




第二步

分包


搭建環境,首先是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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>maven_ssm_test</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>   
        <dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>3.8.1</version>  
            <scope>test</scope>  
        </dependency>  
        <!-- spring 相關jar -->  
        <!-- Spring 4.3.3 -->  
        <!-- Core Container 核心容器 -->  
        <!-- 核心工具類,Spring其它模組大量使用Spring-core -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-test</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 執行時Spring容器 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- Spring容器對第三方包的整合 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>4.3.3.RELEASE</version>  
            <type>jar</type>  
            <scope>compile</scope>  
        </dependency>  
        <!-- Spring定義Bean的支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-beans</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 使用表示式語言在執行時查詢和操作物件 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-expression</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- End Core Container 核心容器 -->  
  
        <!-- AOP -->  
        <!-- 基於代理的AOP支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 基於AspectJ的AOP支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aspects</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- aspectj -->  
        <dependency>  
            <groupId>org.aspectj</groupId>  
            <artifactId>aspectjrt</artifactId>  
            <version>1.8.5</version>  
        </dependency>  
        <dependency>  
            <groupId>org.aspectj</groupId>  
            <artifactId>aspectjweaver</artifactId>  
            <version>1.8.5</version>  
        </dependency>  
        <!-- End AOP -->  
  
        <!-- web -->  
        <!-- 提供基礎的web整合的功能,在web專案中提供Spring容器 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 提供基於Servlet的SpringMVC -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 提供WebSocket功能 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-websocket</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 提供Portlet環境支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc-portlet</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
  
        <!-- json -->  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-core-lgpl</artifactId>  
            <version>1.9.6</version>  
        </dependency>  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-core-asl</artifactId>  
            <version>1.9.4</version>  
        </dependency>  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.5</version>  
        </dependency>  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-lgpl</artifactId>  
            <version>1.9.6</version>  
        </dependency>  
  
        <!-- End web -->  
        <!-- DataAccess/Integration 資料訪問/整合 -->  
        <!-- 提供以JDBC訪問資料庫的支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 提供程式設計式和宣告式的事務支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-tx</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 提供對 物件/關係對映技術的支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-orm</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- 提供對JMS的支援 -->  
        <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jms</artifactId>  
            <version>4.3.3.RELEASE</version>  
        </dependency>  
        <!-- End DataAccess/Integration 資料訪問/整合 -->  
        <dependency>  
            <groupId>org.codehaus.jackson</groupId>  
            <artifactId>jackson-mapper-asl</artifactId>  
            <version>1.9.13</version>  
        </dependency>  
        <!-- End Spring 4.0 -->  
  
        <!-- mybatis jar -->  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.4.1</version>  
        </dependency>  
        <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.3.0</version>  
        </dependency>  
        <dependency>  
            <groupId>mysql</groupId>  
            <artifactId>mysql-connector-java</artifactId>  
            <version>5.1.21</version>  
        </dependency>  
        <dependency>  
            <groupId>c3p0</groupId>  
            <artifactId>c3p0</artifactId>  
            <version>0.9.1.2</version>  
            <type>jar</type>  
        </dependency>  
  
        <!-- 列印日誌 -->  
        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-api</artifactId>  
            <version>1.7.22</version>  
        </dependency>  
        <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-log4j12</artifactId>  
            <version>1.7.22</version>  
        </dependency>  
        <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
        </dependency>  
        <dependency>  
            <groupId>jstl</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
        </dependency>  
  
        <!-- jsp jar -->  
        <!-- JSP相關 -->  
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>servlet-api</artifactId>  
            <version>2.5</version>  
            <scope>provided</scope>  
        </dependency>  
        <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>jsp-api</artifactId>  
            <version>2.0</version>  
            <scope>provided</scope>  
        </dependency>  
    </dependencies>  

  <build>

  <resources>  
     <resource>  
         <directory>src/main/resources</directory>  
             <includes>  
                  <include>**/*.properties</include>  
                  <include>**/*.xml</include>  
                  <include>**/*.tld</include>  
              </includes>  
              <filtering>false</filtering>  
     </resource>  
     <resource>  
          <directory>src/main/java</directory>  
          <includes>  
               <include>**/*.properties</include>  
               <include>**/*.xml</include>  
                <include>**/*.tld</include>  
           </includes>  
           <filtering>false</filtering>  
     </resource>  
   </resources>  
  	<plugins>
	    <plugin>
		<groupId>org.apache.maven.plugins</groupId>
		    <artifactId>maven-compiler-plugin</artifactId>
			<configuration>
				<source>1.8</source>
				<target>1.8</target>
				<encoding>UTF-8</encoding>
			</configuration>
	   </plugin>
            <!-- tomcat7 外掛-->
           <plugin>
              <groupId>org.apache.tomcat.maven</groupId>
              <artifactId>tomcat7-maven-plugin</artifactId>
              <version>2.2</version>
              <configuration>
                  <port>8080</port> 
                  <uriEncoding>UTF-8</uriEncoding>
             </configuration>
         </plugin>
</plugins>

</build>
</project>
  
  

框架的配置檔案


applicationContext-dao.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.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 資料庫連線池 :dataSource -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		destroy-method="close">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl"
			value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8" />
		<property name="user" value="root" />
		<property name="password" value="root" />
		<property name="minPoolSize" value="1" />
		<property name="maxPoolSize" value="20" />
		<property name="maxIdleTime" value="1800" />
		<property name="acquireIncrement" value="2" />
		<property name="maxStatements" value="0" />
		<property name="initialPoolSize" value="2" />
		<property name="idleConnectionTestPeriod" value="1800" />
		<property name="acquireRetryAttempts" value="30" />
		<property name="breakAfterAcquireFailure" value="true" />
		<property name="testConnectionOnCheckout" value="false" />
	</bean>

	<!-- 定義Mybatis的SqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 定義資料來源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 指定mybatis全域性配置檔案 -->
		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"/>
  		<property name="mapperLocations" value="classpath:com/maven_ssm_test/mapper/*.xml" />  
  		<!-- 別名掃描包 -->
  		<property name="typeAliasesPackage" value="com.maven_ssm_test.enity"/>
	</bean>
	<!-- 配置自動生成介面的實現類 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
		<property name="basePackage" value="com.maven_ssm_test.mapper"/>
	</bean>
</beans>

applicationContext-service.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.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
	
    <!-- 註解開發-->
    <context:annotation-config/>
    <!-- 批量掃描service類所在的包 -->
    <context:component-scan base-package="com.maven_ssm_test.service"/>
</beans>
applicationContext-transaction.xml 裡
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	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-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
    <!-- (事務管理)transaction manager-->  
    <bean id="transactionManager"  
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />  
    </bean>  
    <!-- 配置事務特性 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="insert*"  rollback-for="java.lang.Exception"/>
			<tx:method name="update*"  rollback-for="java.lang.Exception"/>
			<tx:method name="delete*" rollback-for="java.lang.Exception"/>
			<tx:method name="add*" rollback-for="java.lang.Exception"/>
			<tx:method name="select*"  read-only="true"/>
			<tx:method name="find*" read-only="true" />
			<tx:method name="get*" read-only="true" />
			<tx:method name="query*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 宣告式事務-->
	<aop:config>
        <!-- 配置事務的切入點 --> 
		<aop:pointcut id="targetMethod" expression="execution(* com.maven_ssm_test.service.*.*(..))"/>
		<aop:advisor advice-ref="txAdvice" pointcut-ref="targetMethod" />
	</aop:config>
</beans>

springmvc.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.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<!-- 註解方式 -->
        <mvc:annotation-driven/>
	<context:component-scan base-package="com.maven_ssm_test.controller"/>
	
	<!-- 對模型檢視名稱的解析,即在模型檢視名稱新增前字尾 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/jsp/" />
		<property name="suffix" value=".jsp" /><!--可為空,方便實現自已的依據副檔名來選擇檢視解釋類的邏輯 -->
	</bean>
</beans>

SqlMapConfig.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>
	<!-- 全域性引數 -->
	<settings>
		<setting name="autoMappingBehavior" value="FULL"/>
	</settings>
	
	<!-- <settings>
		使全域性的對映器啟用或禁用快取。
		<setting name="cacheEnabled" value="true"/>
		全域性啟用或禁用延遲載入。當禁用時,所有關聯物件都會即時載入。
		<setting name="lazyLoadingEnabled" value="true"/>
		當啟用時,有延遲載入屬性的物件在被呼叫時將會完全載入任意屬性。否則,每種屬性將會按需要載入。
		<setting name="aggressiveLazyLoading" value="false"/>
		是否允許單條sql 返回多個資料集  (取決於驅動的相容性) default:true
		<setting name="multipleResultSetsEnabled" value="true"/>
		是否可以使用列的別名 (取決於驅動的相容性) default:true
		<setting name="useColumnLabel" value="true"/>
		允許JDBC 生成主鍵。需要驅動器支援。如果設為了true,這個設定將強制使用被生成的主鍵,有一些驅動器不相容不過仍然可以執行。  default:false 
		<setting name="useGeneratedKeys" value="false"/>
		指定 MyBatis 如何自動對映 資料基表的列 NONE:不隱射 PARTIAL:部分  FULL:全部   
		<setting name="autoMappingBehavior" value="PARTIAL"/>
		這是預設的執行型別  (SIMPLE: 簡單; REUSE: 執行器可能重複使用prepared statements語句;BATCH: 執行器可以重複執行語句和批量更新) 
		<setting name="defaultExecutorType" value="SIMPLE"/>
		使用駝峰命名法轉換欄位。
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		設定本地快取範圍 session:就會有資料的共享  statement:語句範圍 (這樣就不會有資料的共享 ) defalut:session
        <setting name="localCacheScope" value="SESSION"/>
        設定但JDBC型別為空時,某些驅動程式 要指定值,default:OTHER,插入空值時不需要指定型別
        <setting name="jdbcTypeForNull" value="NULL"/>
	</settings> -->
</configuration>

log4j.properties 日誌

# Global logging configuration
#\u751F\u4EA7\u73AF\u5883\u914D\u7F6Einfo   ERROR
log4j.rootLogger=DEBUG,stdout
# MyBatis logging configuration...
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

第三步

測試一下,下面類的位置

User.java

package com.maven_ssm_test.enity;

/**
 * User實體類
 */
public class User {
	private Integer userid;
	private String username;
	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;
	}
	@Override
	public String toString() {
		return "User [userid=" + userid + ", username=" + username + "]";
	}
	
	
}


UserMapper.java

package com.maven_ssm_test.mapper;

import java.util.List;
import com.maven_ssm_test.enity.User;

/**
 * usermapper介面
 */
public interface UserMapper {
	
	// 查所有
	public List<User> selectAll();
}

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">
<!-- 對映檔案的namespace屬性需要配置對應介面的全類名 -->
<mapper namespace="com.maven_ssm_test.mapper.UserMapper">
	<!-- id屬性要與介面的方法名一致 -->
	<!-- parameterType屬性要和方法的形參一致   包名在sqlMapConfig配好   類名就行-->
	<!-- resuletType屬性要和方法返回值型別一致  -->
	
	<!-- 查所有 -->
	<select id="selectAll" resultType="user">
		select * from user
	</select>

</mapper>

UserService.java

package com.maven_ssm_test.service;

import java.util.List;
import com.maven_ssm_test.enity.User;

/**
 * user業務層
 */
public interface UserService {
	
	// 查所有
	public List<User> selectAll();
}

UserServiceImpl.java

package com.maven_ssm_test.service.impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.maven_ssm_test.enity.User;
import com.maven_ssm_test.mapper.UserMapper;
import com.maven_ssm_test.service.UserService;

/**
 * user業務層實現類
 */
@Service
public class UserServiceImpl implements UserService {
	
	@Autowired
	private UserMapper userMapper;

	public List<User> selectAll() {
		return userMapper.selectAll();
	}

}

UserController.java

package com.maven_ssm_test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.maven_ssm_test.enity.User;
import com.maven_ssm_test.service.UserService;

/**
 * user控制層
 */
@Controller
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/selectAll")
	public ModelAndView selectAllUser(ModelAndView mv){
		
		System.out.println(userService.selectAll());
		
		mv.setViewName("success");
		return mv;
	}
}

資料庫


然後啟動,專案右鍵run as ——》Maven build ——》輸入 tomcat7:run 啟動

OK !!

相關文章