Spring MVC:從零開始

前言:以前作的項目包括網上一些教程都是集不少配置和功能一塊兒,有時候使用起來就比較亂。週末抽空從零搭建項目,一步步加新功能,也是讓本身對spring配置有個更全面的瞭解。主要是對流程和配置的介紹,具體業務功能就比較省略。html

1、搭建Spring MVC項目java

這裏是初步搭建完成的項目架構web

說到maven,這裏推薦阿里雲的鏡像地址,若是不在公司或者公司沒有私服的狀況下,可使用,下載賊快。spring

<mirror>
  <id>alimaven</id>
  <name>aliyun maven</name>
  <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  <mirrorOf>central</mirrorOf>        
</mirror>

一、Maven配置: 
引入spring有關的包,這裏咱們暫時只用到spring-core和spring-webmvc和json包apache

<spring.version>4.3.3.RELEASE</spring.version>

<!--spring配置 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>
     <!--json配置 -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>${json.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${json.version}</version>
    </dependency>

二、Spring配置json

spring確定掃不了配置文件,spring-core.xml,放在resources目錄下api

<?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-3.0.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">


<!-- 啓用spring mvc 註解 -->
<mvc:annotation-driven />
<!-- 開啓註解掃描-->
<context:component-scan base-package="com.tan.self" />

<!-- json配置-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
        </list>
    </property>
</bean>

<!-- viewResolver配置-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/"/>
     <property name="suffix" value=".jsp"/>
</bean>
</beans>
  • < mvc:annotation-driven/> 會自動註冊DefaultAnnotationHandlerMapping與AnnotationMethodHandlerAdapter 兩個bean,是spring MVC爲@Controllers分發請求所必須的
  • < context:component-scan base-package=」com.tan.self」 />用於開啓註解掃描
  • RequestMappingHandlerAdapter配置,配置json轉換,用於spring中的@Responsebody註解,能夠將返回值轉換爲json,注意,這裏是spring4.x版本所用的配置,若是是低版本的話,用的是AnnotationMethodHandlerAdapter
  • viewResolver配置,配置requestMapping返回頁面的前綴和後綴

引用spring官方的說明:spring-mvc

< context:annotation-config> declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on. 
< mvc:annotation-driven /> is actually rather pointless. It declares explicit support for annotation-driven MVC controllers (i.e.@RequestMapping, @Controller, etc), even though support for those is the default behaviour.tomcat

使用< context:component-scan/>後,該配置項其實也包含了自動注入上述processor的功能,便可將< context:annotation-config/>省去。服務器

三、web.xml配置

  • CharacterEncodingFilter字符過濾器,用於設置項目編碼
  • ContextLoaderListener用於啓動Web容器時,自動裝配ApplicationContext的配置信息
  • DispatcherServlet用於路由分發
  • classpath:指定爲咱們配置的spring-core.xml,若不予配置的話,默認是/WEB-INF/applicationContext.xml

    <!-- 字符編碼過濾器-->
        <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>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>characterEncodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    <!-- contextLoaderListener配置  啓動Web容器時,自動裝配ApplicationContext的配置信息-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-core.xml</param-value>
    </context-param>
    
    <!-- dispatcherServlet配置-->
    <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-core.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

四、示例代碼

ApiController:

@Controller
@ResponseBody
@RequestMapping("api")
public class ApiController {

@RequestMapping("getJson")
public RestResponse getApiJson() {

    RestResponse restResponse = new RestResponse();
    restResponse.setCode(200);
    restResponse.setMsg("操做成功");
    logger.info("獲取json數據接口");
    return restResponse;
}
}

WebController:

@Controller
@RequestMapping("web")
public class WebController {

@RequestMapping("index")
public String webTest() {
    return "index";
}

RestResponse:

public class RestResponse {

private int code;
private String msg;
private Object data;

public int getCode() {
    return code;
}

public void setCode(int code) {
    this.code = code;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}

public Object getData() {
    return data;
}

public void setData(Object data) {
    this.data = data;
}
} 


index.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<html>
歡迎光臨
</html>

2、項目配置Jetty啓動

項目配置和基礎代碼都已完畢,如今須要的是將web項目部署跑起來。通常而言,會使用tomcat做爲服務器,進行部署,這裏咱們推薦Jetty,Jetty是一款輕量級的服務器,能夠以插件的形式進行安裝,很是便捷。

一、引入jetty插件

修改pom,增長插件引入:

<build>
    <plugins>
        <!--jetty -->
        <plugin>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>7.6.14.v20131031</version>
            <configuration>
                <connectors>
                    <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
                        <port>80</port>
                    </connector>
                </connectors>
                <stopKey>shutdown</stopKey>
                <stopPort>9090</stopPort>
            </configuration>
        </plugin>
        <!--編譯版本 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

這裏配置了兩個plugin,一個是jetty-maven-plugin,可指定port爲啓動端口,一個是maven-compiler-plugin,指定編譯版本,避免不一樣電腦不一樣環境下編譯版本的差別(筆者的idea以前用於開發的時候,某項目編譯打包版本一直是source1.5,必須每次在項目配置裏面進行更改,很是繁瑣,這裏配置了source,就能夠完美解決這種問題)

二、jetty啓動

用jetty啓動web項目也很方便,以idea爲例,在Run–>Edit Configurations中新增Maven啓動方式,配置以下:

運行之:控制檯打印以下,啓動成功。

訪問 http://localhost/api/getJson 查看返回的json數據

{
code: 200,
msg: "操做成功",
data: null
}

訪問 http://localhost/web/index 查看返回的頁面

歡迎光臨

3、集成Log4j2日誌

項目搭建完畢後,筆者就集成了log4j的日誌,但用的是slf4j和log4j1.x的版本,而後在log4j官網上看到:

On August 5, 2015 the Logging Services Project Management Committee announced that Log4j 1.x had reached end of life. For complete text of the announcement please see the Apache Blog. Users of Log4j 1 are recommended to upgrade to Apache Log4j 2.

原來log4j1.x版本自從15年起就已經再也不維護了,官方也一直主推2.x版本,並且和之前方式也不大同樣,因而改成Log4j2。

一、引入依賴

這裏咱們仍是經過slf4j來使用log4j2,slf4j是一個接口工具類,經過它能夠方便的切換log4j、logback等不一樣日誌實現,推薦這種方式。

<slf4j.version>1.7.7</slf4j.version>
    <log4j.version>2.5</log4j.version>
  <!--slf4j log4j2配置 -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency> <!-- 橋接:告訴Slf4j使用Log4j2 -->
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-slf4j-impl</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
        <version>${log4j.version}</version>
    </dependency>

二、log4j2配置

在resources目錄下新建log4j2.xml文件,這是官方默認的路徑和文件名。

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="error" monitorInterval="600">
    <appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
        </Console>

    <RollingFile name="RollingFile" fileName="/data/logs/web.log"
                 filePattern="/data/logs/$${date:yyyy-MM}/web-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout pattern="%d{yyyy-MM-dd 'at' HH:mm:ss z} %-5level %class{36} %L %M - %msg%xEx%n"/>
        <Policies>
            <TimeBasedTriggeringPolicy modulate="true" interval="1"/>
        </Policies>
    </RollingFile>
</appenders>

<loggers>
    <root level="info">
        <appender-ref ref="RollingFile"/>
        <appender-ref ref="Console"/>
    </root>
</loggers>
</configuration>

具體的配置和Log4j1.x有點不太同樣,但大同小異,這裏咱們主要介紹monitorInterval=」600」這個屬性,以前咱們的日誌配置文件若是修改日誌級別或者其餘,須要從新啓動項目,尤爲對於已經上線的項目,很是不友好,而log4j配置裏面新增的這一屬性就是能夠在不啓動項目的狀況下修改配置,monitorInterval是指log4j多久去從新讀取一下配置,單位爲秒,這裏就是十分鐘檢測一次。

相關文章
相關標籤/搜索