首页 > 学院 > 开发设计 > 正文

Intellij IDEA创建基于Gradle的SpringMVC工程

2019-11-06 08:57:07
字体:
来源:转载
供稿:网友

在创建工程时选择基于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. */@RestControllerpublic 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


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表