I need to forward to a servlet that is been dynamically loaded from a jar by a custom class loader from the main servlet using an external configuration file. The servlet itself is not mapped in web.xml.
I have been able to load the servlet and construct a new instance using reflection and casting:
Object o = loadedClass.newInstance() ;
HttpServlet loadedServlet = (HttpServlet) o ;
I have initialized the servlet as:
loadedServlet.init(getServletConfig()) ;
And then implemented every do... method in the main servlet as:
loadedServlet.service(request, response) ;
Everything works as expected with the exception of the response getting output twice:
hello, world!hello, world!
Is not an issue of the loaded servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter printWriter = response.getWriter() ;
printWriter.write("hello, world!") ;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response) ;
}
Sorry if this is not enough specific. Any hint for what should I look at?
Nevermind, I found the solution myself.
A call of response.reset() after calling servlet.service() was all what I needed.
loadedServlet.service(request, response) ;
response.reset() ;
Related
I just want to understand the purpose behind returning back to the calling servlet, after the execution of forwarded servlet.
Below example simply shows that after execution of forwarded servlet, control returns back to calling servlet.
//servlet1 Code (Forwarding to servlet2)
#WebServlet("/servlet1")
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("servlet2");
rd.forward(request, response);
System.out.println("Returned to Calling Servlet");
}
}
//servlet2 Code (returning control to servlet1)
#WebServlet("/servlet2")
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = "to Servlet2";
out.print("Welcome " + n);
}
}
Output ::
Welcome to Servlet2 (on Browser)
Returned to Calling Servlet (on Console)
Need clarification :
After committing response, why it's returning back to servlet1
good afternoon. I have a .JSP file that send a value to a servlet file. I have another project, where there is a java file in that i want to get this servlet value received by .JSP file.
My question is if is there possible pass this servlet value to this .java file in another project ? Or can i send by .JSP file directly ?
I created a Java Class in my Web Application, but now, how can i pass the servlet parameter to this java class ?
I will put the code down here:
Servlet code:
public class ServletJava extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
/*I WANT TO INSTANCE THE PARAMETER HERE TO SEND TO OTHER CLASS*/
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
The Class java:
public class RecebeServlet {
public static void main(String[] args) throws Exception {
/*I WANT RECEIVE THE PARAMETER HERE !! */
}
}
It is probably bad practice to have a class with only one main mathod. I am sure that you can divide the logic from that class into several methods instead of having one giant main.
But anyway, since you asked: Just call your main method as you would call any static method:
String[] args = new String[1];
args[0] = yourValue;
RecebeServlet.main(args);
But again, please consider refactoring your RecebeServlet class. You do not want to have program logic in your main method.
I have written the following code in service and post methods
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter p = response.getWriter();
p.println("<html><body>");
p.println("<form action = roomlog2 method = post>");
p.println("<input type = submit value = back>");
p.println("</form>");
p.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("homepage.html");
}
But when i executed the code and click the back button the post method is not executing. I am getting following exception
java.lang.NumberFormatException: null
why the post method not redirecting to the "homepage.html"?why i am getting the exception?Kindly someone can tell me the error.
Just remove your implementation of the service() method, or have it call super.service(). That's how doPost() gets called. At present you're not calling it at all.
I'm trying to forward request to a jsp file after login using tomacat. But it (servlet) does not forwarding the request. Can anyone figure it out the error here ?
Servlet :
public class AuthenticationServer extends HttpServlet {
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doService(request, response);
}
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doService (request, response);
}
public void doService (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getRemoteUser();
request.setAttribute("user", user);
RequestDispatcher dispatcher = request.getRequestDispatcher("/" + request.getParameter("direct"));
dispatcher.forward(request, response);
}
}
When I printed the "/" + request.getParameter("direct"), it prints out /welcome.jsp. But it just don't forwards it.
request.getRequestDispatcher(String path);
The path specified may be relative, although it cannot extend outside the current servlet context. If the path begins with a "/" it is interpreted as relative to the current context root. If the servlet container cannot return a RequestDispatcher also this method returns null.Try this:RequestDispatcher dispatcher = request.getRequestDispatcher(request.getParameter("direct"));
If you could specify the error it will make it easier to solve your problem...
The problem could be because it cannot find the jsp view.
When you put a "/" in getRequestDispatcher() the path is relative to the root of your application. if http://localhost:8080 is your root then your url will be http://localhost:8080/YourApp/welcome.jsp
you can get a more explanation here
I am working on a filter, this code fails to execute/response.write if there is a 'forward' involved in the request. But it works fine for basic servlets that simply steam HTML content to the user. How can address "forwards" with this code.
For example, here is the filter that simple captures text content and attempts to manipulate that content.
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession(false);
CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
final boolean commit1 = responseWrapper.isCommitted();
final boolean commit2 = response.isCommitted();
if (!commit2) {
final String res = responseWrapper.toString().replaceAll("(?i)</form>", "<input type=\"hidden\" name=\"superval\" value=\""+superval"\"/></form>");
response.getWriter().write(res);
}
return;
}
...
This works for most basic servlets, the goal is at the line with the "replaceAll".
Now, if I create a servlet with a 'forward' the code does not work, it fails at the line with 'if (!commit2)' because the stream is already committed apparently?
For example, if I make a request to this servlet and tie the filter to this servlet, then the filter does not execute completely.
public class TestCommitServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("TestCommitServlet2").forward(req, resp);
}
#Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
And here is the servlet that I am forwarding to:
public class TestCommitServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
final PrintWriter out = resp.getWriter();
resp.setContentType("text/html");
out.println("<html><body>(v-1)testing<form action='test'><input type='submit' value='Run' /> </form></body></html>");
}
#Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Tl;dr : Do I have to make this call 'if (!commit2) {' The code works without it. Under this code, how would I avoid Response already committed or IllegalStateExceptions (around the line with response.getWriter().write(res);
More on the issue here:
https://codereview.stackexchange.com/questions/41260/capturing-content-within-a-j2ee-filter-and-then-replacing-this-text-request-for
I´m using Servlet API 3.0 to check this scenario.
What I found is the following. Using your code for the servlet and the filters when I call the TestCommitServlet2 , I´m able to see the following output.
http://localhost:8080/Question/TestCommitServlet2
(v-1)testing
Button here
com.koitoer.CharResponseWrapper#5b5b6746
When I call the servlet TestCommitServlet , Im able to see the following.
http://localhost:8080/Question/TestCommitServlet
(v-1)testing
Button here
this shown that filter is not apply to this forwarded request at all.
So, I remember that some filters can act in diverse DispatcherTypes as FORWARD, INCLUDE, ERROR, ASYNC and the commong REQUEST, what I decide is change the filter declaration to.
#WebFilter(filterName = "/MyFilter", urlPatterns = { "/TestCommitServlet2" }, dispatcherTypes = {
DispatcherType.FORWARD, DispatcherType.REQUEST })
public class MyFilter implements Filter {
Then when I excecute a GET over the servlet TestCommitServlet I got:
(v-1)testing
Button
com.koitoer.CharResponseWrapper#1b3bea22
the above shown that Filter is now applied to the forward request.
Also if I remove or comment lines for if (!commit2) { code still works, so there is no IllegalStateException as request need to pass over the filter which is who invoke the doChain method.
One note more, if you try to replace the content of the response using this.
responseWrapper.toString().replaceAll
You are doing it wrong as responseWrapper.toString() returns something like this CharResponseWrapper#5b5b6746, not the content, if you want to modify the response use a Wrapper that extends from HttpServletResponseWrapper and override the correct methos to manipulate the outpustream.