Jetty is used in a wide variety of projects and products, both in development and production. Jetty can be easily embedded in devices, tools, frameworks, application servers, and clusters. See the Jetty Powered page for more uses of Jetty.Here we want to use it as an embedded web server that runs with our application.
You should first download the required jetty jar files and import them. Basically you can just down jetty all and use it there will no problem. For now the latest version is the 9.1 and it is the one we will use.Also Gson will be used and you should download it from this link.
First create a class that extends Server and by giving port to its constructor we will be able to start it easily.
By using context.addServlet() method you can add servlets easily.addServlet() takes two parameters and the first one is the class name that will be called when this servlet called and the second one is the name how you will call it.
will be called as localhost:portNumber/test/SaveName
GET methods are defined using doGet and POST methods are defined with doPost.SaveName and GetName classes are
And the get method we will use:
It’s all that simple and now you only need to start to jetty server from your main class.
When your application is running you can call localhost:8080/test/GetName and it will return to you a json object like this
You can use HTTP:POST to send data to server by using localhost:8080/test/SaveName and your post parameters should be named as “name” and “surName”.It is the simplest thing you can do with jetty embedded server.I use it to get data from database using parameters and posting data into database and it’s really fast and lightweight which makes it really feasible.