wrapping a response not render jsp content [duplicate] - java

This question already has answers here:
ContentCachingResponseWrapper Produces Empty Response
(3 answers)
Closed 5 years ago.
I have a custom filter that implements Filter and I wrap the response with a ContentCachingResponseWrapper like this
HttpServletResponse responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
after that I open localhost and I see nothing, only white screen.
<html>
<head><head>
<body></body>
</html>
If I comment the ContentCachingResponseWrapper and use the response without wrapping it
chain.doFilter(request, response);
then my jsp page is rendered correctly.
Can anyone explain what's happening?

After adding ((ContentCachingResponseWrapper) responseWrapper).copyBodyToResponse(); after chain.doFilter(requestToCache, responseWrapper); problem was solved

Related

How does the HTML page find a servlet in an Eclipse dynamic web project? [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
I created a dynamic web project in Eclipse with a HTML page (in the WebContent folder of the project) that is supposed to send some input data from the user to a servlet (with the name "Tee").
I try to locate the servlet with
form method="get" action="../../src/Tee"
it does not find it. No, its not a Status 404 error message. But simply "the page cannot be displayed."
I tried this:
form method="get" action="/Tee"
as well, does not work either.
The Tomcat server is started and the project is deployed on the server. If i start the servlet itself, it runs on the server without problem (with all the data set to null, as these are supposed to come from the html page).
Yes, there are similary questions out there but those gave no real solution to me.
You need to write a servlet class something like:
#WebServlet("/Tee")
public class Tee extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.write("Hello World!");
//...
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//...
}
}
After writing the servlet, right-click its name in Eclipse and click Run As > Run on server
If it runs successfully in the Eclipse browser, it will be accessible in your HTML with its name e.g.
<form method="GET" action="Tee">
<input type="submit">
</form>
Update
After you posted the servlet code, I can see a problem there. You have written method="GET" in the HTML form but in the servlet code, you have just doPost. You should have doGet in the servlet for method="GET" in the HTML form to be acted on. Add the method, doGet in addition to doPost in the servlet.

I am unable to redirect to a jsp file from servlet. It was not redirecting to the actual page? [duplicate]

This question already has answers here:
How to send redirect to JSP page in Servlet
(3 answers)
Closed 3 years ago.
How can I redirect to the other jsp pages with the help of Servlets, I mean how should I construct the if and else condition and also wants to know how can I save the data in the database?
Try using this :
ServletContext sc = getServletContext();
sc.getRequestDispatcher("/file_name.jsp").forward(request, response);

What is the difference between doGet and doPost? [duplicate]

This question already has answers here:
doGet and doPost in Servlets
(5 answers)
Closed 6 years ago.
public void doGet(HttpServletRequest request,HttpServletResponse response){
}
and
public void doPost(HttpServletRequest request,HttpServletResponse response){
}
In HTTP protocal GET and POST are type of request headers. So whenever a GET type of request is recieved by server, doGet() method is invoked at the backend. Same goes for POST, doPost() is invoked.
Example:
This will invoke doGet when html form is submitted.
<form method="GET" action="servletname">
This will invoke doPost()
<form method="POST" action="servletname">
There are more request type headers like put, delete that are used for implementing REST api.

RequestDispatcher incude method issues [duplicate]

How do I generate an HTML response in a Java servlet?
You normally forward the request to a JSP for display. JSP is a view technology which provides a template to write plain vanilla HTML/CSS/JS in and provides ability to interact with backend Java code/variables with help of taglibs and EL. You can control the page flow with taglibs like JSTL. You can set any backend data as an attribute in any of the request, session or application scope and use EL (the ${} things) in JSP to access/display them. You can put JSP files in /WEB-INF folder to prevent users from directly accessing them without invoking the preprocessing servlet.
Kickoff example:
#WebServlet("/hello")
public class HelloWorldServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String message = "Hello World";
request.setAttribute("message", message); // This will be available as ${message}
request.getRequestDispatcher("/WEB-INF/hello.jsp").forward(request, response);
}
}
And /WEB-INF/hello.jsp look like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 2370960</title>
</head>
<body>
<p>Message: ${message}</p>
</body>
</html>
When opening http://localhost:8080/contextpath/hello this will show
Message: Hello World
in the browser.
This keeps the Java code free from HTML clutter and greatly improves maintainability. To learn and practice more with servlets, continue with below links.
Our Servlets wiki page
How do servlets work? Instantiation, sessions, shared variables and multithreading
doGet and doPost in Servlets
Calling a servlet from JSP file on page load
How to transfer data from JSP to servlet when submitting HTML form
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to use Servlets and Ajax?
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Also browse the "Frequent" tab of all questions tagged [servlets] to find frequently asked questions.
You need to have a doGet method as:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hola</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
out.println("</body>");
out.println("</html>");
}
You can see this link for a simple hello world servlet
Apart of directly writing HTML on the PrintWriter obtained from the response (which is the standard way of outputting HTML from a Servlet), you can also include an HTML fragment contained in an external file by using a RequestDispatcher:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HTML from an external file:");
request.getRequestDispatcher("/pathToFile/fragment.html")
.include(request, response);
out.close();
}

Servlet forwarding

I'm using in my project the embebed jetty and came up with a few problems. I have these two pages:
índex.jsp
result.jsp
And these two servlets:
upload
search
In the índex.jsp there is a form to upload a file and the upload process in handle by the upload servlet but then I should return a message to the índex.jsp to tell if the upload was done.
request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
This will forward the message to the índex page but the url will be /upload and I would like to be the índex. So there is some other way of struct my files and maybe make my welcome file some servlet instead of the índex.jsp?
This has nothing to do with Jetty. That's default behavior of forwarding.
Ugly solution:
If you want to rewrite your URL, use a redirect instead and pass the parameter by session. After displaying the message, remove it from session.
Better solution:
Change the name of your upload servlet by IndexServlet. This servlet will handle GET and POST requests for your index.jsp page. In the end of the processing, you will forward to your JSP page. By doing this, you can directly post the form to your current page:
<form action="index.jsp" method="POST" enctype="multipart/form-data">
<!-- your fields ... -->
</form>
Then your servlet:
#WebServlet("index.jsp")
public class IndexServlet extends HttpServlet {
//using ... to avoid parameters and exceptions to be thrown
#Override
public void doGet(...) throws ... {
//this method should only forward to your view
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//using ... to avoid parameters and exceptions to be thrown
#Override
public void doPost(...) throws ... {
//current implementation...
//in the end, forward to the same view
request.setAttribute("message", "Upload Sucedded!");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
More info:
Difference between JSP forward and redirect
The simplest solution would be to change upload servlet to use redirect and use request parameter instead of attribute like this:
// upload servlet
response.sendRedirect("index.jsp?message=YourMessage");
Then in index.jsp use request.getParameter("message") or EL to display your message.

Categories

Resources