Restful 是一个概念,Rest是一个架构,与其唯一绑定的实例就是http。
关于restful:https://www.runoob.com/w3cnote/restful-architecture.html
内容来源于spring官网:https://spring.io/guides/gs/rest-service/
使用 Spring/SpringBoot/Maven/Tomcat
1.使用IDEA建立Maven项目
创建完之后在src/main/java下创建包 hello
目录结构为:
└── src
└── main
└── java
└── hello
配置pom.xml
4.0.0
lsl
RestfulWebServiceHelloworld
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-parent
2.1.6.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.jayway.jsonpath
json-path
test
1.8
org.springframework.boot
spring-boot-maven-plugin
其中要根据自己的设置配置groupId和artifactId
关于插件,官网中如此描述:
The Spring Boot Maven plugin provides many convenient features:
It collects all the jars on the classpath and builds a single, runnable "über-jar", which makes it more convenient to execute and transport your service.
It searches for the public static void main()
method to flag as a runnable class.
It provides a built-in dependency resolver that sets the version number to match Spring Boot dependencies. You can override any version you wish, but it will default to Boot’s chosen set of versions.
2.在包hello下编写代码:
src/main/java/hello/Greeting.java
package hello;
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;
}
}
既然作为网站服务器,必然要有数据传输及数据传输格式,在此使用json将对象实例转换为json格式并进行传输。
具体过程为:1.得到访问网站资源的具体格式,如http://localhost:8080/greeting?name=User
2.通过解析该请求格式返回相对应的内容,如对应的Greeting的对象实例
spring使用jackson JSON自动将对象转化为json格式,非常方便。
Spring uses the Jackson JSON library to automatically marshal instances of type Greeting
into JSON.
src/main/java/hello/GreetingController.java
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
其中,注解@RequestMapping确保http请求映射到方法greeting()
The @RequestMapping
annotation ensures that HTTP requests to /greeting
are mapped to the greeting()
method.
注解@RequestMapping默认映射所有http请求,但是也可以通过@RequestMapping(method=GET)这种方法确认固定的请求参数
@RequestMapping
maps all HTTP operations by default. Use @RequestMapping(method=GET)
to narrow this mapping.
注解@RequestParam
将请求查询的value(变量)与具体的参数变量绑定,当使用?name=User这种方式访问资源时匹配到value=name的情况,于是将本地方法中具体的参数name赋值为User,也就是说,访问者知道服务器有name这么一个参数并且想对这个参数赋值,于是使用?name=User这种方式,而服务器知道有name被传进来了,进行具体的赋值并返回对应的具体的数据(对象)。如果没有则使用默认值。
@RequestParam
binds the value of the query string parameter name
into the name
parameter of the greeting()
method. If the name
parameter is absent in the request, the defaultValue
of "World" is used.
注解@RestController表名该类作为一个控制器返回具体的实例域(实例对象)而不是一个单一的视图
传统的MVC机制返回单一固定的视图(view),而Restful Web Service 控制器(Controller)可以动态(依据需求)返回相应页面
Greeting类的传输必须使用JSON格式,spring会对此进行自动的转化。
3.使程序可执行
src/main/java/hello/Application.java
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
//注解@SpringBootApplication包含许多其他注解,无需配置xml文件即可自动配置获取classpath,bean,执行main()
@SpringBootApplication
public class Application {
public static void main(String[] args) {
//SpringApplication.run(Application.class, args)该方法自动运行应用程序,无需配置web.xml或其他xml文件
//该应用是100%纯java应用程序,SpringBoot自动帮你解决许多配置问题
SpringApplication.run(Application.class, args);
}
}
部署应用程序,建立jar文件或者war文件,这里先略过,详情自查
直接执行Application,出现如下界面
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.6.RELEASE)
2019-06-26 17:25:09.098 INFO 460 --- [ main] hello.Application : Starting Application on DESKTOP-DF9BL8S with PID 460 (started by lsl in H:\练习\java\javaProject\RestfulWebServiceHelloWorld)
2019-06-26 17:25:09.114 INFO 460 --- [ main] hello.Application : No active profile set, falling back to default profiles: default
2019-06-26 17:25:10.630 INFO 460 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2019-06-26 17:25:10.697 INFO 460 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2019-06-26 17:25:10.697 INFO 460 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-06-26 17:25:10.864 INFO 460 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2019-06-26 17:25:10.864 INFO 460 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1672 ms
2019-06-26 17:25:11.082 INFO 460 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2019-06-26 17:25:11.286 INFO 460 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2019-06-26 17:25:11.301 INFO 460 --- [ main] hello.Application : Started Application in 3.199 seconds (JVM running for 4.314)
说明执行成功,当然,可以看到使用的是TomcatWebServer,所以如果不成功应该先安装一个Tomcat
然后在浏览器输入http://127.0.0.1:8080/greeting
或者http://127.0.0.1:8080/greeting?name=lsl98等等
出现页面内容
{"id":3,"content":"Hello, lsl98!"}
页面log是Spring log,也是很骚气的。
以上,也算搭建了一个最最基本的后台服务器了(未部署)。