I have an admin table that I trying to retrieve information from MySQL DB for the admins to edit. When I run the application the table shows up but no information is populating the table. Below is my admin.jsp page.
<%# page language="java" import="java.util.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<link rel="stylesheet" href="../styles/style1.css">
<meta http-equiv="Content-Type" content="text/css; charset=ISO-8859-1">
<title>admin</title>
<script language="javascript">
function editRecord(id){
window.location.href="editServlet/"+id;
}
function deleteRecord(id){
window.location.href="deleteUser/"+id;
}
</script>
</head>
<body>
<div class="content">
<br>
<table align="center">
</table>
<br>
<table width="600px" align="center" style="background-color:#EDF6EA;border:1px solid #000000;">
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr><td colspan=9 align="center" height="10px"></td></tr>
<tr style="background-color:#7BA88B;font-weight:bold;">
<td>CourseID</td><td>Course Rate</td><td>Professor</td>
<td>Professor Rate</td><td>Review</td><td>Edit</td><td>Delete</td>
</tr>
<%
String bgcolor="";
int count=0;
List viewList = new ArrayList();
Iterator viewItr;
if(request.getAttribute("courseList")!=null && request.getAttribute("courseList")!="")
{
List courseList = (ArrayList)request.getAttribute("courseList");
Iterator itr = courseList.iterator();
while(itr.hasNext())
{
if(count%2==0)
{
bgcolor = "#C8E2D1";
}
else
{
bgcolor = "#EAF8EF";
}
viewList = (ArrayList)itr.next();
int id = Integer.parseInt(viewList.get(0).toString());
viewItr = viewList.iterator();
%>
<tr style="background-color:<%=bgcolor%>;">
<%
while(viewItr.hasNext())
{
%>
<td><%=viewItr.next()%></td>
<%
}
count++;
%>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=id%>);" ></td>
<td><input type="button" name="delete" style="background-color:#ff0000;font-weight:bold;;color:#ffffff;" value="Delete" onclick="deleteRecord(<%=id%>);"></td>
</tr>
<%
}
}
if(count==0)
{
%>
<tr><td colspan="9" align="center"> </td></tr>
<tr><td colspan="9" align="center">No Record Avaliable</td></tr>
<%
}
%>
<tr><td colspan=9 align="center" height="2px"></td></tr>
</table>
</div>
</body>
</html>
Here is my one of my servlets:
package com.admin;
import java.sql.*;
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CourseServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String str[] = request.getRequestURI().toString().split("/");
int id = Integer.parseInt(str[3]);
Connection conn = null;
String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/mydatabase";
String DB_USERNAME = "";
String DB_PASSWORD = "";
// out.println(request.getRequestURI());
Statement st;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
System.out.println("Connected to the database");
ArrayList<Comparable> courseList=null;
String query = "select * from coursereview where id="+id;
System.out.println("query " + query);
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
courseList =new ArrayList<Comparable>();
courseList.add(rs.getInt(1));
courseList.add(rs.getString(2));
courseList.add(rs.getString(4));
courseList.add(rs.getString(5));
courseList.add(rs.getString(6));
courseList.add(rs.getString(7));
}
request.setAttribute("courseList",courseList);
String nextJSP = "/editUser.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here is my Servlet record:
package com.admin;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletRecord extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -7311509570234925786L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("MySQL Connect Example.");
Connection conn = null;
String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/mydatabase";
String DB_USERNAME = "";
String DB_PASSWORD = "";
Statement st;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
System.out.println("Connected to the database");
ArrayList<Comparable> al=null;
ArrayList<ArrayList<Comparable>> courseList =new ArrayList<ArrayList<Comparable>>();
String query = "select * from coursereview order by id";
System.out.println("query " + query);
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
al = new ArrayList<Comparable>();
al.add(rs.getInt(1));
al.add(rs.getString(2));
al.add(rs.getString(4));
al.add(rs.getString(5));
al.add(rs.getString(6));
al.add(rs.getString(7));
al.add(rs.getString(8));
System.out.println("al :: "+al);
courseList.add(al);
}
request.setAttribute("courseList",courseList);
String nextJSP = "/admin.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any advice would be greatly appreciated.
Related
I am try to search my database using jstl tags but it is not working.
So far what I manage is to make it display a null message.
I am very new to this side of java, so please if you have any suggestion try to explain in details.
Thanks
Image Description
My codes are as follows:
user-list.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# page isELIgnored="false"%>
<html>
<head>
<title>User Management Application</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbname2?allowPublicKeyRetrieval=true&useSSL=false"
user="root" password="root"/>
<body>
<header>
<nav class="navbar navbar-expand-md navbar-dark"
style="background-color: tomato">
<div>
<a href="" class="navbar-brand"> User
Management App </a>
</div>
<ul class="navbar-nav">
<li><a href="<%=request.getContextPath()%>/list"
class="nav-link">Users</a></li>
</ul>
</nav>
</header>
<br>
<div class="row">
<!-- <div class="alert alert-success" *ngIf='message'>{{message}}</div> -->
<div class="container">
<h3 class="text-center">List of Users</h3>
<hr>
<div class="container text-left">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success">Add
New User</a>
</div>
<form name="userForm" action="user-list.jsp" method="post">
<div class="container text-center">
<input type="text" class="form-group" name="search" value="<%=request.getParameter("id")%>" placeholder="Name" style="width: 400px;">
<INPUT TYPE ="submit">
</div>
</form>
<br>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>Time</th>
<th>Email</th>
<th>Country</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<sql:query var="user" dataSource="${snapshot}">
select *from users where
id like '%<%=request.getParameter("id")%>%'
</sql:query>
<c:forEach var="user" items="${listUser}">
<tr>
<td><c:out value="${user.id}" /></td>
<td><c:out value="${user.name}" /></td>
<td><c:out value="${user.date}" /></td>
<td><c:out value="${user.time}" /></td>
<td><c:out value="${user.email}" /></td>
<td><c:out value="${user.country}" /></td>
<td>Edit
Delete</td>
</tr>
</c:forEach>
<!-- } -->
</tbody>
</table>
</div>
</div>
UserDAO class
package com.project.usermanagement.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import com.project.usermanagement.model.User;
public class UserDAO {
public static Date getSQLDate(LocalDate date) {
return java.sql.Date.valueOf(date);
}
public static LocalDate getUtilDate(Date sqlDate) {
return sqlDate.toLocalDate();
}
public static Time getSQLTime(LocalTime time) {
return java.sql.Time.valueOf(time);
}
public static LocalTime getUtilTime(Time sqlTime) {
return sqlTime.toLocalTime();
}
private String jdbcURL = "jdbc:mysql://localhost:3306/dbname2?allowPublicKeyRetrieval=true&useSSL=false";
private String jdbcUsername = "root";
private String jdbcPassword = "root";
private static final String INSERT_USERS_SQL = "INSERT INTO users" + " (name, date ,time ,email , country) VALUES " +
" (?, ?, ?, ?, ?);";
private static final String SELECT_USER_BY_ID = "select id,name, date, time, email,country from users where id =?";
private static final String SELECT_ALL_USERS = "select * from users";
private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
private static final String UPDATE_USERS_SQL = "update users set name = ?, date=?, time=?, email= ?, country =? where id = ?;";
public UserDAO() {}
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public void insertUser(User user) throws SQLException {
System.out.println(INSERT_USERS_SQL);
// try-with-resource statement will auto close the connection.
try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setString(1, user.getName());
preparedStatement.setDate(2, getSQLDate(user.getDate()));
preparedStatement.setTime(3, getSQLTime(user.getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.setString(5, user.getCountry());
System.out.println(preparedStatement);
preparedStatement.executeUpdate();
} catch (SQLException e) {
printSQLException(e);
}
}
public User selectUser(int id) {
User user = null;
// Step 1: Establishing a Connection
try (Connection connection = getConnection();
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID);) {
preparedStatement.setInt(1, id);
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();
// Step 4: Process the ResultSet object.
while (rs.next()) {
String name = rs.getString("name");
LocalDate date = rs.getDate("date").toLocalDate();
LocalTime time = rs.getTime("time").toLocalTime();
String email = rs.getString("email");
String country = rs.getString("country");
user = new User(id, name, date, time , email, country);
}
} catch (SQLException e) {
printSQLException(e);
}
return user;
}
public List < User > selectAllUsers() {
// using try-with-resources to avoid closing resources (boiler plate code)
List < User > users = new ArrayList < > ();
// Step 1: Establishing a Connection
try (Connection connection = getConnection();
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS);) {
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();
// Step 4: Process the ResultSet object.
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
LocalDate date = rs.getDate("date").toLocalDate();
LocalTime time = rs.getTime("time").toLocalTime();
String email = rs.getString("email");
String country = rs.getString("country");
users.add(new User(id, name, date, time, email, country));
}
} catch (SQLException e) {
printSQLException(e);
}
return users;
}
public boolean deleteUser(int id) throws SQLException {
boolean rowDeleted;
try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(DELETE_USERS_SQL);) {
statement.setInt(1, id);
rowDeleted = statement.executeUpdate() > 0;
}
return rowDeleted;
}
public boolean updateUser(User user) throws SQLException {
boolean rowUpdated;
try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(UPDATE_USERS_SQL);) {
statement.setString(1, user.getName());
statement.setDate(2, getSQLDate(user.getDate()));
statement.setTime(3, getSQLTime(user.getTime()));
statement.setString(4, user.getEmail());
statement.setString(5, user.getCountry());
statement.setInt(6, user.getId());
rowUpdated = statement.executeUpdate() > 0;
}
return rowUpdated;
}
private void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
UserServlet class
package com.project.usermanagement.web;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import javax.servlet.RequestDispatcher;
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 com.project.usermanagement.dao.UserDAO;
import com.project.usermanagement.model.User;
#WebServlet("/")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDAO userDAO;
public void init() {
userDAO = new UserDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List < User > listUser = userDAO.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
dispatcher.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
dispatcher.forward(request, response);
}
private void showEditForm(HttpServletRequest request, HttpServletResponse response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDAO.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);
}
private void insertUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User newUser = new User(name, LocalDate.now(), LocalTime.now(), email, country);
userDAO.insertUser(newUser);
response.sendRedirect("list");
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
LocalDate date = LocalDate.parse(request.getParameter("date"));
LocalTime time = LocalTime.parse(request.getParameter("time"));
String email = request.getParameter("email");
String country = request.getParameter("country");
User book = new User(id, name, date, time, email, country);
userDAO.updateUser(book);
response.sendRedirect("list");
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDAO.deleteUser(id);
response.sendRedirect("list");
}
}
You can send value to be search using form .Then , get that value using ${param.yourinputname} and pass same to your query .Currently , you have incorrect input name i.e : name="search" but you are getting same using id which will return null as you can see in your added output as well .So, your form like below :
<form name="userForm" action="user-list.jsp" method="post">
<!--change value-->
<input type="text" class="form-group" name="search" value="${param.search}" placeholder="Name" style="width: 400px;">
<input type ="submit">
</form>
Now , when form will get submitted get that the value which is typed by user and pass same to your query . i.e :
<sql:query var="user" dataSource="${snapshot}">
select *from users where id LIKE '%' ? '%'
<sql:param value="${param.search}" />
</sql:query>
And get result from query using below code :
<c:forEach var="listUser" items="${user.rows}">
<tr>
<td><c:out value="${listUser.id}" /></td>
<td><c:out value="${listUser.name}" /></td>
<!--same for other fields as well-->
</tr>
</c:forEach>
I have written a simple JSP Code to upload a PDF file into Mysql BLOB Database
My HTML code is
<form method="post" action="uploadfile.jsp" enctype="multipart/form-data">
<center>
<table border="1" width="25%" cellpadding="5">
<thead>
<th colspan="3">Upload File</th>
</thead>
<tbody>
<tr>
<td>Title : </td>
<td><input type="text" name="title" size="30"></td>
</tr>
<tr>
<td>Choose File : </td>
<td><input type="file" name="file_uploaded" /></td>
</tr>
<tr>
<td colspan="3"><center><input type="submit" value="Upload"></center></td>
</tr>
</tbody>
</table>
</center>
</form>
My JSP Code is
<%#page import="java.io.*" %>
<%#page import="java.sql.*" %>
<%
response.setContentType("text/html;charset=UTF-8");
InputStream inputStream = null;
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
String title=(request.getParameter("title"));
Part filePart = request.getPart("file_uploaded");
if (filePart != null)
{
out.println(filePart.getName());
out.println(filePart.getSize());
out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
String idTemp="1";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/fileupload","root","password");
String sql = "INSERT INTO files (id, title, file) values (?, ?, ?)";
st = conn.prepareStatement(sql);
st.setString(1, idTemp);
st.setString(2, title);
if (inputStream != null)
{
st.setBinaryStream(3, inputStream, (int) filePart.getSize());
}
int row = st.executeUpdate();
if (row > 0)
{
out.println("File uploaded!!!");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
}catch(Exception e){out.print(e);}
%>
After executing this code. I am getting the error "java.sql.SQLException: No value specified for parameter 3"
What is the Problem with this code. My database table is empty , i cant able to upload any pdf data
My Database SQL is
create table files(id int(4),title varchar(20),file mediumblob,primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
You are getting error in this section.
String sql = "INSERT INTO files (id, title, file) values (?, ?, ?)";
st = conn.prepareStatement(sql);
st.setString(1, idTemp);
st.setString(2, title);
Here you need to add another parameter. You added only two parameter but in your query you declare three parameter by values (?, ?, ?)
I just created a Servlet code.Now its working well
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
#WebServlet("/uploadServlet")
#MultipartConfig(maxFileSize = 16177215)
public class UploadFileController extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Connection conn=null;
PreparedStatement st=null;
ResultSet rs=null;
String idTemp=request.getParameter("id");
String title=(request.getParameter("title"));
String site=request.getParameter("site");
Part filePart = request.getPart("file_uploaded");
HttpSession hs=request.getSession(true);
hs.setAttribute("site", site);
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","password");
String sql = "INSERT INTO files (id, title,file) values (?, ?, ?)";
st = conn.prepareStatement(sql);
st.setString(1, idTemp);
st.setString(2, title);
//st.setString(3, site);
if (inputStream != null)
{
st.setBinaryStream(3, inputStream, (int) filePart.getSize());
}
int row = st.executeUpdate();
if (row > 0)
{
String fileuploaded="fileuploaded";
out.println("<script> alert("+fileuploaded+")</script>");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
else
{
out.println("Couldn't upload your file!!!");
conn.close();
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.include(request, response);
}
}catch(Exception e){out.println(e);}
}
}
I had a problem in my servlet regarding deleting record from my database.
Please look over my servlet code and please do correct me. Thank you in advance
DeleteRow servlet is working perfectly right when a single ID is given manually.
Scenario is:
ManageSinger.java servlet displays the records in database along with a "Delete" hyperLink in every row. But problem is whenever i try to press delete button.. it receives a null value for ID in deleterow.java servlet ..
Please guide me from here how can only that corresponding ID can be pass to another servlet.
ManageSinger.java
package com.ea.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ManageSinger extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from singerdetails");
out.println("<form method = \"post\">");
out.println("<table border=1 width=50% height=50%>");
out.println("<tr><th align=\"center\">Singer Name</th><th align=\"center\">StageName</th><th align=\"center\">Language</th><th></th><tr>");
while (rs.next()) {
String singername = rs.getString("singername");
String stagename = rs.getString("stagename");
String language = rs.getString("language");
String id = rs.getString("userID");
HttpSession session = req.getSession(true);
session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
}
out.println("</table>");
out.println("</form");
out.println("</body></html>");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}
DeleteRow.java
package com.ea.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.jws.Oneway;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DeleteRow extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement st;
ResultSet rs;
try
{
HttpSession session = req.getSession(true);
Class.forName("com.mysql.jdbc.Driver");
String id = (String) session.getAttribute("id");
System.out.println(id);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
st= con.prepareStatement("delete from singerdetails where userID = ?");
st.setString(1, id);
st.executeUpdate();
int i = st.executeUpdate();
if(i!=0)
pw.println("Deleting row...");
else if (i==0)
{
pw.println("<br>Row has been deleted successfully.");
}
}
catch(SQLException sx)
{
pw.println(sx);
}
catch(ClassNotFoundException cx)
{
pw.println(cx);
}
}
}
In DeleteRow.java say you should do String id = (String) session.getAttribute("userID"); instead of (String) session.getAttribute("id") .In ManageSinger.java you are setting the attribute as follows session.setAttribute("userID",id);
As per your current ManageSinger.java only the last userID gets set in session, which is why the last userID gets deleted. In ManageSinger.java instead of setting the userID as session attribute you can set it as url parameter for each record.
Following lists the changes:
//HttpSession session = req.getSession(true);
//session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
In DeleteRow.java instead of getting the userID from session, you can get it from the url as following:
//HttpSession session = req.getSession(true);
//String id = (String) session.getAttribute("id");
String id = req.getParameter("userID").toString();
I'm trying to insert an image in a MySQL database using Servlet and JSP in Tomcat 7. When I click on the save button, it displays null. I am not getting any errors.
Also I set commons-fileupload.jar file and commons-io.jar file. If you have some demonstration code, please give me.
<%# 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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table
</form>
</center>
</body>
</html>
FileUploadDBServlet.java:
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/FileUploadDBServlet")
#MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/AppDB";
private String dbUser = "root";
private String dbPass = "root";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(dbURL,dbUser,dbPass);
String sql =("INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)");
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (Exception ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/FileUploadDBServlet</url-pattern>
</servlet-mapping>
</web-app>
The following code explains how to store/retrieve an image to/from db.
First create a table in your db using following code
CREATE TABLE contacts (
contact_id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
photo` mediumblob);
Create a jsp file for input parameters.
Upload.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database</title>
</head>
<body>
<h1>File Upload to Database</h1>
<form name="fileform" method="post" action="uploadServlet" enctype="multipart/form-data">
<label for="firstName">First Name:</label>
<input type="text" name="firstName" size="50" placeholder="Enter Your FirstName" required/><br><br>
<label for="lastName">Last Name: </label>
<input type="text" name="lastName" size="50" placeholder="Enter Your LastName" required/><br><br>
<label for="photo"> Portrait Photo: </label>
<input type="file" name="photo" size="50" placeholder="Upload Your Image" required/><br><br>
<input type="submit" value="Save">
</form>
</body>
</html>
Next create controller for uploading image. In this case, I'm using a servlet.
FileUploadDbServlet.java:
package com.fileupload.attach;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#MultipartConfig(maxFileSize = 16177215)
// upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
private static final int BUFFER_SIZE = 4096;
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/mysql";
private String dbUser = "root";
private String dbPass = "arun";
//naive way to obtain a connection to database
//this MUST be improved, shown for
private Connection getConnection() {
Connection conn = null;
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
} catch (Exception e) {
//wrapping any exception and rethrowing it
//inside a RuntimeException
//so the method is silent to exceptions
throw new RuntimeException("Failed to obtain database connection.", e);
}
return conn;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
//obtains input stream of the upload file
//the InputStream will point to a stream that contains
//the contents of the file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
conn = getConnection();
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
//Using a PreparedStatement to save the file
PreparedStatement pstmtSave = conn.prepareStatement(sql);
pstmtSave.setString(1, firstName);
pstmtSave.setString(2, lastName);
if (inputStream != null) {
//files are treated as BLOB objects in database
//here we're letting the JDBC driver
//create a blob object based on the
//input stream that contains the data of the file
pstmtSave.setBlob(3, inputStream);
}
//sends the statement to the database server
int row = pstmtSave.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
String filepath = "D:/Dev/JavaWorkSpaceNew/FileUploadDatabase/WebContent/FromDb.jpg";
//Obtaining the file from database
//Using a second statement
String sql1 = "SELECT photo FROM contacts WHERE first_name=? AND last_name=?";
PreparedStatement pstmtSelect = conn.prepareStatement(sql1);
pstmtSelect.setString(1, firstName);
pstmtSelect.setString(2, lastName);
ResultSet result = pstmtSelect.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("photo");
InputStream inputStream1 = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filepath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream1.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream1.close();
outputStream.close();
System.out.println("File saved");
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
//silent
}
}
// sets the message in request scope
request.setAttribute("message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp")
.include(request, response);
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>servletFileUpload</display-name>
<welcome-file-list>
<welcome-file>Upload.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>FileUploadDBServlet</display-name>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>com.fileupload.attach.FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
Message.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<h3>Result of the operation: ${message}</h3>
</body>
</html>
Jsp Page
Save this page with any name
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action="abc" method="post" enctype="multipart/form-data"> <br><br>
<table>
<tr>
<td>UserName: </td>
<td width='10px'></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Upload: </td>
<td width='10px'></td>
<td><input type="file" name="file" value="Upload"/></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Servlet page and save this page as abc.java
source code
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet(urlPatterns = {"/abc"})
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 100)
public class abc extends HttpServlet {
// this if directory name where the file will be uploaded and saved
private static final String SAVE_DIR = "images";
// this is the method which is created by system it self
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
// this tyr is created by me for the connection of database
try {
// this is the path provide by me to save the image
String savePath = "C:" + File.separator + SAVE_DIR;
/*in place of C: you can place a path wher you need to save the image*/
// this comment will picup the image file and have convert it into file type
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
// this two comment will take the name and image form web page
String name = request.getParameter("name");
Part part = request.getPart("file");
// this comment will extract the file name of image
String fileName = extractFileName(part);
// this will print the image name and user provide name
out.println(fileName);
out.println("\n" + name);
/*if you may have more than one files with same name then you can calculate
some random characters and append that characters in fileName so that it will
make your each image name identical.*/
part.write(savePath + File.separator + fileName);
/*
You need this loop if you submitted more than one file
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}*/
// connectio to database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("url", "host -name", "password");
// query to insert name and image name
String query = "INSERT INTO image_link (name,photourl) values (?, ?)";
PreparedStatement pst;
pst = con.prepareStatement(query);
pst.setString(1, name);
String filePath = savePath + File.separator + fileName;
pst.setString(2, filePath);
pst.executeUpdate();
} catch (Exception ex) {
out.println("error" + ex);
}
}
}
// the extractFileName() is method used to extract the file name
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This question already has an answer here:
Authentication filter and servlet for login
(1 answer)
Closed 7 years ago.
I have created a simple login page in which user will give an username and password. After clicking on submit button it will show welcome user. But it is not giving any result
This is my index page
This is my index login page :
<%# 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">
<link rel="stylesheet" type="text/css" href="style.css"/>
<title>Login</title>
</head>
<body>
<%
String error_msg = "";
Object error = request.getAttribute("error");
if (error != null) error_msg = error.toString();
%>
<div id="Container">
<div id="Header">
<h1>Online File Management System</h1>
</div>
Home
<div id="Content">
<div id="Login">
<form action="login">
<table align = "center" bgcolor=#66CCFF>
<tr><td align = "left">Username: </td>
<td rowspan="7" valign="middle">
<font color="red"> <%= error_msg %> </font>
<p>You can also Login using Google</p>
<p class="Google"><input name="Submit" type="Submit" value="Login with Google Account"></p>
</td>
</tr>
<tr>
<td><input name="username" type="text" size="30"></td>
<td></td>
</tr>
<tr><td align = "left">Password:</td></tr>
<tr><td><input name="password" type="password" size="30"></td></tr>
<tr><td align = "left">Forgot your password?</td></tr>
<tr><td align = "left">Remember me <input type="checkbox" name="checkbox" value="checkbox"></td></tr>
<tr><td align = "left"><input type="Submit" value="LOGIN"></td></tr>
</table>
</form>
<hr>
</div>
</div>
<div id="Footer">
Copyright © 2014 Office of the Vice Chancellor.
</div>
</div>
</body>
</html>
This is my Database conectivity page :
package org.form.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.catalina.connector.Request;
public class database {
#SuppressWarnings("null")
public String validateUserLogin (String username, String password) throws SQLException{
Connection connection = null;
ResultSet resultset = null;
Statement statement = null;
String fullname = "";
String DRIVER = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/onfms";
String USER = "root";
String PASS = "";
String QUERY = "SELECT * FROM tblUser WHERE fldUser_Name = '"+
username+"' AND fldPassword = '"+password+"' ";
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL,USER,PASS);
resultset = statement.executeQuery(QUERY);
} catch (Exception e){
e.printStackTrace();
} finally {
if (resultset != null)
resultset.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
}
}
This is my login servlet page:
package org.form.login;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
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 org.form.login.database;
/**
* Servlet implementation class login
*/
#WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "/main.jsp";
String user = request.getParameter("username");
String pass = request.getParameter("password");
if (user == null || user.length() == 0 ||pass == null || pass.length() == 0) {
url = "/index.jsp";
request.setAttribute("error", "Username & Password must not be empty.");
}else{
try {
String fullname = new database().validateUserLogin(user, pass);
request.setAttribute("fullname", fullname);
if (fullname != null || fullname.length() != 0){
request.setAttribute("sucess", "Sucessfull Connection");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is my final Page where I display my result
<%# 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>Desk Board</title>
</head>
<body>
Hello
<%
String sucess_message ="";
Object sucess = request.getAttribute("sucess");
if (sucess != null ) sucess_message = sucess.toString();
%>
<%= sucess_message %>
</body>
</html>
use this code it is working
// index.jsp or 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>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
You Can simply Use One Jsp Page To accomplish the task.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.