編譯器:Intellij IDEA
系統環境: MAC OS
相關技術:Maven、tomcat 七、jdk8html
首先建立一個web Application項目(這裏咱們打算用maven引入Jersey的相關jar包,因此不用直接建立restful項目,由於 restful項目會把Jersey相關jar包下載到工程lib文件夾下)java
建立完項目後咱們再用Add Frameworks Support把maven項目的支持引入。
web
到此爲止咱們就已經成功建立了一個新的web項目了,能夠愉快地對其coding改造了apache
修改pom.xml, 引入Jersey相關jar包api
<?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.xmltomcat
<?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
配置完環境以後咱們就能夠寫一個簡單的restful api了。在pers.marscheng.restful下新建Hello.java文件。app
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> "; } }
將maven引入的jar包放到lib文件夾下(若是你直接經過maven把項目打成war包放到Tomcat下,這步能夠不用)
maven
在tomcat中引入項目,啓動
ide