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;
}
Related
I am trying to get the servlet program to connect with the database and perform actions. In eclipse, when I put the connection and queries in the main() method and choose "Run as java application" it is working and the database is being updated, however, when I launch the html using "Run on server" and put the queries in the doGet() method, the servlet is running and html is being updated in the browser, but, no update is being done in the database. I also tried putting the code in the main method and calling main() through doGet() with no success.
html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Register</title>
</head>
<body>
<form action="register" method="get">
<label for="uname">Username:</label>
<input type="text" name="uname">
<label for="pwd">Password:</label>
<input type="text" name="pwd">
<button type="submit">Register</button>
</form>
</body>
</html>
doGet() method:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// response.getWriter().append("Served at: ").append(request.getContextPath());
PrintWriter pw = response.getWriter();
String uname = request.getParameter("uname");
String pwd = request.getParameter("pwd");
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/advjavada", "root", "");
if(!con.isClosed()) {
System.out.println("Connection SUCCESSFUL!");
PreparedStatement ps = con.prepareStatement("insert into userdata(uname, pwd) value('sample2', 'sampass2');");
//ResultSet rs = ps.executeQuery();
ps.executeQuery();
}
else {
System.out.println("Connection FAILED!");
}
}
catch (Exception e) {
System.err.print(e.getMessage());
}
pw.println("<h1>Hello, " + uname + "!</h1><p>Registration Successful</p>");
pw.close();
}
Tahir Hussain Mir's answer on this question has resolved the issue.
As it turns out, it's a problem during deployment in which the external jar file for SQL is used for compilation but is not included during runtime.
To solve this:
Add the .jar file to the Deployment Assembly under Project > Properties.
I am trying this for a while but every time when i try to run on browser it shows nothing, not even an error.
"index.html" file
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
"web.xml" file
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" >
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
"Register.java" file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/db","myuser","1234");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
This image is after i entered the details, and there is no data stored in my database
This is the error showing in cmd
I am using JDK 9 which have no "ext" file in the JRE so i included JDBC driver file through command line.
I have created database 'db' in mysql and table name 'student'.
I don't know where is the problem. Please help me!!
You do not close Connection and PreparedStatement.
Best use try-with-resources for that. There was a space in the connection URL.
The other problem was already mentioned.
try (Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/db","myuser","1234");
PreparedStatement ps=con.prepareStatement
("insert into Student (name,email,pass) values(?,?,?)")) {
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
ps.executeUpdate();
} catch(Exception se) {
se.printStackTrace();
}
Your form method is post:
<form method="post" action="register">
And in your servlet you only have a doGet.
Change your form method to get:
<form method="get" action="register">
Servlet doGet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/ /localhost:3306/db","myuser","1234");
PreparedStatement ps=con.prepareStatement
("insert into Student (name,email,pass) values(?,?,?);");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
ps.executeUpdate();
}catch(Exception se){
se.printStackTrace();
}
//redirect user back to index
RequestDispatcher rd=request.getRequestDispatcher("index.html");
rd.forward(request,response);
}
}
I am trying to create a login page using jsp and postgress.The login is not working .The index.jsp page always says Sorry, email or password error.
The index page is the welcome page .It points to loginprocess.jsp.and a bean LoginDao.java is called.
index.jsp
<form action="loginprocess.jsp">
Email:<input type="text" name="email"/><br/><br/>
Password:<input type="password" name="pass"/><br/><br/>
<input type="submit" value="login"/>
</form>
loginprocess.jsp
<%#page import="bean.LoginDao"%>
<jsp:useBean id="obj" class="bean.LoginBean"/>
<jsp:setProperty property="*" name="obj"/>
<%
boolean status=LoginDao.validate(obj);
if(status){
out.println("You r successfully logged in");
session.setAttribute("session","TRUE");
}
else
{
out.print("Sorry, email or password error");
%>
<jsp:include page="index.jsp"></jsp:include>
<%
}
%>
LoginDao.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class LoginDao {
//public static void main(String args[]){
public static boolean validate( LoginBean bean ){
Connection c = null;
Statement stmt = null;
boolean status=false;
try{
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test","postgres", "pgadmin");
// c.setAutoCommit(false);
//PreparedStatement ps=c.prepareStatement("select * from user432 where email=? and pass=?;");
//ps.setString(1,bean.getEmail());
//ps.setString(2, bean.getPass());
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM public.\"USER432\" where email= 'a' and pass='a' ;" );
//ResultSet rs = stmt.executeQuery( "SELECT * FROM public.company;" );
status=rs.next();
rs.close();
stmt.close();
c.close();
}catch(Exception e){}
//System.out.println(status);
return true;
}
}
LoginBean.java
package bean;
public class LoginBean {
private String email,pass;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
Try to follow these steps:
Try to verify if the connection to database it's, and you can retrieve data from DB.
Cologate the bean with jsp without using the input parameters ( LoginBean bean ).
If previous steps are ok.
Try to add parameters (email,pass) in your method validate not object LoginBean.
In your jsp pass parameters like below:
< jsp:useBean id="obj" class="LoginBean" scope="session" />
<body>
< jsp:getProperty name="obj" property="email" />
< jsp:getProperty name="obj" property="pass" />
</body>
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
The reason may be the the short of knowledge in java :( ,so I'm asking this question,
Here in this piece of code I'm getting dynamic value(from a jsp page) :
<form action="">
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/apps","root","root");
Statement stmt = con.createStatement();
String sql = "select * from info;";
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
System.out.println("hi Tirtha");
%>
<center>
<h3>Information of User's</h3>
<table cellpadding="4" cellspacing="2" border="1" bgcolor="">
<tr>
<th>User Name</th>
<th>Email Id</th>
</tr>
<tr>
<%while(rs.next()){%>
<td><input type="text" name="name" value="<%= rs.getString(1)%>" readonly="readonly">
<td><input type="text" name="email" value="<%= rs.getString(2)%>" readonly="readonly">
</tr>
<%}%>
</table>
</center>
</form>
Now I want to save this data in a csv file(having an export option in it).
Any inputs will be appreciated.
here is a class you can using to export to CSV:
import java.io.FileWriter;
import java.io.IOException;
import User;
public class GenerateCsv
{
private static void generateCsvFile(ArrayList<User> users)
{
String output = "Email, Name\n";
for (User user in users) {
output += user.getEmail() + ", " + user.getName() + "\n";
}
return output;
}
}
Working the MVC way
Here is how your code should be written:
Let's say you have a class called. User.java inside of which there is a static function called get all users
public class User {
String name;
String email;
public static ArrayList<User> getAllUsers() {
// returns all users
...
}
}
Then let's say you have a servlet called UsersServlet which get these users:
import javax.servlet.*;
import javax.servlet.http.*;
public class UsersServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/csv");
PrintWriter w = res.getWriter();
ArrayList<User> users = Users.getAllUsers();
w.prinln(GenerateCsv.generateCsvFile(users));
w.flush();
w.close();
}
public void doPost (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
...
}
}
in your jsp, for example, you will have a simple anchor tag which calls the servlet (the servlets calls User.java, get data, forms them into a CSV and then outputs it to the browser...). Something like this would work:
<a href='/getCSV' > Export CSV </a>
but please note that you have to link the servlet to the url using web.xml:
<web-app>
<servlet>
<servlet-name>UsersServlet</servlet-name>
<servlet-class>__package__.UsersServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UsersServlet</servlet-name>
<url-pattern>getCSV</url-pattern>
</servlet-mapping>
</web-app>
EDIT: Writing to disk instead of sending to browser
import java.io.FileWriter;
import java.io.IOException;
import User;
public class GenerateCsv
{
private static void generateCsvFile(String fileName, ArrayList<User> users)
{
try
{
FileWriter writer = new FileWriter(fileName);
writer.append("Email");
writer.append(',');
writer.append("Name");
writer.append('\n');
for (User user in users) {
writer.append(user.getEmail());
writer.append(',');
writer.append(user.getName());
writer.append('\n');
}
writer.flush();
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
It is generally bad practice to have code embedded in the JSP, and you would be better off using a servlet, java classes, or a web framework like Spring, JSF, Struts, etc...
However, using your example above. The easiest way would be to create another JSP page like below:
<%#page contentType="text/text" %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/apps","root","root");
Statement stmt = con.createStatement();
String sql = "select * from info;";
ResultSet rs = stmt.executeQuery(sql);
%>
<%
while(rs.next()){
out.println("\"" + rs.getString(1) + "\", \"" + rs.getString(2) + "\"\n");
}%>
<% //cleanup and close db access %>
This sets the content type to be a text file, so the browser can display it properly. Then it iterates through your recordset and outputs a line with the two fields surrounded by quotes and ends each line with a \n newline character. Then, on your original page, you would just have a link to this new JSP page to download the CSV.
Alternately, you could use an existing library like OpenCSV. This would allow for more complicated needs and may also save headaches by handling escaping or special scenarios automatically.