To insert unchecked value of a check box into database [duplicate] - mysql

This question already has answers here:
Force a checkbox to always submit, even when unchecked
(7 answers)
Closed 6 years ago.
I need help in inserting the unchecked value of a check box into mysql database using servlet.
Work Flow:
1.From a list of check box values the user checks some of the values and the remaining values are set unchecked
2.After selecting the values the user hits the save button
3.On clicking the save button,the checked values should be stored in one table and the unchecked values should be stored in another table
Issue
I have used the general method to insert the values into database,for me the checked values are getting inserted into one table(pdt_list).In the same way I need to insert the unchecked values into another table say(no_pdt_list). Both the insertion should happen once the save button is clicked.
This is my code
products.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>
<form method="post" action="Save_Products">
<b>
Brand Name:<font color="green">
<% String brand_name=(String)session.getAttribute("brand_name");
out.print(brand_name);%>
<c:set var="brand_name" value="brand_name" scope="session" />
</font></b>
<table>
<tr>
<th> Products</th>
<th> Description </th>
</tr>
<tr>
<td> <b><%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} %> </b></td>
<td><%for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>");
}
}
%> </td>
</tr>
<br/>
<br/>
<tr><td align="center"> <input type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</body>
</html>
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 javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class Save_Products 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;
try{
HttpSession session = request.getSession();
String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql);
int num_values = Math.min(prod_list.size(), desc_list.size());
int count_updated = 0;
for(int i = 0; i < num_values; i++){
prep.setString(1, brand_name);
prep.setString(2, prod_list[i]);
prep.setString(3,desc_list[i]);
count_updated += prep.executeUpdate();
}
if(count_updated>0)
{
out.print("Products Saved Successfully...");
RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");
rd.forward(request,response);
}
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());
}
}
}
}

Do you use Jquery as well?, you could try doing:
$("input:checkbox:not(:checked)") and saving it in a hidden field before submitting the form when you hit "Save"...
Be sure to reference the name of your checkbox if you have more than one set os checkboxes in your page.
i.e:
$("input#prod:not(:checked)").each(function(i){
console.log($(this).val()); //or save it to the hidden value with a comma or some sort of separator you can then work with at the servlet
});

Related

How to search database using jstl tags and display in jsp file

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>

java.sql.SQLException: No value specified for parameter 3

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);}
}
}

How to call a DAO method from a Json Servlet

