1. 程式人生 > >Intellij IDEA建立基於Gradle的SpringMVC工程

Intellij IDEA建立基於Gradle的SpringMVC工程

在建立工程時選擇基於Gradle的工程,勾選Web
這裡寫圖片描述
如果選擇使用gradle wrapper導致下載很慢,可以選擇本地安裝的gradle
這裡寫圖片描述
新增tomcat(Run->Edit Configuration),最後點選綠三角執行工程
這裡寫圖片描述
這裡寫圖片描述
build.gradle中新增Spring MVC依賴,並同步工程

group 'cn.iotguard'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'war'


repositories {
    mavenCentral()
}

dependencies {
    compile 'org.springframework:spring-webmvc:4.3.6.RELEASE'
testCompile group: 'junit', name: 'junit', version: '4.11' }

接下來要開始編寫Java程式碼了,在main下建立java資料夾,並在java資料夾下建立一個package,如下
這裡寫圖片描述
在package下建立一個Java類檔案,內容如下:

package cn.iotguard.demo.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import
org.springframework.web.bind.annotation.RestController; /** * Created by caowentao on 2017/2/28. */ @RestController public class DemoController { @RequestMapping("/greeting/{name}") public String greeting(@PathVariable("name") String name) { return "hello, " + name; } }

此時如果訪問http://localhost:8080/greeting/caowentao

,瀏覽器返回404錯誤。開啟Project Structure,找到Web Gradle模組,並點選Deployment Descriptors欄右側的加號新增web.xml檔案。注意web.xml檔案應該放到webapp目錄下的WEB-INF目錄下。
這裡寫圖片描述
在web.xml檔案中新增如下對映資訊

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

此時訪問http://localhost:8080/greeting/caowentao,tomcat返回異常資訊,nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/dispatcher-servlet.xml]。因此還需要在WEB-INF目錄中建立一個dispatcher-servlet.xml檔案(一個Spring Config檔案)。
這裡寫圖片描述
內容如下:

<?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="cn.iotguard.demo.controller"></context:component-scan>
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

最後執行,訪問http://localhost:8080/greeting/caowentao,成功返回hello, caowentao