写在前面
- 重要学习原理
- 先看官方文档,然后可以搜索博客加以配合
Restful 简介
全称REpresentational State Transfer的缩写。是基于 WEB标准的软件架构,使用HTT协议处理数据通信。以资源为中心,其中每个组成部分都是一个资源,并且资源通过使用 HTTP 标准方法的公共接口访问。EST 由 Roy Fielding 在 2000 年首次提出。
参考
操作步骤(本次是以jersy为主)
先决条件 安装好maven
- 运行mvn下载jersy官方的web app骨架
mvn archetype:generate -DarchetypeArtifactId=jersey-quickstart-webapp -DarchetypeGroupId=org.glassfish.jersey.archetypes -DinteractiveMode=false -DgroupId=com.example -DartifactId=simple-service-webapp -Dpackage=com.example -DarchetypeVersion=2.26
User.java
package com.example;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String name;
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + "]";
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User() {
super();
}
}
RestfulHelloWorld.java
package com.example;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
@Path("/helloworld")
public class RestfulHelloWorld {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayHelloWorld() {
return "Hello World!";
}
@GET
@Path("/{param}")
@Produces("text/plain;charset=UTF-8")
public String sayHello2UserByText(@PathParam("param") String username) {
return "Hello " + username;
}
@GET
@Path("/get")
@Produces(MediaType.APPLICATION_JSON)
public User sayHelloToUserByJson(@QueryParam("username") String username) {
User user = new User();
user.setId(1);
user.setName(username);
return user;
}
}
3 .结果
记录:
骨架自带的web.xml, 骨架配置了扫描包
<?xml version="1.0" encoding="UTF-8"?>
<!-- This web.xml file is not required when using Servlet 3.0 container,
see implementation details http://jersey.java.net/nonav/documentation/latest/jax-rs.html -->
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Jersey Web Application</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.example</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey Web Application</servlet-name>
<url-pattern>/webapi/*</url-pattern>
</servlet-mapping>
</web-app>