Why is the code not reaching else part - java

In this servlet,the code is never reaching the else part why so?even though i have not added any cookies and it is still printing some random value?Why so?
public class profile extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Cookie[] ck=req.getCookies();
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
if(ck!=null)
{
System.out.println("hello");
RequestDispatcher rd=req.getRequestDispatcher("/index.jsp");
rd.include(req, resp);
out.println("welcome to your profile "+ck[0].getValue());
}
else
{
out.println("sorry annonymous,you have to login first");
RequestDispatcher rd=req.getRequestDispatcher("/login.jsp");
rd.include(req, resp);
}
}
}
and even eclipse was saying dead code why so?

Instead of verifying existance of cookies.
You should verify some exact value, that you can prevously set with setCookies method.

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

why this link works even after logout(or invalidate session)?

I have generated dynamic delete link for each row in a table in jsp. When I click on that link It should delete the associated row,It works Fine. But it should not delete the row once I logged out..I copied the delete link and logged out..Now If I run that link It redirects me to Login page, If I login again viewed the students in a table..It deletes that particular row.
Why this even after removed the attribute and invalidate the session It still able to reach the servlet?
generated link for delete student..
http://localhost:8080/feeManagement/Delete_Action_Student?delete=67657
Here are my DeleteStudent,Logout servlets.
#WebServlet("/Delete_Action_Student")
public class Delete_Action_Student extends HttpServlet {
private static final long serialVersionUID = 1L;
public Delete_Action_Student() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (request.getAttribute("Accemail") != "") {
String id = request.getParameter("delete");
try {
if (StudentDAOimpl.removeStudent(id)) {
request.setAttribute("msg", "deleted successfully");
getServletContext().getRequestDispatcher("/Delete_Student").forward(request, response);
} else {
request.setAttribute("msg", "failed to remove");
getServletContext().getRequestDispatcher("/Delete_Student").forward(request, response);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
response.sendRedirect("/loginjsp.jsp");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}
Logout snippet.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.removeAttribute("Accemail");
session.invalidate();
response.sendRedirect("loginjsp.jsp");
}
It's the behavior of browser to store the url where you came from to login page. So After successful login it redirect to that url.
After successful login if you want to land always to home page you can do that by using filter.

why html tags are not working inside servlet?

I'm new to Servlets I just trying to print a simple Html tag inside servlet response but I dunno why it doesn't print in Browser. it just print the String without getting the Html tags.
Here is the code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hi All");
PrintWriter out =response.getWriter();
out.println("<h2>Please complete our Customer Survey</h2>");
}
}
**Out Put print as **
<h2>Please complete our Customer Survey</h2>
Please let me know how to fix this
Thanks.
ContentType must be set.
Try this.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hi All");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<h2>Please complete our Customer Survey</h2>");
}

Why I am getting error HTTP GET method not supported by this URL, while I am not using it anywhere in my code

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

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