Can I send error messages after committing data to HttpServletResponse - java

everyone.
If an error is occurred after committing a part of data to HttpServletResponse,
can I send error messages or replace http status code?
I investigated some functions (sendError, sendStatus, etc.), but I wasn't able to find a solution.
It's usual, isn't it?
If so, servers need to store all data before sending a lot data.
I think that servers can never have enough memories.
p.s.
I must send a lot data such as video data. It's so big data, so I don't want to store a lot data before sending. Umm :-(

You can try to increase the buffer and reset it if error occurs. This could help you to "patch" your code. But with video-content it could be probably difficult.
You can experiment with the following code.
http://localhost:8080/BufferedResponse?flash
http://localhost:8080/BufferedResponse
The Servlet:
package testingThings;
import java.io.IOException;
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("/BufferedResponse")
public class BufferedResponse extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().println("buffer size: " + response.getBufferSize());
response.setStatus(HttpServletResponse.SC_OK);
String flash = request.getParameter("flash");
if (flash != null) {
response.flushBuffer();
}
if (response.isCommitted()) {
response.getWriter().println("buffer was commited.");
response.getWriter().println("it is too late change the response");
}
else {
response.resetBuffer();
response.getWriter().println("buffer reseted.");
response.getWriter().println("response and status code were changed");
response.setStatus(HttpServletResponse.SC_FOUND);
}
}
}
Or like others suggested, separate the logic from the view.
At least you can process the data, write "log" (as preparation for response). If everything was ok and no error occurs, write the "log" in the response.

Related

how the getCookies() function will call the cookies that are stored in another java class

package com.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/srv1")
public class TestSrv1 extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
Cookie cookie1,cookie2,cookie3,cookie4;
cookie1=new Cookie("ts", "hyd");
cookie2=new Cookie("kdp", "kadapa");
cookie3=new Cookie("ka", "blr");
res.addCookie(cookie1);
res.addCookie(cookie2);
//cookie is valid for 1hr reagardless of wheather user quites the browser,reboots computer or whatever
cookie4=new Cookie("vjw", "vijayawada");
cookie3.setMaxAge(3600);
cookie4.setMaxAge(3600);
res.addCookie(cookie3);
res.addCookie(cookie4);
PrintWriter pw=res.getWriter();
pw.println("added cookies successfully");
}
}
here i am creating the cookies in one java class and calling the same cookies from other class using req.getCookies() function how will the request object gets all the cookie objects that are created in the previous class with out the reference of that class.
Cookies are present at client side so when ever we create the cookies obj and add the values into cookies object those values are stored into the cookies object at client side so whether you call those cookies object in first servlet or second servlet or any other servlet the data is getting retrieved from the client only using req.getCookies() method.

Web servlet error by using html code in get method

I am new to web programming. I am using this simple code in my get method
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
I am getting the below error while clicking on run on server
enter image description here
Note: When i removed the html code, the servlet is working fine.Is it my Html code problem or any tomcat sevrver issue.
The servlet is in my package cs3220homework and servlet name is #WebServlet("/MainFolder").
I tried everywhere to look for the issue and i was not able to find it.If its duplicate please let me know.
Thanks for your reply
Harminder
Its working fine. App is named Test and Servlet class is also named Test. This is the url http://localhost:8080/Test/Test
package foo;
import java.io.IOException;
import java.io.PrintWriter;
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("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType( "text/html" );
PrintWriter out = response.getWriter();
out.println( "<html><head><title>Guest Book</title></head><body>" );
out.println(" </body></html> ");
}
}

RemoteApi calls from servlet not loading in local app engine app

I'am trying this example https://cloud.google.com/appengine/docs/java/tools/remoteapi
Everything works fine if I run script as java application, but when I do it as servlet it always loads forever and doesn't throw any errors. Also works fine on localhost. Also I noticed it happens when query is made, when I comment it out (datastore.put), servlet loads instantly.
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.tools.remoteapi.RemoteApiInstaller;
import com.google.appengine.tools.remoteapi.RemoteApiOptions;
#SuppressWarnings("serial")
public class Gae_java_Servlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
RemoteApiOptions options = new RemoteApiOptions()
.server("java-dot-project.appspot.com", 443)
.useApplicationDefaultCredential();
RemoteApiInstaller installer = new RemoteApiInstaller();
installer.install(options);
try {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
System.out.println("Key of new entity is " +
datastore.put(new Entity("Hello Remote API!")));
} finally {
installer.uninstall();
}
}
}
I figured it out, needed to use RemoteApiOptions().useServiceAccountCredential("service email", "p12key") instead of useApplicationDefaultCredential()

To stop repeated output in server sent events

Among the COMET,SOCKETS,SSE i felt server sent events is easy to implement.
And i am using tomcat server so i used servlets to implement SSE.
But i am facing big problem here and searched a lot but i did not got any solution to it.
The problem is if you see the basic example at sever sent event
The output is repeating for every 4-seconds,can't we make it to change output in same line.
In detail:
After 4 seconds a new updated result is printing in next line of previous output,
i want it to be printed in the same line of previous output(over write on previous output) and it should looks like a digital watch.
And my servlet code is like this what kind of changes i have to do.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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("/SseServer")
public class SseServer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/event-stream;charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
PrintWriter out = response.getWriter();
while (true) {
out.print("id: " + "ServerTime" + "\n");
out.print("data: " + new Date().toLocaleString() + "\n\n");
out.flush();
try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I thought using while loop make it as a repeated result.
GREAT THANKS FOR ANY HELP
The example you linked to uses the following code:
document.getElementById("result").innerHTML += event.data + "<br>";
So, it appends the new event data to the content of the result element. To replace it, just change it to
document.getElementById("result").innerHTML = event.data + "<br>";
In short, your question doesn't have anything to do with how you produce the event at server-side, but everything to do with how you consume the event, in the browser.

getpathtranslated returns null

The thing I try to implement the method getPathTranslated () but always returns null, this is the method I use:
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 FileLocation extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response.setContentType("text/html;charset=UTF-8");
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
if (request.getPathInfo() != null) {
out.println("The file \"" + request.getPathInfo() + "\"");
out.println("Is stored at \"" + request.getPathTranslated() + "\"");
} else {
out.println("Path info is null, no file to lookup");
}
}
}
If you are trying to retrieve the filesystem path corresponding to a URL path, try getServletContext().getRealPath("your_path").
Try this line:
request.getRequestURI().substring(request.getContextPath().length())
In situations where the servlet container cannot determine a valid file path for getRealPath or getPathTranslated methods, such as when the Web application is executed from an archive, on a remote file system not accessible locally, or in a database, these methods must return null.
The getPathTranslated method computes the real path of the pathInfo of the request.
If there is not a situation check your Servlet Mapping in deployment descriptor.
If you have a situation like:
<url-pattern>*.xhtml</url-pattern>
then you must know that observed path element behavior is like following (assume your request path is /myapp/admin/mypage.xhtml)
ContextPath: /myapp
ServletPath: /admin/mypage.xhtml
PathInfo: null
Hope it will help you to analyze a problem from a different point of view.

Categories