How to keep a user logged in? - html

I'm trying to keep a user logged in after they have entered their details on the login screen. I'm using apache tomcat and MS access database. I can log in with a user stored in my database. But I can't figure out how to keep the user logged in throughout my website. I have been reading up about sessions and trying sample code but I can't get it to work, I keep getting different errors. I managed to "Welcome" the user by name after login, but I can't keep the welcome user message, if I click on any other of my webpages.
loginJsp.jsp-
<sql:setDataSource
var = "bookdB"
scope = "session"
driver = "sun.jdbc.odbc.JdbcOdbcDriver"
url = "jdbc:odbc:bookdB"
/>
<sql:query var ="NameCheck" scope = "session" dataSource = "${bookdB}">
SELECT * FROM Users
WHERE Username = ?
AND Password = ?
<sql:param value = "${param.user}" />
<sql:param value = "${param.password}" />
</sql:query>
<c:if test = "${NameCheck.rowCount == 0}">
<jsp:forward page = "loginError.html"/>
</c:if>
<c:if test = "${NameCheck.rowCount != 0}">
<jsp:forward page = "index.jsp"/>
index.jsp
<sql:query dataSource="${bookdB}" var="result">
SELECT * FROM Users
WHERE Username = ?
AND Password = ?
<sql:param value = "${param.user}" />
<sql:param value = "${param.password}" />
</sql:query>
<font color="orange" face="Futura Std-Light" size="4">
<c:forEach var="row" items="${result.rows}">
Welcome ${row.FirstName}!
</c:forEach>
</font>
Any help would be much appreciated, Thanks!
Is this right:
<c:if test = "${NameCheck.rowCount == 0}">
HttpSession session = request.getSession();
session.setAttribute("connecte", "true");
session.setAttribute("login", "${param.user}");
<jsp:forward page = "loginError.html"/>
</c:if>

in your servlet action handler add this:
HttpSession session = request.getSession();
session.setAttribute("connecte", "true");
session.setAttribute("login", "TOM");
in your JSP add this on the top of your page
<%
if (session.getAttribute("connecte") == null
|| !((String) session.getAttribute("connecte"))
.equals("true")) {
String redirectURL = "/path/ToYour/login.jsp;
response.sendRedirect(redirectURL);
}
%>
<h1>Hello <%= session.getAttribute("login") %></h1>
if it's OK it will show
Hello Tom
#
login.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
#
LoginServlet.java:
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "Pankaj";
private final String password = "journaldev";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
Cookie loginCookie = new Cookie("user",user);
//setting cookie to expiry in 30 mins
loginCookie.setMaxAge(30*60);
response.addCookie(loginCookie);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
#
LoginSuccess.jsp:
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!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=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
String userName = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
if(userName == null) response.sendRedirect("login.html");
%>
<h3>Hi <%=userName %>, Login successful.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>

Related

Java Servlet and JSP cannot view arraylist from session initially

I'm a complete beginner to JSPs and servlets and I would appreciate it if you could help me on this small problem. I have an index.html file that has links to two JSP files: addItem.jsp (user can input item into their todDo list, and submit button links to servlet), and toDoList.jsp (shows the toDO list and redirects via a button to addItem.jsp)
The problem I am having is that when I view the toDoList.jsp before adding an item to the list, the list does not appear. However, I add an item on addItem.jsp, the list shows from the servlet, and now I can view the full list, including the item that was added on toDoList.jsp.
How can I change my code so that I don't have to add something to the list to view it?
toDoList.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="javax.servlet.http.HttpSession" %>
<%#page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>My ToDo List:</h1>
<% ArrayList<String> toDoList = new ArrayList<String>();%>
<% if(session.getAttribute("toDoList") != null) { // If the list exists in the session %>
<% toDoList = (ArrayList<String>) session.getAttribute("toDoList");%>
<% for(String toDoItem:toDoList) { %>
<% out.println(toDoItem); %><br>
<% } %>
<% } else {%>
<h3>Your list is empty!</h3>
<% } %>
<form action="addItem.jsp" method="post">
<fieldset>
<input type="submit" value="Add Item">
</fieldset>
</form>
</body>
addItem.jsp :
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Servlet1" method="post">
<fieldset>
<label>New ToDo Item:</label>
<input type="text" name="item"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
The main Servlet1 code:
#WebServlet(urlPatterns = {"/Servlet1"})
public class Servlet1 extends HttpServlet {
ArrayList<String> toDoList = new ArrayList<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String item = request.getParameter("item");
toDoList.add(item);
HttpSession session = request.getSession();
boolean is_toDoList_Initilized = false;
if(session.getAttribute("toDoList") == null) {
is_toDoList_Initilized = false;
session.setAttribute("toDoList", toDoList);
} else is_toDoList_Initilized = true;
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Servlet1</title>");
out.println("</head>");
out.println("<body>");
for(String toDoItem:toDoList) {
out.println(toDoItem + "<br>");
}
out.println(is_toDoList_Initilized);
out.println("</body>");
out.println("</html>");
}
}
I think you just need to call that servlet before redirecting your toDoList.jsp from your index page.
Flow will be like
flow 1: index.jsp > servlet1 > toDoList
flow 2: index.jsp > addItem.jsp > servlet1 > toDoList

