suggestions on creating a admin page using jsp - java

I am pretty new in developing web applications using Java. I have developed a small application which is a login & registration page both of which are working fine. Now, I have decided on making a admin page(using jsp). In my java code I control the redirection of jsp pages (if user!="admin"then home.jsp else user=="admin" then admin.jsp). in my admin page what I want to do is I want the admin to be able to view all the users registered and can edit their details or delete them. Someone can please suggest me on how to achieve this.
Login Servlet.java(code where I decide between admin & regular user)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String password = request.getParameter("password");
String errorMsg = null;
String name;
if(email == null || email.equals("")){
errorMsg ="User Email can't be null or empty";
}
if(password == null || password.equals("")){
errorMsg = "Password can't be null or empty";
}
if(errorMsg != null){
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>"+errorMsg+"</font>");
rd.include(request, response);
}else{
Connection con = (Connection) getServletContext().getAttribute("DBConnection");
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("select id, name, email,country from Users where email=? and password=?");
ps.setString(1, email);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs != null && rs.next()){
User user = new User(rs.getString("name"), rs.getString("email"), rs.getString("country"), rs.getInt("id"));
name=rs.getString("name");
System.out.println("Name:"+ name);
//if(rs.getString("name")!="admin")
if(!name.equalsIgnoreCase("admin"))
{
logger.info("User found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("home.jsp");
}
// String rs1=rs.getString();
else if(name.equalsIgnoreCase("admin"))
{
logger.info("Admin found with details="+user);
HttpSession session = request.getSession();
session.setAttribute("User", user);
response.sendRedirect("admin.jsp");
}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
logger.error("User not found with email="+email);
out.println("<font color=red>No user found with given email id, please register first.</font>");
rd.include(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
logger.error("Database connection problem");
throw new ServletException("DB Connection problem.");
}finally{
try {
rs.close();
ps.close();
} catch (SQLException e) {
logger.error("SQLException in closing PreparedStatement or ResultSet");;
}
}
}
home.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="com.javadbproject.util.User"%>
<%# 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>Home Page</title>
<link rel="stylesheet" type="text/css" href="<c:url value='/loginstyle.css'/>">
</head>
<body>
<%User user = (User) session.getAttribute("User"); %>
<h3>Hi <%=user.getName() %></h3>
<strong>Your Email</strong>: <%=user.getEmail() %><br>
<strong>Your Country</strong>: <%=user.getCountry() %><br>
<br>
<form action="Logout" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</html>
AuthenticationServlet
package com.javadbproject.servlet.filters;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
#WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {
private Logger logger = Logger.getLogger(AuthenticationFilter.class);
public void init(FilterConfig fConfig) throws ServletException {
logger.info("AuthenticationFilter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
logger.info("Requested Resource::"+uri);
HttpSession session = req.getSession(false);
if(session == null && !(uri.endsWith("html") || uri.endsWith("Login") || uri.endsWith("Register"))){
logger.error("Unauthorized access request");
res.sendRedirect("login.html");
}else{
// pass the request along the filter chain
chain.doFilter(request, response);
}
}
public void destroy() {
//close any resources here
}
}
I am looking to develop my admin.jsp on the similar lines as my home.jsp
Thanks!!

You need a database mysql would be nice to start with.
You need to have a mysql connector jar file.
Create a class User for example.
public class User{
String iduser;
String name;
String username;
String password;
//setters and getters
}
Create a table for user in mysql or any database that you have.
CREATE TABLE sampleapplication.user (
iduser INT NOT NULL AUTO_INCREMENT ,
name VARCHAR(45) NULL ,
username VARCHAR(45) NULL ,
usercol VARCHAR(45) NULL ,
PRIMARY KEY (iduser) );
Let's start the database with java. :) add the mysql connector jar file in your build path (right click project > Build path > Configure build path > Click Add external jar > Locate mysql connector), and paste it in your web-inf>lib folder.
Create a class for database transaction. for reference
public class DatabaseTransaction{
public List<User> readDataBase() throws Exception {
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
connect = DriverManager
.getConnection("jdbc:mysql://localhost/database?"
+ "user=sqluser&password=sqluserpw");
// statements allow to issue SQL queries to the database
statement = connect.createStatement();
// resultSet gets the result of the SQL query
resultSet = statement
.executeQuery("select * from user");
List<User> listOfUsers=new ArrayList<User>();
User userToAdd;
while (resultSet.next()) {
userToAdd = new User();
userToAdd.setUsername(resultSet.getString("username"));
userToAdd.setPassword(resultSet.getString("pword"));
userToAdd.setUserid(resultSet.getString("userid"));
userToAdd.setName(resultSet.getString("name"));
listOfUsers.add(userToAdd);
}
}
}
call the DatabaseTransaction to your filter/controller/servlet
DatabaseTransaction databaseTransaction = DatabaseTransaction();
//use your `HttpServletRequest`
//parameters are key and value
//store as attribute to access in jsp page
request.setAttribute("userList",databaseTransaction.readDataBase());
//then forward the page using `HttpServletRequest`
//dont use response.redirect(); you wont be able to use the attribute because you are using a response
//filename of the jsp
request.getRequestDispatcher("adminpage").forward(request, response);
In your jsp page. use JSTL
//import the core tag library
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
//lastly loop through the list attribute
<table>
<thead>
<tr>
<td>id</td>
<td>Name</td>
<td>Username</td>
</tr>
</thead>
<tbody>
<c:foreach items="${userList}" var="user">
<tr>
<td><c:out value="${user.iduser}"/></td>
<td><c:out value="${user.name}"/></td>
<td><c:out value="${user.username}"/></td>
</tr>
</c:foreach>
</tbody>
</table>
thats all :)

