1. 程式人生 > >Maven-SSM框架整合

Maven-SSM框架整合

jstl 導入 ring test 編碼格式 append main ani pat

1、創建Maven項目

配置pom.xml依賴

<!-- 允許創建jsp頁面 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!-- jsp頁面標簽 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- jsp API -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- servlet Api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- SSM依賴 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument-tomcat</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-messaging</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc-portlet</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>4.2.1.RELEASE</version>
        </dependency>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.40</version>
        </dependency>
        <!-- jackjson,支持接口返回輸出json格式 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.2.1</version>
        </dependency>
        <!--打印日誌 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.5</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>
        
        <!-- 文件上傳處理 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>
<build>
        <finalName>SSM-project</finalName>
        <plugins>
            <!--JDK版本 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.5.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showWarnings>true
</showWarnings> </configuration> </plugin> <!-- Tomcat7插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <!-- tomcat7的插件, 不同tomcat版本這個也不一樣 --> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.1</version> <configuration> <!-- 通過maven tomcat7:run運行項目時,訪問項目的端口號 --> <port>8080</port> <!-- 項目訪問路徑 本例:localhost:9090, 如果配置的aa, 則訪問路徑為localhost:9090/aa --> <path>/SpringMVC_Maven</path> <uriEncoding>UTF-8</uriEncoding> </configuration> </plugin> </plugins> </build>

2、導入db.properties

dataSource.driverName=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://{主機IP}/{數據庫名稱}
dataSource.user={數據庫用戶名}
dataSource.password={數據庫密碼}

 

導入日誌:log4j.properties

log4j.rootLogger=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=[%c]%m%n
log4j.appender.File=org.apache.log4j.RollingFileAppender 
log4j.appender.File.File=../log/error.log
log4j.appender.File.MaxFileSize=10MB
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

3、配置springMVC配置文件:src/main/resources/springmvc/springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    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">
    <!-- 掃描器,指定DispatcherServlet去掃描當前包名下的所有類, base-package屬性不能精確到類級別,只能到包級別 -->
    <context:component-scan
        base-package="com.maven.controller" />
    <!-- exception -->
    <context:component-scan
        base-package="com.maven.exception" />
    <!-- 視圖解析器 -->
    <bean 
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    
    <!-- 解決@ResponseBody中文亂碼 -->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8" />
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>    
    <!-- 文件上傳配置 -->
     <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
       <!--  defaultEncoding:請求的編碼格式必須和用戶JSP的編碼一致,以便正確讀取表單中的內容。 
            uploadTempDir:文件上傳過程中的臨時目錄,上傳完成後,臨時文件會自動刪除 
            maxUploadSize:設置文件上傳大小上限(單位為字節)-1為無限制 -->
        <property name="defaultEncoding" value="UTF-8" />
        <property name="maxUploadSize" value="102400000" /> 
       <!--  uploadTempDir可以不做設置,有默認的路徑,上傳完畢會臨時文件會自動被清理掉 -->
        <property name="uploadTempDir" value="/upload/"></property>
    </bean> 

    <!-- 處理器映射器 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" 
        /> -->

    <!-- 處理器適配器 -->
    <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" 
        /> -->

    <!-- 配置註解驅動,配置之後就不用配置處理器映射器和處理器適配器了 -->
    <mvc:annotation-driven />
    <!-- 靜態資源不攔截 -->
    <mvc:resources location="/staitcSources/"
        mapping="/staitcSources/**" />

    <!-- 配置攔截器,可以配置多個攔截器,按順序執行 -->
    <!-- <mvc:interceptors>
        第一個攔截器
        <mvc:interceptor>
            <mvc:mapping path="/**" /> 所有請求都攔截
            <mvc:exclude-mapping path="/staticRescoures/**"/> 靜態資源不攔截
            <bean class="org.sprigmvc.Interceptor.MyInterceptor1" />
        </mvc:interceptor>
        第二個攔截器
        <mvc:interceptor>
            <mvc:mapping path="/**" /> 所有請求都攔截
            <mvc:exclude-mapping path="/staticRescoures/**"/> 靜態資源不攔截
            <bean class="org.sprigmvc.Interceptor.MyInterceptor2" />
        </mvc:interceptor>
    </mvc:interceptors> -->
