Intellij IDEA建立基於Gradle的SpringMVC工程
阿新 • • 發佈:2018-11-02
在建立工程時選擇基於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
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