我想要一个代码从Java代码调用servlet。我的代码如下。 Servlet没有被调用,

时间:2018-07-04 05:46:48

标签: java servlets

package test;
import java.io.ObjectOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {

public static void main(String[] args) {

    URL url;
    try {
        url = new URL("http://localhost:8081/Projectt/ServletTest");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
        out.writeObject("test");
        out.flush();
        System.out.println("------------");
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

这是我的servlet代码

import java.io.IOException;
import java.io.ObjectInputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/ServletTest")
public class ServletTest extends HttpServlet {
     private static final long serialVersionUID = 1L;
     public ServletTest() {
         super();
     }
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ObjectInputStream in = new ObjectInputStream(request.getInputStream());
    try {
        System.out.println("In get : " + (String) in.readObject());
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    System.out.println("End of servlet");
}
}

我想从Java代码调用servlet。以上是我的代码。 端口是8081。给定的URL是从浏览器触发的,而不是我的代码。 仅从Test类而不是从TestServlet执行println语句

1 个答案:

答案 0 :(得分:0)

在您进行一些输入(即获取HttpURLConnection的输入流或获取响应代码)之前,什么都不会发生。您至少需要致电getResponseCode()