1. 程式人生 > >SSM輕鬆寫出Restful風格介面

SSM輕鬆寫出Restful風格介面

1.新建web專案
src下新建包com.company

二 . 匯入jar包
aopalliance-1.0、aspectjweaver-1.7.4、commons-dbcp2-2.1.1、druid-0.2.19、fastjson-1.2.32、jackson-annotations-2.9.1、jackson-core-2.9.1、jackson-databind-2.9.1、javaee-api-7.0、mybatis-3.3.0、ojdbc6、slf4j-api-1.8.0-beta0、slf4j-log4j12-1.8.0-beta0、spring-aop-4.3.12.RELEASE、spring-beans-4.3.12.RELEASE、spring-context-4.3.12.RELEASE、spring-context-support-4.3.12.RELEASE、spring-core-4.3.12.RELEASE、spring-expression-4.3.12.RELEASE、spring-jdbc-4.3.12.RELEASE、spring-oxm-4.3.12.RELEASE、spring-tx-4.3.12.RELEASE、spring-web-4.3.12.RELEASE、spring-webmvc-4.3.12.RELEASE。

http://mvnrepository.com/search?q= 上逐一下載匯入(WEB-INF/lib)
三 . src下新建log4j.properties檔案

 log4j.rootLogger=DEBUG,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 = ssm.log #定義檔案最大大小 log4j.appender.File.MaxFileSize = 10MB # 輸出所以日誌,如果換成DEBUG表示輸出DEBUG以上級別日誌
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}][%c]%m%n

四. src下新建ssm.log
五. src下新建資料庫配置檔案jdbc.propertis

driver=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@XXX
username=test  
password=psw  
#定義初始連線數  
initialSize=0  
#定義最大連線數  
maxActive=20  
#定義最大空閒  
maxIdle=20  
#定義最小空閒  
minIdle=1  
#定義最長等待時間  
maxWait=60000  

六. src下新建spring-mybatis.xml,顧名思義,即配置資料庫和spring(含xml對映資訊和對映檔案對應的dao介面)

<?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">
        <!-- 配置資料來源 ,使用的alibba的資料庫-->
     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <!-- 基本屬性 url、user、password -->        
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${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" />

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

    <!-- 配置mybatis的對映檔案 -->  
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
        <property name="dataSource" ref="dataSource" />  
        <!-- 自動掃描mapping.xml檔案 -->  
        <property name="mapperLocations" value="classpath*:com/company/mapping/*.xml"></property>  
    </bean>   
     <!-- DAO介面所在包名,Spring會自動查詢其下的類 -->  
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.company.dao" />  
        <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>

七. src下新建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.propertis"/>
    </bean>
    <import resource="classpath*:spring-mybatis.xml" />

</beans>

八. com.company.pojo下新建類User

public class User {
    public String user_id;
    public String user_name;
}

九.com.company.dao下新建 對映檔案對應的UserMapper介面

public interface UserMapper {
    public User findByUserId(String userId);  
}

十.com.company.mapping下新建對映檔案UserMapping.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">  
<!--這塊等於dao介面的實現 com.company.dao.UserMapper即為對映的介面-->  
<mapper namespace="com.company.dao.UserMapper">  
 <!-- findByUserId必須和介面中的方法名一樣 返回一個User就是剛才的別名-->  
 <select id="findByUserId" parameterType="String" resultType="com.company.pojo.User">  
    select * from emp_data where user_id=#{userId}  
    </select>  
</mapper>  

ps:第九、十步com.company.dao和com.company.mapping已經在第六步spring-mybatis.xml進行過配置,是不是很方便?
十一.在com.company.service下新建Spring介面類IUserService

public interface IUserService {
    public User getUserById(String userId);  
}

十二. 在com.company.service.impl新建上一步介面的實現類

@Service("userService")  
public class UserServiceImpl implements IUserService{
    @Resource  
    private UserMapper userDao;  
    @Override
    public User getUserById(String userId) {
        return userDao.findByUserId(userId);
    }
}

十三.下面就可以寫控制器了,在com.company.controller下新建控制類UserCtr

@Controller
@RequestMapping(value = "user/")  
public class UserCtr {

    @Autowired  
    private IUserService userService;

    @RequestMapping(value = "queryUserById/{userId}", method = RequestMethod.GET,produces={"application/json;charset=UTF-8"})  
     @ResponseBody  
     public User queryUserById(@PathVariable("userId") String userId) {  
         User user = userService.getUserById(userId);

         return user;  
     }  

}

十四. 控制器掃描注入,在src下新建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:util="http://www.springframework.org/schema/util"
  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
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-2.5.xsd">

    <!-- 掃描controller -->
   <context:component-scan base-package="com.company.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!-- 掃描實現類 -->
     <context:component-scan base-package="com.company.service.impl" />

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

     <bean     
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter ">
        <property name="messageConverters">
            <util:list id="beanList">
                <ref bean="mappingJacksonHttpMessageConverter" />
            </util:list>
        </property>
    </bean>
    <bean id="mappingJacksonHttpMessageConverter"
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8</value>
            </list>
        </property>
    </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>

十五. 在web.xml中引入spring-mvc.xml和applicationContext.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_3_0.xsd"  
    version="3.0">  
    <display-name>springMVC</display-name>  

     <!-- 該servlet為tomcat,jetty等容器提供,將靜態資源對映從/改為/static/目錄,如原來訪問 http://localhost/foo.css ,現在http://localhost/static/foo.css -->  
    <!-- 不攔截靜態檔案 -->  
    <servlet-mapping>  
        <servlet-name>default</servlet-name>  
        <url-pattern>/js/*</url-pattern>  
        <url-pattern>/css/*</url-pattern>  
        <url-pattern>/images/*</url-pattern>  
        <url-pattern>/fonts/*</url-pattern>  
    </servlet-mapping> 

    <!-- Spring和mybatis的配置檔案 -->  
    <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>classpath*:applicationContext.xml</param-value>  
    </context-param>  
    <!-- 編碼過濾器 -->  
    <filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <async-supported>true</async-supported>  
        <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>encodingFilter</filter-name>  
        <url-pattern>/*</url-pattern>  
    </filter-mapping>  

    <!-- 新增日誌監聽器 -->
    <context-param>
        <param-name>logbackConfigLocation</param-name>
        <param-value>classpath*:logback.xml</param-value>
    </context-param>
    <!-- Spring監聽器 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
    <!-- 防止Spring記憶體溢位監聽器 -->  
    <listener>  
        <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  
    </listener>  

    <!-- Spring MVC servlet核心配置 -->  
    <servlet>  
        <servlet-name>dispatcherServlet</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>  
        <async-supported>true</async-supported>  
    </servlet>  
    <servlet>  
        <servlet-name>DruidStatView</servlet-name>  
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>  
    </servlet>  

    <servlet-mapping>  
        <servlet-name>dispatcherServlet</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping>  

    <servlet-mapping>  
    <servlet-name>DruidStatView</servlet-name>  
    <url-pattern>/druid/*</url-pattern>  
</servlet-mapping>  

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

</web-app>