How to get value of generated row value for another action when generated submit button is clicked

I want to know how to get dynamically generated table row value (eg. empp_id) when clicking submit button that is generated for each row dynamically.
Below is my code. I used to generate each row and submit button for each row. I don't know how to use submit button to get and pass the value of 'id' column to another action.
Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" namespace="/" extends="struts-default">
<action name="edit" class="com.ojt.database.EditUserAction" method="execute">
<result name="success">edituser.jsp</result>
<result name="error"></result>
</action>
</struts>
EditUserAction.java
package com.ojt.database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
#SuppressWarnings("serial")
public class EditUserAction extends ActionSupport {
List<User> liUser=null;
public List<User> getLiUser() {
return liUser;
}
public void setLiUser(List<User> liUser) {
this.liUser = liUser;
}
#Override
public String execute() throws Exception {
Connection conn;
String ret = "error";
try {
String url = "jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, "root", "root");
String sql = "SELECT * FROM user";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
liUser=new ArrayList<User>();
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setPassword(rs.getString(3));
liUser.add(user);
}
conn.close();
ret = "success";
System.out.println(ret);
} catch (Exception e) {
e.printStackTrace();
ret = "error";
System.out.println(ret);
}
return ret;
}
}
edituser.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="display" uri="http://displaytag.sf.net/el"%>
<!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>Edit</title>
</head>
<body>
<table cellpadding="20" align="center">
<tr>
<th>Id</th>
<th>Name</th>
<th>Password</th>
</tr>
<s:iterator value="liUser">
<tr>
<td><s:property value="id" /></td>
<td><s:property value="name" /></td>
<td><s:property value="password" /></td>
<td><s:submit value="Edit" theme="simple" action="review" method="POST"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
I need your help please.
I can't go any further, i am stuck here.
When you use <s:property/>, you are not creating a form tag, but just simple text. To send something printed with <s:property/>, use an <s:hidden/> in conjunction with it.
To send a list of object from JSP, you need to use the IteratorStatus object to specify an index.
You are not even using a form. You need a form to POST something in the standard, non-AJAX way.
You need two action's methods, or two actions: one to display the data, the other to edit it. In your execute() method you are initializing your list every time: liUser=new ArrayList<User>();, so the one coming from the page will always be lost.
You are in deep water. I suggest you to stop for a moment and take a closer look at HTML, HTTP, Struts2 and its tags, otherwise you will get frustrated quite soon.

How to get multiple images for same id from database in jsp servlet

index.jsp
This is my jsp code
<%# page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<sql:setDataSource var="webappDataSource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/bharatwellness"user="root" password="naveen" />
<sql:query dataSource="${webappDataSource}" sql="select * from individaulpartner " var="result" />
<table width="100%" border="1">
<c:forEach var="row" items="${result.rows}">
<tr>
<td>${row.id}</td>
<td>${row.fname}</td>
<td>
<img src="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}" />
</td>
<td>
<a href="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}" />certificate</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
ImageGetTest.java
This my servlet code
package com.server.servlet;
import java.io.IOException;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
final String DB_URL = "jdbc:mysql://localhost/mydatabase";
final String User = "root";
final String Password = "password";
try {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, User, Password);
PreparedStatement stmt = conn.prepareStatement("select * from usertable where id=?");
stmt.setLong(1, Long.valueOf(request.getParameter("id")));
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
response.getOutputStream().write(rs.getBytes("image"));
response.getOutputStream().write(rs.getBytes("certificate1"));
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is my table from where i am fetching my data
I am able to show only single image or single certificate for one id . How can I show all file on jsp page. Please help me out...
You need to call the Sevlet for each individual image. So in your JSP you need to do somthing like:
<td>
<img src="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}&name=image" />
<img src="${pageContext.servletContext.contextPath }/ImageServlet?id=${row.id}&name=certificate" />
</td>
and in your Servlet check the additional 'name' parameter to determine which image to send back:
if (rs.next()) {
if(request.getParameter("name").equals("image")
response.getOutputStream().write(rs.getBytes("image"));
}else{
response.getOutputStream().write(rs.getBytes("certificate1"));
}
}
The problem with all of this is that it is not dynamic. To make it handle any number of images for a given entity you need to have some knowledge of the available images when the JSP is processed and have a loop which will generate an <img/> tag for each image and call the Servlet with the necessary paramaters.
This will also probably involve some database update: images go into a different table with a FK to the corresponding user.
img_id user_id image_data
1 1 bytes
2 1 bytes
3 1 bytes
4 1 bytes
Now you get a handle on the image ids for the relevant user and load them one-by-one by passing the id to the Servlet.

