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.
Related
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> ");
}
}
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.
I need verify header before receive the request. I found that tomcat valve can help in it. I follow these steps but valve is not called:
make a maven project and do this code in it.
package cz.ValveTest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;
public class ProcessingValve extends ValveBase {
private static final Logger logger = Logger.getLogger(ProcessingValve.class.getName());
#Override
public void invoke(Request request, Response response) throws IOException,
ServletException {
HttpServletRequest httpServletRequest = request.getRequest();
Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
logger.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
while (headerNames.hasMoreElements()) {
String header = headerNames.nextElement();
logger.log(Level.INFO, "Header --> {0} Value --> {1}", new Object[]{header, httpServletRequest.getHeader(header)});
}
getNext().invoke(request, response);
}
}
make jar and put jar inside tomcat/lib folder
add this line in server.xml
<valve className="cz.ValveTest.ProcessingValve"/>
restart tomcat.
Now I hit my web service with header:
Expect : 100-continue
but using this configuration and code valve is not called on http hit.If any one knew why tomcat valve is not called please help.
The tags in server.xml are case sensitive.
So try this :
<Valve className="cz.ValveTest.ProcessingValve"/>
I have a folder that has only .java files. There are no .html, .jsp, .jsf etc. files only .java. I was told that this is a web application, but I have no idea on how to run it.
Here is a sample code from one of the .java files:
public List<String> generateHtml(String name, String css) {
List<String> html = new ArrayList<>();
html.add("<!DOCTYPE HTML><html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"" + css
+ "\"/></head><body>");
html.add("<div class='screen page_size " + name + "'>");
for (HtmlElement element : orderedElements) {
element.generateHtml(html);
}
html.add("</div>");
html.add("</body></html>");
return html;
}
I tried making a web project in eclipse and importing the files and running it, but no luck. It gives me a lot of errors with something to do with jetty. After installing jetty it still didnt work. Maybe I am installing it wrong. Anyone has any idea?
If you want to create a runnable war with jetty, have a look a the Embedded Jetty examples
You can call the generateHtml method from the servlet below.
package org.eclipse.jetty.embedded;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletHandler;
public class MinimalServlets
{
public static void main( String[] args ) throws Exception
{
Server server = new Server(8080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class, "/*");
server.start();
server.join();
}
#SuppressWarnings("serial")
public static class HelloServlet extends HttpServlet
{
#Override
protected void doGet( HttpServletRequest request,
HttpServletResponse response ) throws ServletException,
IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
//From here you can call the generateHtml method
response.getWriter().println("<h1>Hello from HelloServlet</h1>");
}
}
}
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.