构建RESTful Web Service

1、项目包结构:


2、文件说明:

/**
* 使用SpringBootApplication注解,让我们不需要单独的将项目部署到web容器中去,因为spring内嵌了tomcat容器
*/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

/**
* RestController注解相当于struts中的action
*/
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
/**
* @RequestMapping("/greeting") 定义访问路径
* @RequestParam(value="desc", defaultValue="World")定义访问传参,
* 如果不定义RequestParam,那么默认是以name为键访问参数,如果不传name或者传的name是空字符串,那么name=null
* 如果定义了RequestParam,那么这里desc的值就会赋给name,如果不传des或者传的des是空字符串,那么name=W
* @param name
* @return
*/
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="desc", defaultValue="World") String name) {
if(name==null){
name="river";
}
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
build.gradle文件
group 'springguides'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE")
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile group: 'junit', name: 'junit', version: '4.12'
compile("org.springframework.boot:spring-boot-starter-web")
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('com.jayway.jsonpath:json-path')
}

3、配置运行启动的tomcat



4、响应



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值