- So first of all we are going to create a Maven web project.
- Go to this Link For Project Creation: Create Maven Base Web Project.
- Open pom.xml file add dependencies. Dependencies mean the jars file that project need. For example we need blow jars for our project.
- commons-lang-2.3.jar
- jaxb-api-2.1.jar
- jaxb-impl-2.1.4.jar
- stax-api-1.0-2.jar
- jsr311-api-1.1.jar
- slf4j-api-1.5.11.jar
- slf4j-jdk-1.5.11.jar
- wink-common-<version #>.jar
- wink-server-<version #>.jar
- Instead of adding these jars in project and updating with change inversions, we are using maven which will do this work for us on chnage in pom.xml
- We need few plugins for maven as well to run this project on Apache tomcat
- So pom file is here pom.xml.
- Now go to src/main/webapp/WEB_INF/web.xml
- Add internal servlet and servlet mapping for jx-rs.
- Register the web service with javax.ws.rs.Application.
- I am making a file Services.java which is extending javax.ws.rs.Application.It is registering our service class MainServices.clas with rest servlet
- Now write a web service in java file. My service file name is MainServices.java.
- @Path("/mainServices") annotation on top of Class MainServices is the path to this web service from the Rest servlet (servlet declare in web.xml).
- This thing means this /mainServices will append with path of Rest Servlet which is (/service/ => in web.xml).
- @GET @Path("/hellow_world" ) @Produces(MediaType.APPLICATION_JSON)
public String helloWorld(){}
- Method helloWorld() is working as separate service and its path on url is /hellow_world. And this path is append with the path of Class MainServices "/mainServices".
- So path to this service is "BASER_URL + /service/mainServices/hellow_world"
- @GET means the method to access this service is GET.
- @Produces(MediaType.APPLICATION_JSON) means this is service is returning json.
- To run project Right click the project go to Run As -> install then Right click project -> Run As -> click -> Build -> tomcat:run.
- So we can access this service with this url. http://localhost:8080/maven.work/service/mainServices/hellow_world
- No take a look on a web service (/user_details) which is getting the data from html forms and methods we are using is post.
- It is consuming (taking input) the form data Content Type = application/x-www-form-urlencoded
- @FormParam("userName") String name. The annotation @FormParam is mapping html form field = userName to Java variable name.
- You can access the web service with the blow url http://localhost:8080/maven.work/service/mainServices/user_details
You can get source code from this link Source Code
No comments:
Post a Comment