I have a dependency dropdown list in my JSP. I have a json servlet where I populate the second dropdown. Based on the selection made for the first dropdown will determine the second dropdown. I have hardcoded values within the jsonServlet class but I want to be able to call a query from my DAO method. How would I go about this?
JsonServlet:
package master.service;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import master.dao.MasterDataDao;
import master.dto.SiteDto;
import com.google.gson.Gson;
/**
* Servlet implementation class JsonServlet
* #param <E>
*/
public class JsonServlet<E> extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
MasterDataDao masterDataDao = new MasterDataDao();
String divisionIdName = request.getParameter("divisionIdName");
List<String> list = new ArrayList<String>();
List<SiteDto> site = new ArrayList<SiteDto>();
String json = null;
if (divisionIdName.equals("33") || divisionIdName.equals("36")) {
try {
site.equals(masterDataDao.getAllJJSites());
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
list.addAll(-1, element);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
}
} else if (divisionIdName.equals("Select Division")) {
list.add("Select Site");
} else {
try {
site.equals(masterDataDao.getAllSites());
for (Iterator<SiteDto> iter = site.iterator(); iter.hasNext(); ){
SiteDto element = iter.next();
list.addAll(-1, element);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
json = new Gson().toJson(list);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
Based off the divisionID selection in my JsonServlet, if the divisionID is either 33 or 36 i'd like to call this method in my MasterDataDao class:
public List<SiteDto> getAllJJSites() throws IOException, ClassNotFoundException, SQLException {
List<SiteDto> siteDtoList = new ArrayList<SiteDto>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "Select Distinct Name, Id From Addtl_Type Where Addtl_Type.is_active = '1' And Data_Field_Id = 3050 Order By Name";
con = getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
// System.out.println("&*******" + rs.getFetchSize());
while (rs.next()) {
SiteDto siteDto = new SiteDto();
siteDto.setId(rs.getString("Id"));
siteDto.setName(rs.getString("Name"));
siteDtoList.add(siteDto);
}
} finally {
cleanUp(con, ps, rs);
}
return siteDtoList;
}
Otherwise if it is another selection value(besides Select Division), I'd like to call this method with the MasterDataDao class:
public List<SiteDto> getAllSites() throws IOException, ClassNotFoundException, SQLException {
List<SiteDto> siteDtoList = new ArrayList<SiteDto>();
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
String query = "Select Distinct Name, Id From Addtl_Type Where Addtl_Type.is_active = '1' And Data_Field_Id = 105 Order By Name";
con = getConnection();
ps = con.prepareStatement(query);
rs = ps.executeQuery();
// System.out.println("&*******" + rs.getFetchSize());
while (rs.next()) {
SiteDto siteDto = new SiteDto();
siteDto.setId(rs.getString("Id"));
siteDto.setName(rs.getString("Name"));
siteDtoList.add(siteDto);
}
} finally {
cleanUp(con, ps, rs);
}
return siteDtoList;
}
Is this possible to do within the JsonServlet? If so how? Thanks in advance.
Please let me know if more information is needed.
Also I have included my JSP here. Initially I had made a call to the DAO from here. I referenced a bean.
JSP:
<script>
$(document).ready(function() {
$('#divisionId').change(function(event) {
var divisionId = $("select#divisionId").val();
$.get('JsonServlet', {
divisionIdName : divisionId
}, function(response) {
var select = $('#siteId');
select.find('option').remove();
$.each(response, function(index, value) {
$('<option>').val(value).text(value).appendTo(select);
});
});
});
});
</script>
</head>
<body>
<form name="input" action="getMasterData" method="get">
<br /> <br />
<h1 align='center'>Master Data File</h1>
<br /> <br />
<table border="0" align='center'>
<tr>
<td>
<h2>Division</h2>
</td>
<td align='left'><jsp:useBean id="masterDaoUtil"
class="master.dao.util.MasterDataConstants" />
<select name="divisionId" id="divisionId">
<option>Select Division</option>
<option value="33">
<%=MasterDataConstants.DIVISION_TYPE_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="31">
<%=MasterDataConstants.DIVISION_TYPE_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="34">
<%=MasterDataConstants.DIVISION_TYPE_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="35">
<%=MasterDataConstants.DIVISION_TYPE_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="23">
<%=MasterDataConstants.DIVISION_TYPE_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="36">
\
<%=MasterDataConstants.DIVISION_TYPE_QUALITY_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="40">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_AUDIT_MANAGEMENT_GLOBAL_NAME%></option>
<option value="43">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_CHANGE_MANAGEMENT_GLOBAL_NAME%></option>
<option value="41">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_DEA_MANAGEMENT_GLOBAL_NAME%></option>
<option value="42">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_EHS_MANAGEMENT_GLOBAL_NAME%></option>
<option value="44">
<%=MasterDataConstants.DIVISION_TYPE_NORAMCO_EVENT_MANAGEMENT_GLOBAL_NAME%></option>
</select></td>
</tr>
<tr>
<td>
<h2>Site Name</h2>
</td>
<td align='left'>
<%-- <jsp:useBean id="masterDao"
class="master.dao.MasterDataDao" />
--%>
<select name="siteId"
id="siteId">
<option>Select Site</option>
<%-- <option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}
</option>
</c:forEach>
--%>
</select></td>
</tr>
</table>
<br /> <br />
<div style="text-align: center">
<input type="submit" value="Submit">
</div>
</form>
<%
if (request.getAttribute("message") != null) {
%>
<p>
<font size=4 color="red"> Master_Data(timestamp).xlsx and
Consistency_Check_Data(timestamp).xlsx are located under
d:/stage/MasterDataReports <%--Master_Data(timestamp).xlsx and Consistency_Check_Data(timestamp).xlsx are located under /jsc/ets/u02/tools7/apache-tomcat-7.0.55/webapps/MasterData/MasterDataReport--%>
</font>
</p>
<%
}
%>
Originally before I used JSON and AJAX I used this statement for the options which is now commented out.
<%-- <jsp:useBean id="masterDao"
class="master.dao.MasterDataDao" />
--%>
<select name="siteId"
id="siteId">
<option>Select Site</option>
<%-- <option value="0">ALL</option>
<c:forEach items="${masterDao.allSites}" var="siteDto">
<option value="${siteDto.id}">${siteDto.name}
Is there a way I can leverage this? Maybe can I make a function call to the JSP from my servlet? I know this is not good practice but I cannot think of another way. I need to get the siteDto.id value as well as the siteDto.name value.
Thanks in advance
Create an interface and implementation DAO like IMasterDataDAO and MasterDataDAOImpl.
In case if you get more if..else condition in future then use switch..case instead of if..else.
Create an object for DAO using the interface in servlet like below:
IMasterDataDAO masterDAO = new MasterDataDAOImpl()
then call either masterDAO.getAllJSites() or masterDAO.getAllSites() based on the condition.

How to insert image in MySQL database using Servlet and JSP in Tomcat 7

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>
}

Create a simple Login page using eclipse and mysql [duplicate]

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.