Servlet Filter is what you need, you need a logical roles for each user and allowable URL patterns per role configured and a Filter filtering each request and blocking/allowing based on it

Related

How to configure the return in AMP-Access?

In theory when the AMPByExample server receives the POST request
from the login page, if the credentials are correct, it will redirects
the request to the URL of returnURL and the parameter is added
success = true. Once done, the AMP execution time can finally
authorize the page.
The login page is the following:
login.jsp
<%#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 method="post" action="loginauthorization">
Correo Electronico: <input type="text" name="correo"><br>
ContraseƱa: <input type="password" name="clave"><br>
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=https%3A%2F%2Fampbyexample.com%2Fplayground%2F">
<input type="submit" value="Ingresar">
</form>
</body>
</html>
As you can see, in the returnurl it is the same login URL ofAmpByExample and it does not work.
I already tried to make my own url in the following way:
<input name="returnurl" type="hidden" value="https://cdn.ampproject.org/v0/amp-login-done-0.1.html?url=http%3A%2F%2Flocalhost%3A8084%2Fmypage%2Fpanel.jsp">
And it doesn't work either.
In the servlet loginauthorization.java I receive thatreturnurl and I add the # success = true (supposedly I must verify username and password, but I want to make it work first).
loginauthorization.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class loginauthorization extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
response.setContentType("text/html");
//I get the parameters
String email = request.getParameter("correo");
String password = request.getParameter("clave");
String url = request.getParameter("pageurl");
int ridini = url.indexOf("rid=")+4;
int ridend = url.indexOf("&url=");
String rid = url.substring(ridini, ridend);
String returnurl = request.getParameter("returnurl");
//assuming that the username and password are correct, add to the returnurl success true
returnurl= returnurl + "#success=true";
//create a session
HttpSession session=request.getSession();
session.setAttribute("umail",email);
session.setAttribute("upass",password);
session.setAttribute("rid",rid);
session.setAttribute("returnurl",returnurl);
//redirect after login with the success = true
response.sendRedirect(returnurl);
}catch(Exception exp){
System.out.println(exp);
}
}
}
The configuration of the panel is as follows:
panel.jsp
<script id="amp-access" type="application/json">
{
"authorization": "http://localhost:8084/mypage/jsonauthorization",
"noPingback": "true",
"login": {
"sign-in": "/mypage/login.jsp?rid=READER_ID&url=CANONICAL_URL&return=RETURN_URL",
"sign-out": "/mypage/endsession"
},
"authorizationFallbackResponse": {
"loggedIn": false
},
"type": "server"
}
</script>
The jsonauthorization prints{"loggedIn": true}or{"loggedIn": false}:
jsonauthorization.java
import java.io.*;
import javax.servlet.http.*;
public class jsonauthorization extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("application/json");
response.setHeader("AMP-Access-Control-Allow-Source-Origin", "http://localhost:8084/mypage");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
if(session != null){
String email=(String)session.getAttribute("umail");
if(email==null){
session.invalidate();
pwriter.print("{\"loggedIn\":false}");
}else{
String rid;
rid = (String) session.getAttribute("rid");
Cookie AmpCookie = new Cookie("authorized",rid);
AmpCookie.setPath("/");
AmpCookie.setDomain("/mypage");
response.addCookie(AmpCookie);
pwriter.print("{\"loggedIn\":true}");
}
}else{
pwriter.print("{\"loggedIn\":false}");
}
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
I appreciate the answers, if the error is not in the returnurl please tell me where :P
I am also trying to figure out AMP integration with login/registration. Not sure if this will help, but I found that the return url is automatically added to the url param, so you don't necessarily have to add it to your sign-in url within your initialization json object.
I figured out, it is not necessary to configure the return url. Simply add the hidden input inside the html in order to close the login window and read the json url approving the login.
Just like this:
<input name = "returnurl" type = "hidden" value = "https://cdn.ampproject.org/v0/amp-login-done-0.1.html">
Then, if the json url aproves the login it will works.
Actually the code is fine, the problem was in the json generator file.
CORS problems. Is necessary to set the header "AMP-Access-Control-Allow-Source-Origin" right.

