编译器:Intellij IDEA 系统环境: MAC OS 相关技术:Maven、tomcat 7、jdk8
首先创建一个web Application项目(这里我们打算用maven引入Jersey的相关jar包,所以不用直接创建restful项目,因为 restful项目会把Jersey相关jar包下载到工程lib文件夹下)
创建完项目后我们再用Add Frameworks Support把maven项目的支持引入。
到此为止我们就已经成功创建了一个新的web项目了,可以愉快地对其coding改造了
修改pom.xml, 引入Jersey相关jar包
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>pers.marscheng.restful</groupId> <artifactId>restfulDemo</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.glassfish.jersey.containers</groupId> <artifactId>jersey-container-servlet</artifactId> <version>2.22.2</version> </dependency> </dependencies> </project>修改web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>JAX-RS Servlet</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>pers.marscheng.restful</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>JAX-RS Servlet</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping> </web-app>其中pers.marscheng.restful对应放置restful demo代码的包,/api/对应的是restful api映射的地址,一般我们不把这个地址设为/*,因为这样会覆盖默认的index地址,除非你自己重新定义了首页地址。
配置完环境之后我们就可以写一个简单的restful api了。在pers.marscheng.restful下新建Hello.java文件。
package pers.marscheng.restful; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * restful测试类 * * @author marscheng * @create 2017-07-26 下午3:19 */ @Path("hello") public class Hello { @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello(){ return "Hello,I am text!"; } @POST @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> Hello,I am xml!" + "</hello>"; } @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + "Hello,I am html!" + "</body></h1>" + "</html> "; } } @PATH对应的是我们要配置的restful api的子路劲,比如前面我们配置的是/api/*,则用户访问该API的路径就是https//:ip:port/api/hello@GET @POST对应的是用户请求资源用的HTTP方法@Produces表示返回的数据类型,如MediaType.TEXT_PLAIN对应返回文本类型将maven引入的jar包放到lib文件夹下(如果你直接通过maven把项目打成war包放到Tomcat下,这步可以不用)
在tomcat中引入项目,启动
转载于:https://www.cnblogs.com/MarsCheng/p/7245292.html