How to transfer control from service to post method in servlets? - java

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.

Related

For what reason, RequestDispatcher.forward() method returns to the calling servlet? What's the use of returning, if we can't make changes in response?

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

JAVA upload string to server

I would like to upload a string to a server in java. I would not like to just upload a file I would like to upload a string
String toupload = "Cheese"; Upload(toupload);
like this
You can upload it using both POST method, and GET methods:
If you use the GET method: you pass the string in the url.
ex: localhost:8080/yourwebproject/yourservlet?nameofyourstring=itsvalue
And then in your servlet you can do something like:
public myServlet extends HttpServlet(HttpServletRequest request, HttpServletResponse response)
public myServlet() {
super();
}
/*This method will be called by your web-container if you used the get method..*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
//here we go
String str = request.getParameter("nameOfyourString");
}`
}
If you use the POST method, you have to implement the doPost with same logic..

Response been writen twice in custom servlet forwarding

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() ;

J2EE: Understanding isCommitted and Filters under this scenario

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.

HTTP method GET is not supported by this URL

i am having trouble with my code as i am accessing the logout servlet from a jsp page's hyperlink.
Jsp page link:
href="/logout"
logout Servlet:
public class logOut extends HttpServlet{
public void doGET(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
System.out.println("log out servlet");
HttpSession session = req.getSession(false);
if (session != null) {
session.invalidate();
}
resp.sendRedirect("/signin.jsp");
}
}
but i am having the following error :
HTTP ERROR 405
Problem accessing /logout. Reason:
HTTP method GET is not supported by this URL
please help me.....
It is called doGet, not doGET.
The #Override annotation would have told you that.
Your method needs to be called
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
in order to be recognized - the uppercase letters make it fail.

Categories

Resources