</beans>

4、配置mybaits配置文件:src/main/resources/mybaits/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.maven.pojo.animalPojo" alias="Animal"/>
          <typeAlias type="com.maven.pojo.cttablePojo" alias="Cttable"/>
      </typeAliases>
</configuration>

5、配置spring配置文件:/resources/spring/applicationContent-dao.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">

    <!-- 數據源 -->
    <context:property-placeholder
        location="classpath:db.properties" ignore-unresolvable="true" />
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${dataSource.driverName}" />
        <property name="url" value="${dataSource.jdbcUrl}" />
        <property name="username" value="${dataSource.user}" />
        <property name="password" value="${dataSource.password}" />
    </bean>
    <!-- 會話工廠 -->
    <bean id="sqlSessionFactory"
        class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <!-- 載入mybaits配置文件 -->
        <property name="configLocation"
            value="classpath:mybaits/mybatis-config.xml"></property>
        <!-- 載入SQL映射文件 -->
        <property name="mapperLocations"
            value="classpath:com/maven/dao/*.xml"></property>
    </bean>
    <!-- 事務管理器 -->
    <bean id="txManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    
     <!-- 事務註解驅動,註解@Transactional的類和方法將具有事務性 
        <tx:annotation-driven transaction-manager="txManager" />-->
        
    <!-- 配置事務增強處理Bean,指定事務管理器 -->
    <tx:advice id="txAdvice"
        transaction-manager="txManager">
        <!-- 用於配置詳細的事務傳播、隔離、是否只讀等屬性, 這些屬性會封裝到底層事務代碼中的TransactionDefinition中 -->
        <tx:attributes>
            <!-- 所有以‘get‘開頭的方法是read-only的 事務的隔離性isolation="DEFAULT" 事務的傳播行為 propagation="REQUIRED" 
                REQUIRED 支持當前的事務,如果不存在就創建一個新的。這是最常用的選擇。 SUPPORTS 支持當前的事務,如果不存在就不使用事務。 MANDATORY 
                支持當前的事務,如果不存在就拋出異常。 REQUIRES_NEW 創建一個新的事務,並暫停當前的事務(如果存在)。 NOT_SUPPORTED 不使用事務,並暫停當前的事務(如果存在)。 
                NEVER 不使用事務,如果當前存在事務就拋出異常。 NESTED 如果當前存在事務就作為嵌入事務執行,否則與REQUIRED類似。 事務的超時 
                timeout="-1" -1為永不超時,8代表8秒超時 -->
            <tx:method name="get*,login*" read-only="true"
                isolation="DEFAULT" propagation="REQUIRED" timeout="-1" />
            <!-- 其他方法使用默認的事務設置 -->
            <tx:method name="*" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <!-- 配置一個切入點,org.fkjava.service以及子包下面的所有類需要做事務 -->
        <aop:pointcut id="pointcut"
            expression="execution(* com.maven.service..*ServiceImpl.*(..))" />

        <!-- 指定在pointcut切入點應用txAdvice事務增強處理 aop:advisor的作用是在已有的advice前提下,通過該元素指定將advice織入哪些位置 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>

</beans>

配置spring-service層:/resources/spring/applicationContent-service.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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
        
   <beans>
        <bean id="userdao" class="com.maven.service.impl.UserServiceImpl" p:sqlSessionFactory-ref="sqlSessionFactory"></bean>
    </beans>
</beans>

