在创建工程时选择基于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