Hi I'm writting java servlet which should get DVDs depends on which user is logged in. I have method
public List<Dvd> getDvdsByUserId(String user_id) throws SQLException {
List<Dvd> dvds = new ArrayList<Dvd>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
preparedStatement.setString(1, user_id);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Dvd dvd = new Dvd();
dvd.setId(resultSet.getInt("id"));
dvd.setUser_id(resultSet.getString("user_id"));
dvd.setName(resultSet.getString("name"));
dvd.setBorrower(resultSet.getString("borrower"));
dvd.setMail(resultSet.getString("mail"));
dvd.setBorrow_date(resultSet.getString("borrow_date"));
dvd.setBorrow_until(resultSet.getString("borrow_until"));
dvds.add(dvd);
}
} catch (SQLException e) {
throw e;
} finally {
cleanUp(connection, preparedStatement);
}
return dvds;
}
and I don't know how to set up logged user id in servlet's doGet method:
dvds = this.dvdDao.getDvdsByUserId();
loginServlet
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
DbSettings dbSettings = new DbSettings();
dbSettings.setServer(config.getServletContext().getInitParameter("dbServer"));
dbSettings.setPort(Integer.valueOf(config.getServletContext().getInitParameter("dbPort")));
dbSettings.setUser(config.getServletContext().getInitParameter("dbUser"));
dbSettings.setPassword(config.getServletContext().getInitParameter("dbPassword"));
dbSettings.setDatabase(config.getServletContext().getInitParameter("dbDatabase"));
try {
this.userDao = new UserDao(dbSettings);
} catch (ClassNotFoundException e) {
throw new ServletException("Unable to initialize DB driver", e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
getServletContext().log("error", e);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if (getLoggedUser(request, response) != null) {
response.sendRedirect("/list");
return;
}
String nickname = request.getParameter("nickname");
String password = request.getParameter("password");
if (nickname != null && password != null) {
User user = userDao.getByLogin(nickname);
if (user != null && UserUtil.checkLogin(user, password)) {
HttpSession session = request.getSession(true);
Long userId = user.getId();
session.setAttribute("userId", userId);
session.setAttribute("loggedUser", user);
request.getSession().setAttribute("nickname", nickname);
response.sendRedirect("/list");
} else {
request.setAttribute("message", "Login se nepovedl.");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
dispatcher.forward(request, response);
}
} else {
response.sendRedirect("/login");
}
} catch (Exception e) {
getServletContext().log("error", e);
}
}
public User getLoggedUser(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
User user = (User) session.getAttribute("loggedUser");
return user;
}
}
Does anybody have an idea please?
Get Logged User Id In Servlet Using Session.
HttpSession session=request.getSession(true);
session.setAttribute("user", userLoggedId);
Later You can retrieve Session Data :
HttpSession session=request.getSession(true);
String userId=(String)session.getAttribute("user");
According to my understand of your requirement first you validate whether username and password are matching then you pass the control to the servlet so on the request set the userid .Then you can acquire the userid in the doGet() method using the request.getParameter() method.
This can be done in many ways.
I think you are using form because in servlet you are calling doget().So while calling the servlet from the form pass the userid also and in servlet you can use userid=request.getParameter("user");
The other way is to keep the user in session
After the login if you are calling any servlet or jsp page then keep the user there in session like this way
session.setAttribute("username","username");
and in the servlet you can retrieve by using
session.getAttribute("username");
Related
I'm fairly new to using hibernate and I'm trying to create a webapp with hibernate as the backend but I'm running into an error I can't seem to figure out how to solve given the current configuration of my code. Any help would be appreciated
I have added my hibernate.cfg.xml configuration into the hibernateutil java class but i can't seem to get my configuration to read data from my database and keep getting
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
caused by another error: Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.mysql.jdbc.Driver] and a ClassNotFoundException again to the mysql driver
i thought i configured my class properly but i can't seem to get it to work, here is my code where the error starts
public class HibernateUtil {
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
try {
Configuration configuration = new Configuration();
Properties settings = new Properties();
// Hibernate settings equivalent to hibernate.cfg.xml's properties
settings.put(Environment.DRIVER, "com.mysql.jdbc.Driver");
settings.put(Environment.URL, "jdbc:mysql://localhost:3308/demo");
settings.put(Environment.USER, "user");
settings.put(Environment.PASS, "password");
settings.put(Environment.DIALECT, "org.hibernate.dialect.MySQL5Dialect");
settings.put(Environment.SHOW_SQL, "true");
settings.put(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(Environment.HBM2DDL_AUTO, "create-drop");
configuration.setProperties(settings);
configuration.addAnnotatedClass(Student.class);
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
e.printStackTrace();
}
}
return sessionFactory;
}
}
here is my DAO class
public class StudentDAO {
public void saveStudent(Student student) {
Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.save(student);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
public void updateStudent(Student student) {
Transaction transaction = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.saveOrUpdate(student); //student object updated
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
public Student getStudent(int id) {
Transaction transaction = null;
Student student = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
student = session.get(Student.class, id); //get student object by id
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
return student;
}
#SuppressWarnings("unchecked")
public List<Student> getAllStudents() {
Transaction transaction = null;
List<Student> students = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
students = session.createQuery("from student").list(); //get all student objects
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
return students;
}
#SuppressWarnings("null")
public void deleteStudent(int id) {
Transaction transaction = null;
Student student = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
student = session.get(Student.class, id);
if (student != null) {
session.delete(student);
System.out.println(student + "has been deleted");
}
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
}
}
}
and here is my servlet class
#WebServlet("/")
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 2L;
private StudentDAO studentDao;
String home = "/Week05";
public StudentServlet() {
this.studentDao = new StudentDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sPath = request.getServletPath();
//switch statement to call appropriate method
switch (sPath) {
case "/new":
try {
showNewForm(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
case "/insert":
try {
insertStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/delete":
try {
deleteStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/update":
try {
updateStudent(request, response);
} catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
case "/edit":
try {
editStudent(request, response);
} catch (ServletException | IOException e) {
e.printStackTrace();
}
break;
default:
try {
listAllStudents(request, response); //home page = .../week04/StudentServlet
} catch (ServletException | IOException | SQLException e) {
e.printStackTrace();
}
break;
}
}
// functions to fetch data from studentDao and display data on appropriate jsp
private void listAllStudents(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
List<Student> allStudents = studentDao.getAllStudents();
request.setAttribute("listStudents", allStudents);
RequestDispatcher dispatch = request.getRequestDispatcher("index.jsp"); //home page week04/StudentServlet | list all objects from table
dispatch.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp");
dispatch.forward(request, response);
}
private void insertStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student newStudent = new Student(firstname, lastname, email);
studentDao.saveStudent(newStudent); //student object inserted to table
response.sendRedirect(home); //redirect to home page
}
private void deleteStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
studentDao.deleteStudent(id); //student object deleted
response.sendRedirect(home);
}
private void updateStudent(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException{
int id = Integer.parseInt(request.getParameter("id"));
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
Student updateStudent = new Student(id, firstname, lastname, email);
studentDao.updateStudent(updateStudent); //student object updated
response.sendRedirect(home);
}
private void editStudent(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
// String firstname = request.getParameter("firstname");
// String lastname = request.getParameter("lastname");
// String email = request.getParameter("email");
Student currentStudent = studentDao.getStudent(id);
RequestDispatcher dispatch = request.getRequestDispatcher("student-form.jsp"); //student form called with current student info loaded
request.setAttribute("student", currentStudent);
dispatch.forward(request, response);
}
}
Any help on where I'm going wrong would be appreciated as I truly can't figure what exactly to do, it might be a mapping error issue but i assumed all necessary mapping was covered on the servlet.
#Alpheus
Your project can't find out your driver's dependency, because you haven't put dependency on build path.
I have one application in which i am restricting the user for multiple loggin from different devices. For that i took two column in my table status and ip. If user already logged in from one computer then he is able to login again from same machine but when he try to logged in from another then the ip of new machine will be assigned. but he is able to access from previous computer. Why? how to logged out him? And also if i logged out from one browser he is able to access from another browser if he logged in from both browser. How to logged out him from all browsers?
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("LoginServlet..........");
InetAddress address;
//String hostname;
byte[] ip = new byte[0];
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
LoginDTO loginDTO = (LoginDTO) session.getAttribute("loginDTO");
int noOfCartItems = 0;
session.setAttribute("noOfCartItems", noOfCartItems);
Connection con = null;
try {
String operation = request.getParameter("operation");
if (operation.equalsIgnoreCase("signin")) {
String mobile_email = request.getParameter("mobile_email");
String password = request.getParameter("password");
address = InetAddress.getLocalHost();
ip = address.getAddress();
String ipAddress = com.oeuvretc.util.RawIPToString.getIpAddress(ip);
System.out.println(ipAddress);
con = ConnectionManager.getConnection();
PreparedStatement ps=con.prepareStatement("SELECT * FROM view_user_details WHERE (mobile=? OR email_id=?) AND user_password=?");
ps.setString(1, mobile_email);
ps.setString(2, mobile_email);
ps.setString(3, password);
ResultSet rs=ps.executeQuery();
if(rs.next())
{
HttpSession s=request.getSession();
s.setAttribute("mob", mobile_email);
out.print(1);
String ipadd=rs.getString("ip");
String stat=rs.getString("status");
if(ipadd.equals("")||ipadd.equals(ipAddress))
{
PreparedStatement ps3=con.prepareStatement("update user_registration set status=?, ip=? where (mobile=? or email_id=?)");
ps3.setString(1,"ONLINE");
ps3.setString(2, ipAddress);
ps3.setString(3,mobile_email);
ps3.setString(4,mobile_email);
int count=ps3.executeUpdate();
if (loginDTO == null) {
loginDTO = new LoginDTO();
loginDTO.setLoginID(mobile_email);
loginDTO.setPassword(password);
session.setAttribute("loginDTO", loginDTO);
session.setAttribute("loginStatus", "logged-in");
}
PersonalInfoDTO personalInfoDTO = new PersonalInfoDTO();
if (rs.getString("fname") != null) {
personalInfoDTO.setFirstName(rs.getString("fname"));
}
if (rs.getString("lname") != null) {
personalInfoDTO.setLastName(rs.getString("lname"));
}
String name = null;
if (rs.getString("fname") != null) {
name = rs.getString("fname");
}
if (rs.getString("lname") != null) {
name = name + " " + rs.getString("lname");
}
if (name != null) {
personalInfoDTO.setName(name);
}
if (rs.getString("email_id") != null) {
personalInfoDTO.setEmail(rs.getString("email_id"));
}
if (rs.getString("mobile") != null) {
personalInfoDTO.setMobile(rs.getString("mobile"));
}
if (rs.getString("gender") != null) {
personalInfoDTO.setGender(rs.getString("gender"));
}
if (rs.getString("blood_group") != null) {
personalInfoDTO.setBloodGroup(rs.getString("blood_group"));
}
if (rs.getString("dob") != null) {
personalInfoDTO.setDOB(rs.getString("dob"));
}
if (rs.getString("height_feet") != null) {
personalInfoDTO.setHeightFeet(rs.getString("height_feet"));
}
if (rs.getString("height_inch") != null) {
personalInfoDTO.setHeightInch(rs.getString("height_inch"));
}
if (rs.getString("height_cm") != null) {
personalInfoDTO.setHeightCentiMeter(rs.getString("height_cm"));
}
if (rs.getString("weight_hg") != null) {
personalInfoDTO.setWeightKG(rs.getString("weight_hg"));
}
if (rs.getString("weight_lbs") != null) {
personalInfoDTO.setWeightLBS(rs.getString("weight_lbs"));
}
loginDTO.setPersonalInfoDTO(personalInfoDTO);
AddressDTO addressDTO = new AddressDTO();
if (rs.getString("locality") != null) {
addressDTO.setLocality(rs.getString("locality"));
}
if (rs.getString("pincode") != null) {
addressDTO.setPincode(rs.getString("pincode"));
}
if (rs.getString("addr") != null) {
addressDTO.setAddr(rs.getString("addr"));
}
if (rs.getString("landmark") != null) {
addressDTO.setLandmark(rs.getString("landmark"));
}
if (rs.getString("Cityname") != null) {
addressDTO.setCity(rs.getString("Cityname"));
}
if (rs.getString("Statename") != null) {
addressDTO.setState(rs.getString("Statename"));
}
if (rs.getString("Countryname") != null) {
addressDTO.setCountry(rs.getString("Countryname"));
}
loginDTO.setAddressDTO(addressDTO);
//loginDTO.setImage(rs.getBinaryStream("image"));
loginDTO.setProfilePic(rs.getString("image"));
//System.out.println(rs.getString("image"));
// fetch if any item is available in the user cart or not
PreparedStatement ps1 = con.prepareStatement("SELECT test_kit FROM user_registration WHERE mobile=? OR email_id=?");
ps1.setString(1, loginDTO.getLoginID());
ps1.setString(2, loginDTO.getLoginID());
ResultSet rs1 = ps1.executeQuery();
if (rs1.next()) {
InputStream is = rs1.getBinaryStream(1);
if (is != null) {
ObjectInputStream ois = new ObjectInputStream(is);
HashMap<String, CartDTO> mapOfCartDTO = (HashMap<String, CartDTO>) ois.readObject();
session.setAttribute("mapOfCartDTO", mapOfCartDTO);
noOfCartItems = mapOfCartDTO.size();
session.setAttribute("noOfCartItems", noOfCartItems);
}
}
}
else{
out.print(2);
PreparedStatement ps3=con.prepareStatement("update user_registration set status=?, ip=? where (mobile=? or email_id=?)");
ps3.setString(1,"OFFLINE");
ps3.setString(2, "");
ps3.setString(3,mobile_email);
ps3.setString(4,mobile_email);
int count=ps3.executeUpdate();
System.out.println("Already Logged In. from another device.");
}
}
else{
out.print(0);
System.out.println("Invalid Username or Password");
}
}
}}
public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("LogoutServlet..........");
Connection con = null;
HttpSession session = request.getSession(false);
HttpSession s=request.getSession();
String mob=(String) s.getAttribute("mob");
String siginThrough = (String) session.getAttribute("siginThrough");
try{
con = ConnectionManager.getConnection();
PreparedStatement ps3=con.prepareStatement("update user_registration set status=?, ip=? where (mobile=? or email_id=?)");
ps3.setString(1,"OFFLINE");
ps3.setString(2, "");
ps3.setString(3,mob);
ps3.setString(4,mob);
int count=ps3.executeUpdate();
session.invalidate();
}
catch(Exception e)
{
e.printStackTrace();
}
//response.sendRedirect(getServletContext().getInitParameter("baseURL_USER"));
//response.sendRedirect("/scylla/");
if (siginThrough != null) {
if (siginThrough.equals("facebook")) {
response.getWriter().print(siginThrough);
} else if (siginThrough.equals("google")) {
response.getWriter().print(siginThrough);
}
} else {
response.getWriter().print(1);
}
}
}
You should add a parameter to achieve this.
One to contain the sessionvalidation, which should be a combination of IP and a boolean. eg (127.0.0.1-true)
you set the boolean as true when he logins from a browser and set as false once he logs out. Add a check in all pages to check this parameter to be true, and also on the IP of the accessing system and the IP in this variable. so that when he logs out, he will not be able to access from other browsers / computers.
I've got an error I can't seem to correct on my own
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");
}
response.sendRedirect("/SupTracking/index");
}
response.sendRedirect("/SupTracking/index");
}
I get an error in the response.sendRedirect("/SupTracking/admin"), saying that I can't use sendRedirect() because response is already sent.
The error should have been pretty straightforward, except that i don't understand WHERE i have sent anything in this code...
Here is the exact stack trace :
java.lang.IllegalStateException: Impossible d''appeler "sendRedirect()" après que la réponse ait été envoyée
org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:494)
com.SupTracking.servlets.admindeluser.doGet(admindeluser.java:39)
javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
what am I doing wrong?
Add a return statement after each redirection. Otherwise you redirect many times if one or both if conditions are true.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");
return;
}
response.sendRedirect("/SupTracking/index");
return;
}
response.sendRedirect("/SupTracking/index");
}
You can only call sendRedirect once for the response object. You should change your logic so you know it will only be called once like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");
}
else
{
response.sendRedirect("/SupTracking/index");
}
}
else
{
response.sendRedirect("/SupTracking/index");
}
}
Your problem is:
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
response.sendRedirect("/SupTracking/admin");******Called Here**********
}
response.sendRedirect("/SupTracking/index");*******Also Called Here**********
You can't redirect multiple times the response can only redirect to one page.
Because your sendRedirect() is called many times on response object as your conditions are becoming true.
Try this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session.getAttribute("username") != null) {
if ((boolean)session.getAttribute("usertype") == true) {
int userID = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();
User user = dao.ReturnUserID(userID);
dao.DeleteUser(user);
dao.Close();
}
}
response.sendRedirect("/SupTracking/index");
}
I have a web application where I want to prevent a user login multiple times (from different browsers on the same machine or from different machines).
I read about HttpSessionBindingListener and I tried to adapt my login servlet and my user Bean to implement the desired solution. Unfortunately it only works when I login the second time on the same browser (in a different tab) but if I change browser (on the same machine) it doesn't work anymore.
The code is as follows.
User Bean to put in session after successful login in
public class BeanUtente implements HttpSessionBindingListener {
private String username;
private String gruppo;
public boolean ruoloPresente(String nomeRuolo) {
//se il gruppo dell'utente è uguale a quello richiesto dal filtro
if (this.gruppo.equals(nomeRuolo))
return true;
else
return false;
}
public void valueBound(HttpSessionBindingEvent argo) {
System.out.println("Value Bound Called, " + argo.getValue() + " isNewSession: " + argo.getSession().isNew());
}
public void valueUnbound(HttpSessionBindingEvent argo) {
System.out.println("Value UnBound Called, " + argo.getValue() + " isNewSession: " + argo.getSession().isNew());
}
public String toString() {
return "Username is: " + username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getGruppo() {
return gruppo;
}
public void setGruppo(String gruppo) {
this.gruppo = gruppo;
}
}
Login servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Db db = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
response.setHeader("Cache-Control","no-cache,no-store,must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader("Expires", 0);
Locale locale = request.getLocale();
ResourceBundle labels = ResourceBundle.getBundle("risorse.label", locale);
String urlLoginOk = getInitParameter("urlLoginOk");
String urlLoginKo = getInitParameter("urlLoginKo");
String username = request.getParameter("username");
String password = request.getParameter("password");
db = new Db();
db.apriConnessione();
String sql = "SELECT gruppo FROM Utenti WHERE username=? AND password=SHA2(?, 512)";
ps = db.getConnection().prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
//login OK
if(username != null && password != null && rs.next()) {
BeanUtente beanUtente = new BeanUtente();
beanUtente.setUsername(username);
beanUtente.setGruppo(rs.getString("gruppo"));
HttpSession sess = request.getSession();
sess.setAttribute("beanUtente", beanUtente);
request.getRequestDispatcher(urlLoginOk).forward(request, response);
}
//login KO
else {
request.setAttribute("errore", labels.getString("loginFallito"));
request.getRequestDispatcher(urlLoginKo).forward(request, response);
}
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(!ps.isClosed())
ps.close();
if(!rs.isClosed())
rs.close();
}
catch (SQLException sqle) {
sqle.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if(db.getConnection() != null)
db.chiudiConnessione();
}
}
}
Here is the log.
When I login the first time, I get:
*Value Bound Called, Username is: pi isNewSession: false*
When I login the second time from the same browser, I get:
*Value Bound Called, Username is: pi isNewSession: false
Value UnBound Called, null isNewSession: false*
So it seems the UnBound method is correctly called.
However, if I login the third time from another browser on the same machine, I get:
*Value Bound Called, Username is: pi isNewSession: false*
that is, the UnBound method has not been called.
Can you help me to understand where is my mistake?
I suppose I have to explicity invoke session.removeAttribute("beanUtente") but when/where?
Thanks in advance for any help :)
To avoid login from multiple browser,i don't think so that HttpSessionBindingListener will work,because with new browser,it will create new session.
You will have to save the state at your backend for the particular user,let say userId for each user,may be in cache/DB,once he login, and remove it from cache/DB once he log out,
So when user login do like below.
Object user = getUser(userId);
if(user != null){
// user already logged in,just return custom message
}
else{
// Allow user to login
}
Similary on logout remove the userId from cache/user.
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.mvcMatchers("/").permitAll()
.and().sessionManagement()
.maximumSessions(1);
}
I have my servlet:
public class Authentification extends HttpServlet {
public int id1;
private static final long serialVersionUID = 1L;
public HttpSession session;
Authentification_link auth=new Authentification_link();
public Integer IdUser;
public Authentification() {
super();
}
public void init() {
Codb co= new Codb();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
int IdUser = Integer.valueOf(request.getParameter("id"));
session.setAttribute("ide", IdUser);
try {
if(auth.authen(IdUser)){
session.setAttribute("id", IdUser);
request.getRequestDispatcher("acceuil.jsp").forward(request, response);
System.out.println("found");}
else{
request.getRequestDispatcher("index.jsp").forward(request, response);
System.out.println("not found");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doInteret (HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
IdUser = (Integer) session.getAttribute("IdUser");
Interets inte= new Interets (IdUser);
}
}
The user login to through an id, the authentification works fine, but now I want to get the same user's id so I can include it in this java classe when the user click on a link. For that I added the method doInteret in the servlet and the class Interet.java is like this:
public class Interets {
static Statement St ;
public ResultSet rs;
public Interets(Integer IdUser) throws SQLException, ServletException, IOException{
String res=" ";
try{
ResultSet result = St.executeQuery("SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar="+IdUser+"");
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
while(result.next()){
String Newligne=System.getProperty("line.separator");
for(int i = 1; i <= resultMeta.getColumnCount(); i++){
res=res+Newligne+result.getObject(i).toString();
System.out.println(res);
}
}
}
catch (Exception e) {
System.out.println("Error in Select ");
}
}
}
but I am getting this error:
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: pack1.Interets.AfficheInteret()Ljava/lang/String;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:412)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
try changing your query and print it may be your query is not working
SELECT description FROM interets, avoir, consomateur WHERE avoir.id_interet=interets.id_interets AND avoir.id_user=consomateur.code_bar AND consomateur.code_bar='"+IdUser+"'");