I am trying to write a servlet. And I want to write a text in a main method, and get it inside of servlet. But when I run write() method it does not trigger any servlet method.
I am expecting my servlet's doPost() method to be triggered when I run output.flush() in my main method. But it does not. Can you help me what is wrong? PS: I looked for similar topics. But they did not work either. (How to use java.net.URLConnection to fire and handle HTTP requests?) My code is here:
package com.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServ extends HttpServlet{
private static final long serialVersionUID = -8318963033521229815L;
@Override
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
//some code here
}
@Override
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException{
//some code here
}
}
I call servlet from this Main Class
package com.test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
public class Main {
static String charset = "UTF-8";
public static void main(String[] args) throws IOException {
URLConnection connection = new URL("http://localhost:8080/servlet-example/Demo1").openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + Charset.defaultCharset());
try {
OutputStream output = connection.getOutputStream();
output.write("test".getBytes(charset));
output.flush();
// InputStream inputStream = connection.getInputStream();
}catch(Exception e){
e.printStackTrace();
}
}
}