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.
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
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 am developing login servlet app my code is as follows:
Login page for displaying two text box and one login button. Where user enter username and password and submit data.
public class LoginPage extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String contextPath = request.getContextPath();
out.println("<form method='post' action='LoginCheck'>");
out.println("Username: <input type='text' name='username'>");
out.println("<br>");
out.println("Password: <input type='password' name='password'>");
out.println("<br>");
out.println("<input type='submit' value='login'>");
out.println("<br>");
out.println("</form>");
}
}
LoginCheck page This page is for checking user's username and password.After checking if username and password is correct then it redirect to welcome page or if it is incorrect then it redirects to Error page And the code for each page is as follows:
public class LoginCheck extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("abs") && password.equals("abs")){
response.sendRedirect("Welcome");
}else{
response.sendRedirect("Error");
}
}
}
Welcome If username and password correct.
public class Welcome extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<h3>Welcome user</h3>");
}
}
Error If username or password is Incorrect.
public class ErrorPage extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<h3>ERROR !!!</h3>");
out.println("<h3>Username or Password you entered is wrong.</h3>");
}
}
OK !!! But after entering username and password to login page it goes to checklogin and when it goes towards welcome page or error page it gives error !!!
HTTP Status 405 - HTTP method GET is not supported by this URL
I am not using GET method anywhere in above code as you can see but why I am getting this type of error ???
The reason why you get HTTP 405 is that HttpServletResponse.sendRedirect is specified like this:
Sends a temporary redirect response to the client using the specified
redirect location URL.
So if you do a response.sendRedirect("Welcome");, you "tell" the client browser to go to the relative URL "Welcome" instead. This by coincidence is mapped to your Welcome-servlet (I presume). HTTP only supports GET redirects, so a GET request is issued by the client browser, but your Welcome-servlet only supports POST.
If you change your Welcome-servlert like this it should work:
public class Welcome extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<h3>Welcome user</h3>");
}
}
Remember to change your ErrorPage-servlet as well.
BUT heed the following!
You should not use a client side redirect but a server side forward like this:
public class LoginCheck extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.equals("abs") && password.equals("abs")){
RequestDispatcher rd = request.getRequestDispatcher("Welcome");
rd.forward(request, response);
}else{
RequestDispatcher rd = request.getRequestDispatcher("Error");
rd.forward(request, response);
}
}
}
Change
protected void doPost(HttpServletRequest request, HttpServletResponse response)
to
protected void doGet(HttpServletRequest request, HttpServletResponse response)
in you Welcome and Error methods.
Thanks Andrew Mairose for pointing that out in comments.
Reference - http://www.wellho.net/resources/ex.php4?item=j601/demolet.java
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.