I have created a post yesterday regarding this, but someone decided to close it. I have tried solutions from the post, it didn't work. If answer from the post could solve my issues, I won't be asking the same question again. Tried Put servlet class in a package, Set servlet URL in url-pattern, Use domain-relative URL to reference servlet from HTML. The thing is my registration.jsp is almost the same as my login.jsp same for the servlets as well, I dont get why it doesnt work for registration when it works for the login servlet. I also have clean and restarted my server multiples times. Didnt install tomcat into the computer just import it thru zip files into eclipse.
HTTP Status 404 return by Servlet
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Login Servlet
package net.login.controller;
import java.io.IOException;
import java.sql.SQLException;
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 javax.servlet.annotation.WebServlet;
import net.login.dao.UserDAO;
import net.login.model.Users;
#WebServlet("/login")
public class UserLoginServlet extends HttpServlet{
public #interface WebServlet {
}
private static final long serialVersionUID = 1L;
public UserLoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDao = new UserDAO();
try {
Users user = userDao.checkLogin(username, password);
String destPage = "login.jsp";
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
destPage = "home.jsp";
} else {
String message = "Invalid username/password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
register.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.0/dist/jquery.validate.min.js"></script>
<link href=”bootstrap/css/bootstrap.min.css” rel=”stylesheet” type=”text/css” />
<script type=”text/javascript” src=”bootstrap/js/bootstrap.min.js”></script>
</head>
<body>
<div style='text-align=center' class="container">
<h1>New User Registration</h1>
<form action='register' method='POST' role='form'>
<div class='registerform'>
<label for='username'> Username: </label>
<input type="text" placeholder='Username' class='form-control' name='username'>
</div>
<div class='registerform'>
<label for='password'> Password: </label>
<input type="password" class='form-control' placeholder='Password' name='password'>
</div>
<br><br>
<button type="submit" class="btn btn-default"> Register </button>
</form>
</div>
</body>
</html>
UserRegisterServlet
package net.login.controller;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.login.dao.UserDAO;
import net.login.model.Users;
#WebServlet("/register")
public class UserRegisterServlet extends HttpServlet{
public #interface WebServlet{
}
private static final long serialVersionUID = 1L;
public UserRegisterServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// String pathInfo = request.getPathInfo();
// String[] pathParts = pathInfo.split("/");
// String part1 = pathParts[1];
// String part2 = pathParts[2];
//
// System.out.println(part1 + part2); //doesnt work for now since cant find /register
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDAO = new UserDAO();
try {
userDAO.createUsers(username, password);
String destPage = "register.jsp";
System.out.println("Success");
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
}catch(SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
Related
I am currently working on A middle-size Java Web application using Netbeans & GlassFish. And everything was good until I placed all JSP fils into the folder called LoginOut, which I created it to store all specific JSP files to make my project succinct. But after I placed all JSP files into that folder, the problem came out. In detailed, the browser keeps telling me HTTP 404 Not Found. This is a very common error I believe. I put relevant screenshots below. By the way, when I put all JSP files outside LoginOut folder, my application works fine. I don't know where the error has occurred..(Here is code) Project Fils Structure
public User checkLogin(String email, String password) throws SQLException,
ClassNotFoundException {
Connection conn = getConnection();
String sql = "SELECT * FROM users WHERE email = ? and password = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, email);
st.setString(2, password);
ResultSet rs = st.executeQuery();
User user = null;
if (rs.next()) {
user = new User();
user.setFullName(rs.getString("fullname"));
user.setEmail(email);
}
conn.close();
return user;
}
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="POST">
Email: <input type="text" name="email" ><br><br>
Password: <input type="password" name="pass" ><br><br>
<input type="submit" value="Login" ><br><br>
Click here to go back.
</form>
</body>
</html>
package controller.Servlet;
import Dao.UserDao.UserDAO;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.User.User;
#WebServlet("/Login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
UserDAO userDao = new UserDAO();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String email = request.getParameter("email");
String password = request.getParameter("pass");
try {
User user = userDao.checkLogin(email, password);
String destPage = "Login.jsp";
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
destPage = "home.jsp";
} else {
String message = "Invalid email/password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
I have implemented a simple web app with user authentication, and tried to add a filter to redirect to the login page, when the user is not logged in. The filter does the redirection properly, when it is supposed to, but it keeps redirecting to the login page when a user is logged in too.
Is there any specific method to be called, in case there is no need for redirection (besides filterChain#doFilter), or is there another mistake in my code?
Here are the classes and pages:
login page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login page</title>
</head>
<body>
<form method= "post" action="login" name="Login Form" id="login-form">
<h2>login</h2>
<label for="username">username</label><input name="username" type="text" id="username" />
<br>
<label for="password">password</label><input name="password" type="password" id="password" />
<br>
<input type="submit" value="login" id="submitButton" />
</form>
</body>
</html>
login handler:
package control;
import model.User;
import repository.DAOFactory;
import repository.UserDAO;
import util.PasswordHasher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
#WebServlet(name = "loginHandler", urlPatterns = {"/login"})
public class loginHandler extends HttpServlet{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException{
UserDAO dao = DAOFactory.getInstance().getUserDAO();
String username = request.getParameter("username");
try {
if(dao.validateUserLogin(username,request.getParameter("password"))>0) {
HttpSession session = request.getSession();
session.setAttribute("username",username);
session.setMaxInactiveInterval(30*60);
Cookie cookie = new Cookie("username",username);
cookie.setMaxAge(30*60);
response.addCookie(cookie);
User user = dao.getUserByUsername(username);
user.setLastHashedSessionID(PasswordHasher.hashPassword(session.getId(),user.getSalt()));
dao.updateUser(user);
response.sendRedirect("page.html");
}
else
request.getRequestDispatcher("error.html").forward(request,response);
} catch (IOException e) {
e.printStackTrace();
}
}
}
authentication filter:
package control;
import model.User;
import repository.DAOFactory;
import repository.UserDAO;
import util.PasswordHasher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
#WebFilter(urlPatterns = {"/page.html"})
public class authenticationFilter implements Filter{
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if(request instanceof HttpServletRequest) {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
System.out.print("Checking username in session...");
if(session.getAttribute("username") == null) {
System.out.println("FAILED!");
System.out.println("Redirect needed, no username in session!");
req.getRequestDispatcher("login.html").forward(request, response);
return;
}
System.out.println("OK");
User user;
UserDAO dao = DAOFactory.getInstance().getUserDAO();
String username = ((HttpServletRequest) request).getSession().getAttribute("username").toString();
user = dao.getUserByUsername(username);
System.out.print("Checking session ID...");
if(!user.getLastHashedSessionID().equals(PasswordHasher.hashPassword(session.getId(),user.getSalt()))) {
System.out.println("FAILED!");
session.invalidate();
req.getRequestDispatcher("login.html").forward(request,response);
System.out.println("Redirect needed, invalid session!");
return;
}
else {
System.out.println("OK");
chain.doFilter(request, response);
}
}
System.out.println("end of doFilter!");
}
#Override
public void destroy() {
}
}
I am having when using apache tomcat with java. The problem might be in the web.xml but I dont know how to fix it. This is my project explorer:
So the thing is that when I run registro.html everything goes as expected:
But when I click on enviar the 404 appears:
So this is my code in registro.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="/Ejer2/Registro" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
And this is my Registro.java:
package Ejer2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.*;
#SuppressWarnings("deprecation")
#WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
And this my web.xml:
I don't know what to do, thanks in advance.
There is a problem in the session.
In create.html when i click on createdepartment the createdepartment.jsp page opens i copy its url1 after i submit the data , i again copy the url2 and then i logout after logging out when i paste url2 in the browser it gives message that Please login first and opens login.html but when i paste url1 in the browser it opens it but it shouldn't. Why is this happening?
I have given the code please could someone correct it?
LoginServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
String sql="select * from roles where name='" + name + "' and pass='" + password + "'";
PreparedStatement stmt =con.prepareStatement(sql);
String role="admin";
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
status=true;
role=rs.getString("role");
}
if(status){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
if(role!=null && role.equals("admin") ){
request.getRequestDispatcher("create.html").include(request, response);
}
else {
request.getRequestDispatcher("create1.html").include(request, response);
}
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
}catch( SQLException | ServletException | IOException e){}
}
}
}
create.html
Logout
Create Department
Create Users
<hr/>
department.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Create Department</h1>
<br>
<form action="DepartmentServlet">
<table border="1">
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
DepartmentServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DepartmentServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
if(status){
out.print("Values have been inserted,"+name);
request.getSession();}
else
{
out.print("failed");
}
request.getRequestDispatcher("department.jsp").include(request, response);
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
}
Logout.Servlet
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
}
}
}
http://mytechsoft.jimdo.com/exclusive-projects
above link is for your problem, refer first 2 photos in it
LogoutServlet.java code might has problem.
You haven't mentioned its code.
Logout procedure includes 2 important things..
Remove all attributes attached to that session object
Make session object null (by making session.invalidate(); )
doing this makes session eligible for Garbage Collection, and reference of object (object stored in heap memory) is deleted (reference is stored in stack ).
In your case, I guess (because LogoutServlet.java is not there), most likely the reason for error is that
"You might be creating a new session Object and then you are copying the reference of old session object, now you would be deleting this new session by "session.invalidate();".
The above process deletes new reference but old one is still there because it's copy available in new object is deleted not the original one.
For More Specific and correct answer, please attach your LogoutServlet.java source code too.
Your logout servlet should have request.getSession(false)..This will not return new session if one already exists..Also clear your browser cache before running it.
HttpSession session=request.getSession(false);
session.invalidate();
This is my jsp page
<html>
<head>
<link rel = "stylesheet" href="main.css"/>
<title>Login Page</title> </head>
<body>
<div class ="RegWrap">
<div class ="Set">
<form name="actionForm" action="Connecter" method ="Get">
<table>
<tr><td>Enter your Username: </td>
<td><input type="text" name="userName"/></td></tr>
<tr><td>Enter your Password: </td>
<td><input type="password" name="password"/></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"> </td></tr>
</table>
</form>
</div>
</div>
</body>
</html>
This is my Connecter class :
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;`
public class Connecter extends HttpServlet {
public void doGet(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");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("welcom");
rd.forward(request,response);`
}
else {
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("Sign up.jsp");
rd.include(request,response);
}
out.close();
}`
This is my Welcome page
import java.io.IOException;`
import java.io.PrintWriter;`
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;`
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class welcom extends HttpServlet {
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=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}
}
}
This is my Dao page
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class LoginDao {
public static boolean validate(String userName,String password){
boolean status=false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306 /autolube","root","mehar");
PreparedStatement ps=con.prepareStatement
("select * from person where userName=?and password=?");
ps.setString(1,userName);
ps.setString(2,password);`ResultSet rs=ps.executeQuery();
status=rs.next();`}catch(Exception e){System.out.println(e);
}
return status;
}
}
In your servlet add the below line. As I commented I think its a problem with web.xml. If you are using servlet 3.0 you can use the below ammotation or map in web.xml.
#WebServlet("/Connecter")
public class Connecter extends HttpServlet
if url-pattern is /Connector then add /Connector in your form tag of index.html.