I am a complete beginner in web programming. I created an application with Eclipse Java EE and a Tomcat server running in localhost.
The goal of the application is to get information from a client and send back other information.
I developped a servlet and implement a doPost() method that works perfectly. I get information that I saved in a bean named USSDPull and write in a text file named log.txt.
public void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
USSDPull ussdpull = new USSDPull();
ussdpull.setUssdstring(request.getParameter("ussdstring"));
ussdpull.setSessionid(Integer.parseInt(request.getParameter("sessionid")));
ussdpull.setMsisdn(request.getParameter("msisdn"));
ussdpull.setUssdcode(request.getParameter("ussdcode"));
ussdpull.setEncoding(Integer.parseInt(request.getParameter("encoding")));
response.setContentType("text/text");
response.setCharacterEncoding( "UTF-8" );
PrintWriter out = response.getWriter();
out.flush();
out.println("POST received : " + ussdpull.getUssdstring()+" "+ussdpull.getSessionid()+" "+ussdpull.getMsisdn()+" "+ussdpull.getUssdcode()+" "+ussdpull.getEncoding());
//WRITE IN FILE
FileWriter fw = new FileWriter("D:/Users/Username/Documents/log.txt", true);
BufferedWriter output = new BufferedWriter(fw);
output.write(dateFormat.format(date)+";"+ussdpull.getUssdstring()+";"+ussdpull.getSessionid()+";"+ussdpull.getMsisdn()+";"+ussdpull.getUssdcode()+";"+ussdpull.getEncoding()+"\n");
output.flush();
output.close();
}
I need the servlet to send back 2 specific booleans and 1 string to the client. I don't know how to proceed. Is it possible to use the HttpServletResponse to send the data? Or do I need to find a way to "call" the doGet() method?
The HttpServletResponse
itself doesn't give you a way to write data back to the client other than some headers, such as the response code.
However, it has a method called getOutputStream
and a method getWriter()
that give you resp. an OutputStream
or a PrintWriter
. You can use these to write data to the response.