6、配置web.xml

 <!-- log4j配置 -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:log4j.properties</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
    
     <!-- Spring容器加載所有的配置文件的路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:spring/applicationContent-*.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
    
     <!-- 配置SpringMVC核心控制器 -->
        <servlet>
        <servlet-name>MVC</servlet-name>
        <!-- SpringMVC的中央處理器:DispathcherServlet有,其成為分派器, 把所有的請求url分派給其他的處理器 -->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc/springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup> <!-- 加載的時候就啟動 -->
    </servlet>
    <servlet-mapping>
        <servlet-name>MVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <!-- 解決中文亂碼 -->
    <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>
    
    <!-- 404頁面 -->
    <error-page>
       <error-code>404</error-code>
       <location>/404.jsp</location>
    </error-page>

自此,最基本的配置就完成了,用的時候註意改相對應的配置文件地址

7、最簡單的測試

技術分享圖片

UserLoginController:

package com.maven.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.portlet.ModelAndView;

import com.maven.pojo.animalPojo;
import com.maven.service.UserService;

@Controller
public class UserLoginController {
    @Resource(name="userdao")
    private UserService userservice;
   @RequestMapping(value="/home")
   @ResponseBody
   public ModelAndView login(ModelAndView mv) {
       List<animalPojo> list=userservice.getAllDate();
       mv.setViewName("home");
       mv.addObject("json", list);
       System.out.println(list);
       return mv;
   }
}

animalMapper,java

package com.maven.dao;

import java.util.List;

import com.maven.pojo.animalPojo;

public interface animalMapper {
    List<animalPojo> selectAllData();
}

animalMapper.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.maven.dao.animalMapper">
    <resultMap type="Animal" id="AnimalResultMap">
           <id column="id" property="id"/>
           <result column="Species_id" property="SpeciesId"/>
           <result column="animal" property="animalName"/>
    </resultMap>
    <select id="selectAllData" resultMap="AnimalResultMap">
           select *from animal
    </select>
</mapper>

animalPojo.java

package com.maven.pojo;

public class animalPojo {
      private int id;
      private String SpeciesId;
      private String animalName;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getSpeciesId() {
        return SpeciesId;
    }
    public void setSpeciesId(String speciesId) {
        SpeciesId = speciesId;
    }
    public String getAnimalName() {
        return animalName;
    }
    public void setAnimalName(String animalName) {
        this.animalName = animalName;
    }
    @Override
    public String toString() {
        return "animalPojo [id=" + id + ", SpeciesId=" + SpeciesId + ", animalName=" + animalName + "]";
    }
    public animalPojo() {
        super();
        // TODO Auto-generated constructor stub
    }
    public animalPojo(int id, String speciesId, String animalName) {
        super();
        this.id = id;
        SpeciesId = speciesId;
        this.animalName = animalName;
    }
      
}

cttablePojo.java

package com.maven.pojo;

public class cttablePojo {
     private Integer id;
     private String Species;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getSpecies() {
        return Species;
    }
    public void setSpecies(String species) {
        Species = species;
    }
    @Override
    public String toString() {
        return "cttablePojo [id=" + id + ", Species=" + Species + "]";
    }
    public cttablePojo() {
        super();
        // TODO Auto-generated constructor stub
    }
    public cttablePojo(Integer id, String species) {
        super();
        this.id = id;
        Species = species;
    }
     
}

UserService.java

package com.maven.service;

import java.util.List;

import com.maven.pojo.animalPojo;

public interface UserService {
     /**
      * 獲取animal所有的數據
      * */
    List<animalPojo> getAllDate();
}

UserServiceImpl.java

package com.maven.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import com.maven.dao.animalMapper;
import com.maven.pojo.animalPojo;
import com.maven.service.UserService;

public class UserServiceImpl implements UserService {
    
    private SqlSessionFactory sqlSessionFactory;
    
    public SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        this.sqlSessionFactory = sqlSessionFactory;
    }
    public UserServiceImpl() {}
    @Override
    public List<animalPojo> getAllDate() {
        // TODO Auto-generated method stub
        SqlSession session=sqlSessionFactory.openSession();
        animalMapper am=session.getMapper(animalMapper.class);
        return am.selectAllData();
    }

}

結果:

技術分享圖片

Maven-SSM框架整合