Reputation: 2773
I created a java
web server using jetty-server (org.eclipse.jetty version:9.1.0.M0)
. My server code is as follows.
package webservice;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ContextHandler;
public class ServerClass {
public void startServer() throws Exception{
int port=2000;
Server server= new Server(port);
ContextHandler context = new ContextHandler();
context.setContextPath("/square");
context.setResourceBase(".");
context.setClassLoader(Thread.currentThread().getContextClassLoader());
context.setHandler(new ContentHandler1());
server.setHandler(context);
server.start();
}
public static void main(String []args) throws Exception{
ServerClass server= new ServerClass();
server.startServer();
}
}
And here is the content handler code:
package webservice;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
class ContentHandler1 extends AbstractHandler{
public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException{
try{
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_OK);
baseRequest.setHandled(true);
int number = Integer.parseInt(request.getParameter("number"));
response.getWriter().println(number*number);
}catch(Exception e){
e.printStackTrace();
}
}
}
When i send GET
method, it works perfect. ie, http://localhost:2000/square?number=8
returns output 64. But i need a POST
method. How can i convert this code to process POST
request?
Upvotes: 1
Views: 4647
Reputation: 5315
You can try this:
ContextHandler context = new ContextHandler();
context.setContextPath("/square");
context.setAllowNullPathInfo(true);
It looks like POST
requests to /square
are redirected as GET
requests to /square/
.
See also: POST request becomes GET
Upvotes: 4