Connect MySql with Servlet for login page

How to connect MySql dataBase with servlet for login page?
For now in servlet I have code for predefined username (gogikole) and password (1234)
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("gogikole") && password.equals("1234")) {
response.sendRedirect("mainMenu.jsp");
return;
}
but how to check is username and password are correct for some other users from database?
For example username: konsta, password: 4321
I have code like this:
Login Servlet
package servlets;
import java.io.IOException;
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.sql.*;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username.equals("gogikole") && password.equals("1234")) {
response.sendRedirect("mainMenu.jsp");
return;
}
}
}
login.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>Login page</title>
</head>
<body>
<form method="post" action="LoginServlet">
<table align="center">
<tr>
<td>User name</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Also I already added mysqlconnector to Eclipse.
First,you should connect to mysql use MysqlConnection.
Then,create a statement use sql like SELECT * FROM users WHERE username = :username AND password = :password.Then execute it.
You will got a resultSet which contains the results of match user,of course,if username or password is wrong,the resultSet is empty.
The key to slove your problem is you should query to database instade of username.equals("gogikole") && password.equals("1234")
Example:
final String DB_URL = "localhost:3306/db"; //Mysql Address
final String USER = "root"; //mysql username
final String PASS = "123456";//mysql password
final String SQL = "SELECT * FROM users WHERE username = ? AND password = ?"; //SQL
String username = request.getParameter("username");
String password = request.getParameter("password");
Connection conn = null; //mysql connection
Statement stmt = null; //mysql statement
Class.forName("com.mysql.jdbc.Driver"); //register driver
conn = DriverManager.getConnection(DB_URL,USER,PASS); //get connection
stmt = conn.prepareStatement(SQL); //create statement
//init param
stmt.setString(1,username);
stmt.setString(2,password);
ResultSet rs = stmt.executeQuery(); //execute query
if(rs.first()){ //finded
response.sendRedirect("mainMenu.jsp");
return;
}

Displaying the result set values from servlet to jsp

I need help in forwarding the result set values from servlet to jsp without using JSTL implementation
Work flow :
The user enters a value in text box and clicks search button
On clicking search the servlet is called.
The servlet focuses on the database implementation and forward the result set values to the same jsp page from where the request comes.
Issue:
My result set size is 3, but the value which is in the top of my table alone is getting printed in my jsp page. The remaining 2 values are missing.I want all the values to be printed in my jsp page.
This is my code:
Productlist.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Products</title>
</head>
<body>
<form method="post" align="center" action="ProductList">
Company Name:<input type="text" size="20" id="company" name="company" />
<input type="submit" value="search"/>
<%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<br/>" + prod.getProductname());
}
}
%>
</form>
</body>
</html>
Products.java
public class Products {
private String productname;
public String getProductname() {
return productname;
}
public void setProductname(String productname) {
this.productname=productname ;
}
}
ProductList.java(servlet-code)
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 java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class ProductList extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs = null;
Connection connection = null;
List<Products> pdt = new ArrayList<Products>();
try{
String company =request.getParameter("company");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="select product_pck from comp_pdt_list where company_name='"+company+"'";
PreparedStatement prep = connection.prepareStatement(sql);
rs=prep.executeQuery();
while(rs.next()) {
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);
return;
}
prep.close();
} catch(Exception E) {
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
} finally {
try {
connection.close();
} catch (Exception ex) {
System.out.println("The error is" + ex.getMessage());
}
}
}
}
You set the attribute to request in your while loop. So the "list" contains only one product. (method returns on first iteration)
Add products to the list in while loop and set your list (request attribute) only after while loop.
Following should fix it:
while(rs.next()){
Products prod=new Products();
prod.setProductname(rs.getString("product_pck"));
pdt.add(prod);
}
request.setAttribute("list",pdt);
RequestDispatcher rd=request.getRequestDispatcher("Productlist.jsp");
rd.forward(request,response);

Ajax Unique user name search fails JSP

