3

I am new to java servlets. I googled for how to build simple login form with validation against mysql database. I have made so much changes and still have the following error for some reason.

The following error type:

HTTP Status 404 - /LoginServlet

type Status report

message /LoginServlet

description The requested resource is not available.
Apache Tomcat/7.0.57

Here all my jsp pages and java objects and web.xml:

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page</title>
</head>
<body>
<center>
<h1>Login Details</h1>
<form action="/LoginServlet" method="POST">
<br/>Username:<input type="text" name="username">
<br/>Password:<input type="password" name="password">
<br/><input type="submit" value="Submit">
</form>
</center>
</body>
</html>

Welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"  
  pageEncoding="ISO-8859-1"%>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>Welcome <%=session.getAttribute("name")%></title>  
</head>  
<body>  
<h3>Login successful!!!</h3>  
<h4>
Hello,
<%= session.getAttribute("name")%>
</h4>  
</body>  
</html> 

LoginServlet.java package com.servlet;

import java.io.IOException;  
import java.io.PrintWriter;  

import javax.servlet.RequestDispatcher;  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.HttpSession;

import com.logindao.LoginDao;

public class LoginServlet extends HttpServlet {  

private static final long serialVersionUID = 1L;  

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    

    response.setContentType("text/html");    
    PrintWriter out = response.getWriter();    

    String n=request.getParameter("username");    
    String p=request.getParameter("password");   

    HttpSession session = request.getSession(false);  
    if(session!=null)  
    session.setAttribute("username", n);  

    if(LoginDao.validate(n, p)){    
        RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");    
        rd.forward(request,response);    
    }    
    else{    
        out.print("<p style=\"color:red\">Sorry username or password error</p>");    
        RequestDispatcher rd=request.getRequestDispatcher("index.jsp");    
        rd.include(request,response);    
    }    

    out.close();    
   }    
}

LoginDao.java

package com.logindao;

import java.sql.*;

public class LoginDao {  
    public static boolean validate(String name, String pass) {          
        boolean status = false;  
        Connection conn = null;  
        PreparedStatement pst = null;  
        ResultSet rs = null;  

    String url = "jdbc:mysql://localhost:3306/";  
    String dbName = "form";  
    String driver = "com.mysql.jdbc.Driver";  
    String userName = "root";  
    String password = "password";  
    try {  
        Class.forName(driver).newInstance();  
        conn = DriverManager.getConnection(url + dbName, userName, password);  

        pst = conn.prepareStatement("select * from login where user=? and password=?");  
        pst.setString(1, name);  
        pst.setString(2, pass);  

        rs = pst.executeQuery();  
        status = rs.next();  

    } catch (Exception e) {  
        System.out.println(e);  
    } finally {  
        if (conn != null) {  
            try {  
                conn.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
        if (pst != null) {  
            try {  
                pst.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
        if (rs != null) {  
            try {  
                rs.close();  
            } catch (SQLException e) {  
                e.printStackTrace();  
            }  
        }  
    }  
    return status;  
   }  
}

Web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  version="3.0">

    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.servlet.LoginServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332

3 Answers3

1

The problem is here:

<form action="/LoginServlet" method="POST">
              ^ means absolute path

Change it to a proper form using EL:

<form action="${request.contextPath}/LoginServlet" method="POST">

In your doPost method, if you're already using this:

RequestDispatcher rd=request.getRequestDispatcher("...");
rd.forward(request,response);

There's no need to use the writer of the response:

PrintWriter out = response.getWriter();
//...
out.print("<p style=\"color:red\">Sorry username or password error</p>");
//...
out.close();

These lines using out should be removed from your code.

Also, please stop using scriptlets. Use EL + JSTL to achieve the same result:

<!-- <title>Welcome <%=session.getAttribute("name")%></title> -->
<!-- Retrieve it directly from any scope -->
<!-- <title>Welcome ${name}</title> -->
<!-- If you want to make sure it is retrieved from session scope -->
<title>Welcome <c:out value="${sessionScope.name}" /></title>
</head>  
<body>  
<h3>Login successful!!!</h3>
<h4>
<!-- similar here -->
<!--
Hello, <%= session.getAttribute("name")%>
-->
Hello, <c:out value="${sessionScope.name}" />
Community
  • 1
  • 1
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • I still have the same error: HTTP Status 404 - /LoginServlet type Status report message /LoginServlet description The requested resource is not available. Apache Tomcat/7.0.57 – user3158406 Jan 26 '15 at 18:01
1

Unless your application is deployed as the root application, all the URLs to resources of the application should start with the context path of the application (the root application's context path is the empty string).

Typically, if your war file is myWebApp.war, the app is living under /myWebApp, and all the URLs should thus start with /myWebApp.

Your form action is /LoginServlet, so it fails to fill this constraint.

Use the JSTL, and define the action as

<form action="<c:url value='/LoginServlet' />"

The c:url tag will prepend the context path, whatever it is.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • I still have the same error: HTTP Status 404 - /LoginServlet type Status report message /LoginServlet description The requested resource is not available. Apache Tomcat/7.0.57 – user3158406 Jan 26 '15 at 18:00
  • Have you correctly installed the JSTL jar files, and declared the use of the core library in the JSP? What's the HTML source (in the browser) of the form? – JB Nizet Jan 26 '15 at 18:14
  • Yes i downloaded JSTL jar file and drop it in WEB-INF. But still the same error type !!! Any suggestions ??? Please help me.. – user3158406 Jan 26 '15 at 18:39
  • Yes, I have a suggestion: answer my questions. Have you declared the use of the core library in the JSP? What's the HTML source (in the browser) of the form? – JB Nizet Jan 26 '15 at 18:43
  • I am not so sure i am understanding what you say, i am really new to all of this, but from what i understand i declared the use of the core library in my jsp file like this: Just add this to jsp file: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> Also i don't understand your second question.. Thanks a lot for helping me ! – user3158406 Jan 26 '15 at 18:53
  • When you right-click in your browser and click "View HTML source", what does the code of the form look like? – JB Nizet Jan 26 '15 at 20:07
  • Now for some reason i can't get to the index.jsp and here is the error: HTTP Status 500 - The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application type Exception report message The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application description The server encountered an internal error that prevented it from fulfilling this request. – user3158406 Jan 28 '15 at 14:12
0

You servlet is not found in the absolute path you requested the <form action> attribute . I suggest you to get the path using contextPath as suggessted by @Luggi.

This temporary soultion should work ,

<form action="<c:url value='./LoginServlet'>"

as it will search for the servlet in the packages that are created under the src package.

And also avoid using the scriplets as they are not suggested over the decade. Please see How to avoid Java code in JSP files?

Hope this helps

Community
  • 1
  • 1
Santhosh
  • 8,181
  • 4
  • 29
  • 56