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语句