将jetty-server GET方法转换为POST方法

时间:2014-04-30 06:17:46

标签: java webserver jetty httpserver java-server

我使用java创建了一个jetty-server (org.eclipse.jetty version:9.1.0.M0)网络服务器。我的服务器代码如下。

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();
    }

}

这是内容处理程序代码:

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();
        }
    }
}

当我发送GET方法时,它完美无缺。即,http://localhost:2000/square?number=8返回输出64.但我需要一个POST方法。如何将此代码转换为处理POST请求?

1 个答案:

答案 0 :(得分:3)

你可以试试这个:

ContextHandler context = new ContextHandler();
context.setContextPath("/square");
context.setAllowNullPathInfo(true);

POST/square的请求似乎被重定向为GET /square/次请求。

另请参阅:POST request becomes GET