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();
Related
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);
}
}
}
This is my JSP code, i am using get method to send data to go to servlet , servlet name is googleser.
<body>
<div class="formdiv">
<h1 align="center">Shikhar Google</h1>
<form action="googleser" method="get" align="center">
<input type="text" name="search1" class="search1"><br>
<input type="submit" class="submitbtn">
</form>
</div>
</body>
This is my servlet code . I tired printing every option related with printwriter method , but none of these worked.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class googleser extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3307/shikhar","root","");
Statement st = con.createStatement();
ResultSet rs= st.executeQuery("select * from student");
PrintWriter out=response.getWriter();
while(rs.next())
{
out.print(rs.getString(2));
}
String a= request.getParameter("search1");
out.print("<h1>Shikhar</h1>");
out.print("sddsdssdsd");
}
catch(Exception ex)
{
// System.out.print("yes yes yes");
}
}
}
please call the flush method after writing content into the response.
out.flush();
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.
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.
I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# 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>Insert title here</title>
</head>
<body>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.
You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example
Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}