use of doGet() in Java to write HTML code - java

I want to write an HTML code inside Java, using a servlet. I read about the method doGet() and I wrote this simple example
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter( );
response.setContentType("text/html");
out.println("<H1>Hello from a Servlet</h2>");
But it doesn't give anything in the browser, can someone tell me what's wrong?

The standard PrintWriter which you get by calling response.getWriter(); doesn't automatically flush its buffers. It's a bug/feature.
Add out.flush() at the end of doGet().
Also note that PrintWriter.close() does not flush. It's a bug; PrintWriter/PrintStream are the only output classes which don't flush on close.
[EDIT] To make sure that no other problem confuses you, add a breakpoint in the method and run it in the debugger. You should also add the annotation #Override to make sure your method signature is correct.

It seems you don't actually override doGet. You missed the ServletException exception.

Related

Why someone calls post() method inside get() method in Servlets?

why we call post() method inside get() method in servlets?
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
Simply only because someone wants to have the same behavior disregarding the HTTP method whether it was POST or GET. So requesting resource with POST does the same as GET.
BUT: doing this - doing the same action - is quite propably wrong. Someone who does this might do it for convenience - for example wants to provide more means to access resource but does not fully understand the difference of GET vs. POST.
It is a matter of idempotency. Good explanation here.
In a nutshell GET should be used when GETting stuff and POSTing when you need to change stuff on the server side.
But what I have experienced some people use GET as long as there too much data for GET and then switch to POST without further thinking about the real difference.

getOutputStream() has already been called for this response when using PrintWriter

I'm working on this Java Sprint 3.0 application where I'm passing data to a dataTable. Everything works fine, but every so often I see this error:
ERROR [[dispatcher]] Servlet.service() for servlet dispatcher threw exception
java.lang.IllegalStateException: getOutputStream() has already been called
for this response.
Here is my code:
#PreAuthorize("hasRole('ADMIN')")
#RequestMapping(value = "/dataTable", method = RequestMethod.GET)
public void serverSide(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
response.setHeader("Cache-Control", "no-store");
PrintWriter out = response.getWriter();
out.print(dataTableService.viewUsers(request));
}
I have tried adding the following:
out.flush();
out.close();
return;
I have also tried using response.getOutputStream().print(dataTableService.viewUsers(request)) and response.getWriter().append(dataTableService.viewUsers(request)) instead of using a PrintWriter but nothing seems to fix it.
EDIT:
Here is the stacktrace:
The basics are:
headers must be written first;
then the content must be written using either getOutputStream or getWriter.
What still can go wrong:
Basic errors like using both response.getOutputStream() and response.getWriter() - very unlikely here.
Control flow:
if (...) {
... redirect
// Missing return
}
... normal output
A filter or interceptor: ordinarily unlikely; though here are annotations.
out.flush(); // OKAY
// Probably NOT OKAY: out.close();
Servlet fields being used. The service methods should be stateless in themselves.

what exactly the printWriter() object do in servlet?

public class myServlet extends httpservlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
PrintWriter out = response.getWriter();
out.println(--------"HTML CODE"------);
}
}
I'm new to servlets and web programming. While practicing, I'm stuck at some general doubt. What exactly does the PrintWriter() object do in a servlet? Just directing the HTML code to output stream?
In Java, to handle I/O operations, there are different I/O classes like Reader, Writer, InputStream, OutputStream classes etc. In Servlet, when you want to do output operation i.e., writing HTML content in web page, you need one of these classes. More info on these classes, you can get from this link.
So we create PrintWriter instance from the response and invoke its write() method to write simple HTML contents.
getWriter() method of HttpServletResponse returns a PrintWriter object which can be used to send text to client side, and yes it may be used to send html code to the client side.

Outputstream between threads

I have an ajax method on my servlet that could be running at the same time for the same user. Sorry if I use the wrong words to describe the problem but it's how I understand it so far (don't know much about threading).
Anyways here's the method
private void ajaxPartidas() throws ServletException, IOException {
//Variables necesarias
DataSource pool = (DataSource) session.get().getAttribute("pool");
Recibo registro = null;
int id = -1;
try{ id = Integer.parseInt(request.get().getParameter("id"));}catch(NumberFormatException e){}
if(id > 0){
registro = new Recibo(id);
if(!registro.obtener(pool))
registro = null;
registro.setPartidas(Partida.obtenerRegistros(pool, registro.getId()));
}
response.get().setContentType("application/json");
response.get().setHeader("Content-Type", "application/json; charset=utf-8");
response.get().getWriter().print((new Gson()).toJson(registro.getPartidas()));
}
This method is being called via ajax, it works fine the 1st time it gets called, but second time (on same id) and it returns a NullPointer on the getWriter() line. I've looked around and everyone seems to pinpoint the problem to threads. Now a little bit more of context would be that everytime the servlet enters in the
doPost(request, response)
I assign a threadlocal variable declared like so in the global vars
private static ThreadLocal<HttpServletResponse> response = new ThreadLocal<>();
and I assign it the response
Home.response.set(response);
in the doPost() method.
How would I go about making the getWriter() threadsafe?
Not sure why you're assigning the response to a class level ThreadLocal? Each new user generated request has a clean request and response object. getWriter and all methods on the servlet class are threadsafe as long as you follow the correct guidelines for using a Java Servlet. A general rule with Java Servlets is that as long as you don't use class level variables, you are thread-safe.
Instead of using a ThreadLocal, you need to pass the request and response objects as parameters to your ajaxPartidas method and then call it as you normally would. So your doPost method would look like this
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ajaxPartidas(request, response);
}
The concurrency issues are already handled by the Servlet class itself, you just need to write the business logic. See this answer in a similar thread for more details on using a Java Servlet with Ajax: https://stackoverflow.com/a/4113258/772385
Tomcat creates a new Request and Response for EVERY user request. So they are already threadsafe (unless you go in and create a new Thread). Besides, make sure you are passing "id" and is getting set properly. I think it's the "registro" object on the same line as getWriter() that's causing the NullPointerException.

Java Servlet: Specify postdata limit for request.getParameter?

I understand that the first call to getParameter will read the postdata content, if any.
Is there a way for me to limit how much postdata content would be processed into the RAM, or am I going to need to override the getParameter* methods for that to be accomplished?
I am not interested in making this a server-wide setting.
or am I going to need to override the getParameter methods for that to be accomplished?*
Yes.
For that you can use a homegrown HttpServletRequestWrapper which is injected by a Filter.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(new MyPostDataLimitingRequest((HttpServletRequest) request), response);
}
I do not believe there is a way to limit through the existing getParameter(), which is a convenience method, without extending the servlet or adding a listener to break it down for you.
You can circumvent this by parsing the input stream within your servlet directly using getInputStream() or getReader(), but I believe this invalidates further calls to getParameter() for the rest of that request; you'll need to consume the rest of the input through your selected method.
It's not elegant, but it works.

Categories