When user enters wrong password i need to show error and then load login.html using request dispatcher but i am getting login form without any error. Like this
When user enters correct password it is showing correct output but it is showing login.jsp in the url rather than welcome.jsp Like this
This is my login.html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
</head>
<body>
<div>
<h1>Login Here</h1>
<form action="login.jsp" method="post">
<div>
<label for="username">Username: </label>
<input type="text" name="username" id="username">
</div>
<div>
<label for="password">Password: </label>
<input type="password" name="password" id="password">
</div>
<div>
<input type="submit" value="Login">
</div>
</form>
</div>
</body>
</html>
This is my login.jsp code:
<%@page import="java.util.*, java.io.*, java.sql.*, javax.sql.*, java.time.format.DateTimeFormatter, java.time.LocalDateTime"%>
<html>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "saiakhil");
Statement st = conn.createStatement();
String sql = "select * from myusers where username = '" + username + "' and password = '" + password + "'";
ResultSet rs = st.executeQuery(sql);
if (rs.next() == false)
{
out.println("<h2>Invalid Username or Password!</h2>");
RequestDispatcher rd = request.getRequestDispatcher("login.html");
rd.include(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
rd.forward(request, response);
}
st.close();
conn.close();
}
catch (SQLException se)
{
out.println(se);
}
catch (Exception e)
{
out.println(e);
}
%>
</body>
</html>
This is my welcome.jsp code:
<%@page import="java.util.*, java.io.*, java.sql.*, javax.sql.*, java.time.format.DateTimeFormatter, java.time.LocalDateTime"%>
<html>
<body>
<%
String username = request.getParameter("username");
out.println("<h2>Logged in successfully</h2>");
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
out.println("<h3>Welcome " + username +"</h3>");
out.println(dtf.format(now));
%>
</body>
</html>
` tag is printed **before** the contents of `login.html` and the browser does its best to display this invalid HTML.
– Piotr P. Karwasz Dec 05 '21 at 23:59