display blob image in jsp (javax.servlet.ServletException: java.sql.SQLException: Column '2' not found.)

I am trying to display a blob image in a jsp page by (using this) but i am getting an error:
javax.servlet.ServletException: java.sql.SQLException: Column '2' not found.
My table is:
create table upload_image
(
iImageID int AUTO_INCREMENT primary key,
bImage longblob
);
Code: uploadimage.jsp
<%# page language="java" errorPage="" %>
<html>
<head>
<title>Image insert into database</title>
</head>
<body>
<form name="frm" action="saveImage.jsp" enctype="multipart/form-data" method="post">
<input type="file" name="uProperty" /> <br>
<input type="submit" name="goUpload" value="Upload" />
</form>
</body>
</html>
saveImage.jsp
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="org.apache.commons.io.output.*"%>
<%# page import="org.apache.commons.fileupload.servlet.*"%>
<%# page import="org.apache.commons.fileupload.disk.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<%
Connection conn=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/online","root", "12345");
PreparedStatement psImageInsertDatabase=null;
byte[] b=null;
try{
String sqlImageInsertDatabase="insert into upload_image (bImage) values(?)";
psImageInsertDatabase=conn.prepareStatement(sqlImageInsertDatabase);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
b = item.get();
}
}
psImageInsertDatabase.setBytes(1,b);
psImageInsertDatabase.executeUpdate();
}
catch(Exception e)
{
e.printStackTrace();
response.sendRedirect("addimage.jsp");
}
%>
get.jsp
<%# page import ="java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/online","root", "12345");
Statement st = con.createStatement();
ResultSet i = st.executeQuery("select * from upload_image");
%>
<%
while(i.next( )){
%>
<img src="imageServlet?id=<%=i.getString("2")%>" />
<% }%>
After executing the get.jsp (after executing uploadimage.jsp) I am getting "Column '2' not found." Please help me to display the image in the jsp page
Its throwing an error cause it is finding a column named as 2 since you have put 2 in double quotes.Also I feel it should be 1 and not 2(but you know better)
This is the answer below
<img src="imageServlet?id=<%=i.getString(1)%>" />//with no quotes as you can see
or
<img src="imageServlet?id=<%=i.getString("iImageID")%>" />

JSP and MYSQL: how do I relay a SQL Exception

I am trying to create a login screen which will allow a user to enter a unqiue ID. How do I relay the information to a user that the ID chosen is not unique. So far all I'm able to do is trigger the exception.
Registration.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>Enter Your details here</title>
</head>
<body>
<h3>Enter User ID</h3>
<br>
<form action = "RegistrationServlet" method = "post">
Enter User ID : <input type = "text" name ="newUserId"/>
<br>Enter your Password : <input type = "password" name ="newUserPassword"/>
<br>Enter your First Name :<input type = "text" name = "newUserFirstName"/>
<br>Enter your Last Name : <input type = "text" name ="newUserLastName"/>
<br><input type = "submit"/>
<br>
<%=session.getAttribute("notUniqueUserID")%>
</form>
</body>
</html>
RegististrationServlet
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
boolean notUniqueUserID = true;
request.getSession(notUniqueUserID);
response.sendRedirect("registration.jsp");
}
This is not the best solution as it will reload the form and the user will need to enter all the data again, I would suggest you to use AJAX for this kind of verification.
Anyway here is a piece of code to set one attribute to the request and get it in the jsp.
Servlet:
}catch (SQLException e) {
e.printStackTrace();
boolean notUniqueUserID = true;
request.setAttribute("notUniqueUserID", "Not Unique User ID");
request.getRequestDispatcher("registration.jsp").forward(request, response);
}
JSP:
<%=request.getAttribute("notUniqueUserID")%>