I'm trying to create simple unique username check following this tutorial.
http://javaandj2eetutor.blogspot.com/2013/12/check-username-availability-using-java.html
But My ajax call for username is fails. I'm new to ajax and somewhat new for jsp.
Here is my index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Username Availability</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
$(".username").change(function () {
var username = $(this).val();
if (username.length >= 3) {
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "CheckAvalability",
data: "uname="+ username,
success: function (msg) {
$(".status").ajaxComplete(function (event, request, settings) {
$(".status").html(msg);
});
}
});
}
else {
$(".status").html("<font color=red>Username should be <b>3</b> character long.</font>");
}
});
});
</script>
<div>
<label class="flable">User Name :</label> <input class="username" type="text" name="username"> <span class="status"></span>
</div>
</body>
</html>
Here is my Servlet
package hsenid;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class CheckAvailability extends HttpServlet {
private static final Logger logger = LogManager.getLogger(CheckAvailability.class);
private static final long serialVersionUID = -734503860925086969L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
logger.info("Check availability called");
DBConnector dbPool = (DBConnector)getServletContext().getAttribute("DBConnection");
Connection myConn = dbPool.getConn();
String uname = request.getParameter("username");
PreparedStatement ps = myConn.prepareStatement("select username from userdetails where username=?");
ps.setString(1,uname);
ResultSet rs = ps.executeQuery();
if (!rs.next()) {
out.println("<font color=green><b>"+uname+"</b> is avaliable</font>");
logger.info("Username detected!!!");
}
else{
out.println("<font color=red><b>"+uname+"</b> is already in use</font>");
}
out.println();
} catch (Exception ex) {
out.println("Error ->" + ex.getMessage());
} finally {
out.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
Here is my servlet mapping in web.xml.
<servlet>
<servlet-name>CheckAvailability</servlet-name>
<servlet-class>hsenid.CheckAvailability</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CheckAvailability</servlet-name>
<url-pattern>/CheckAvailability</url-pattern>
</servlet-mapping>
This detects if minimum characters aren't added and also gives the massage check availability when type in there so I think jquery is added. Also I've run the servlet in Eclipse Mars. It do check the if a username is in the table or not. So I believe that the problem calling to the servlet because I can't see the log4j console output then. I'm unable find what wrong with my code.
Thanks in advance

How should I create this new page? JSP or servlet?

I am completely new to web development and I would like some help please. I am doing a payroll system web application project using Java Eclipse EE, tomcat server and mysql. I used a tutorial and managed to create the login interface below. So right now, when i click enter my login details and click login (at localhost:8080/Payroll) I want it to go to a web page (which I have no idea how to create) and display a list of buttons (any random buttons which I can later rename). Can someone please help me. I have no idea about how to use .JSP, .html, .java and I am really confused about how these file types will help me get what I want. Please help someone, I just want the login button to redirect to a web page with buttons on it. Thank you.
Login.java (Servlet)
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String employee_id = request.getParameter("employee_id");
String password = request.getParameter("password");
if(Validate.checkUser(employee_id, password)) {
RequestDispatcher rs = request.getRequestDispatcher("**SOME FILE NAME HERE TO REDIRECT TO?**");
rs.forward(request, response);
}
else
{
out.println("Employee ID or Password is incorrect. Please try again.");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="login" method="post">
<h3>
Employee Login
</h3>
<b>Employee ID:</b> <br>
<input type="text"name="employee_id" size="20"><br><br>
<b>Password:</b><br>
<input type="password" name="password" size="20"><br><br>
<input type="submit" value="Login"><br><br>
</form>
</body>
</html>
Validate.java (class file)
import java.sql.*;
public class Validate
{
public static boolean checkUser(String employee_id, String password)
{
boolean st = false;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps = con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ?");
ps.setString(1, employee_id);
ps.setString(2, password);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
As your index.html is already a "page with buttons" this seems to work for you.
However, if your page will include dynamic data, you're better of with jsp.
You might want to start by setting the username into the session and go display that in jsp:
request.setAttribute("user", employee_id);
RequestDispatcher rs = request.getRequestDispatcher("stackoverflow.jsp");
rs.forward(request, response);
And in stackoverflow.jsp
<h2><%= request.getAttribute("user") %></h2>
Now compare calling the jsp directly and when invoked through login...
Make sure to read on MVC in web projects and consider using a framework (like Spring) once you have a feel for the concepts.
Some notes on your code:
You don't ever close Connection, Statement, ResultSet. Consider a connection pool and try-with-resource:
public static boolean checkUser(String employee_id, String password)
{
boolean st = false;
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/payroll_system", "root", "");
PreparedStatement ps =
con.prepareStatement("select * from employee_login where employeeID = ? and pwd = ?")) {
ps.setString(1, employee_id);
ps.setString(2, password);
try(ResultSet rs =ps.executeQuery()) {
return rs.next();
}
}catch(Exception e) {
e.printStackTrace();
}
return false;
}

Categories