How to call a DAO method from a Json Servlet - json

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.

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>

JSP: How to increase a value of a database in JSP? Error when i click the button

------ 2 DAYS AGO --------
"I made a database only for the "likes" of a website. The database has a table (Likes) with several fields (Like1, Like2, etc ...)
In a JSP file I made the connection and show the value of a field (Like1).
But what I want to do is: by clicking on a certain text, the value increases by one, updating that value in the database from Like1 to Like1 + 1."
--- EDIT ---
When i click the button, show me this:
ERROR
When I refresh, the data does not change. So I think if I did not show the error, it would work.
What I want is, when you press the button, the DB data increment by 1.
Structure:
Structure
index.jsp:
<body>
<div class="col-lg-12">
<form method="post" action="likeCount">
<button type="submit" name="click"><b style="color:#ff5858;font-size: 24px;">❤</b></button>
<% try {
Connection conn = DBConnect.connect();
PreparedStatement pstmt = conn.prepareStatement("SELECT Like1 from Likes");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {%>
<input type="text" hidden name="counts" value="<%=rs.getInt("Like1")%>" />
</form>
<span style="font-weight: bold"><%=session.getAttribute("count")==null)?rs.getInt("Like1"):(session.getAttribute("count"))%></span><% }
} catch (SQLException ex) {
System.out.println("Error in select: " + ex.getMessage());
}%>
</div>
</body>
DBConnect.java:
package myPack;
import com.mysql.jdbc.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnect {
public static Connection connect() throws SQLException {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/Likes";
String username = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error : " + e.getMessage());
}
return conn;
}
}
likeCount.java:
package myPack;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class likeCount {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
/*check whether the button is clicked*/
if (request.getParameter("click") != null) {
try {
/*getting the number of likes*/
String x = request.getParameter("counts");
int c = Integer.parseInt(x);
int count = c;
count = count + 1; //increment the value
Connection conn = DBConnect.connect();
PreparedStatement ps = conn.prepareStatement("UPDATE Likes SET Like1 = ?");
ps.setInt(1, count);
int num = ps.executeUpdate();
if (num > 0) {
HttpSession session = request.getSession();
session.setAttribute("count", count);
response.setIntHeader("Refresh", 3);
response.sendRedirect("index.jsp");
}
} catch (SQLException e) {
System.out.println("Error in update :" + e.getMessage());
}
}
}
}
In this case you will need a servlet and a database connection classes.
First, this is the database connection class. DBConnect.java
public class DBConnect {
public static Connection connect() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/likes";
String username = "root";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error : "+e.getMessage());
}
return conn;
}
}
Next, this will be the index.jsp form
<body>
<div class="col-lg-2">
<form method="post" action="likeCount">
<button type="submit" name="click">TEXTO DONDE QUISIERA QUE INCREMENTE AL HACER CLICK.</button>
<% try {
Connection conn = DBConnect.connect();
PreparedStatement pstmt = conn.prepareStatement("SELECT Like1 from Likes");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {%>
<input type="text" hidden name="counts" value="<%=rs.getInt("Like1")%>" />
</form>
<span style="font-weight: bold"><%=(session.getAttribute("count")==null)?rs.getInt("Like1"):(session.getAttribute("count"))%></span>
<% }
} catch (SQLException ex) {
System.out.println("Error in select: " + ex.getMessage());
}%>
</div>
</body>
And finally, the servlet. likeCount.java
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/*check whether the button is clicked*/
if (request.getParameter("click") != null) {
try {
/*getting the number of likes*/
String x = request.getParameter("counts");
int c = Integer.parseInt(x);
int count = c;
count = count + 1; //increment the value
Connection conn = DBConnect.connect();
PreparedStatement ps = conn.prepareStatement("UPDATE Likes SET Like1 = ?");
ps.setInt(1, count);
int num = ps.executeUpdate();
if (num > 0) {
HttpSession session = request.getSession();
session.setAttribute("count", count);
response.setIntHeader("Refresh", 3);
response.sendRedirect("index.jsp");
}
} catch (SQLException e) {
System.out.println("Error in update :" + e.getMessage());
}
}
}
Hope it would work.

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

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

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

file getting corrupted after transfering using apache commons

i have done file uploading partially successful .the file with extension-.html,.jpeg,.pdf etc works fine.when it comes to .zip,.rpm,.tar.gz it doesn't works.the file is getting transferred to the desired path but the file is corrupted.
<tr>
<td>FileName</td>
<td><input type="text" name="filename" size="30"/></td>
</tr>
<tr>
<td>Select main category</td>
<td>
<select name="main">
<option >--Select--</option>
<option>aerospace</option>
<option>automotive</option>
<option>energy</option>
<option>icengines</option>
<option>wind</option>
<option>turbo</option>
<option>it</option>
<option>training</option>
</select>
</td>
</tr>
<tr>
<td>Select sub category</td>
<td>
<select name="sub">
<option >--Select--</option>
<option>internal</option>
<option>demo</option>
<option>best practice</option>
<option>marketing</option>
<option>papers & public</option>
<option>validation</option>
<option>training</option>
</select>
</td>
</tr>
<tr>
<td>Upload File</td>
<td><input type="file" name="file1"/></td>
</tr>
it will get the filename along with the dropdown values and type="file",the file is transferred to the desired path but the file is corrupted for above mentioned formats(i have checked with those formats alone).i need all the file to be stored without getting corrupted.
my servlet:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
private String filename="";
private String main1="";
private String location;
private String sub;
private File uploadFile;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = fileUpload.parseRequest(request);
Iterator ir = items.iterator();
while(ir.hasNext()){
FileItem item = (FileItem)ir.next();
if(item.isFormField())
{
String name = item.getFieldName();
if(name != null)
{
if(name.equals("userName"))
{
filename = item.getString();
}
else if(name.equals("main"))
{
main1 = item.getString();
}
else if(name.equals("sub"))
{
sub=item.getString();
}
}
}else{
location = File.separator+"home"+File.separator+"adapco"+File.separator+"Desktop"+ File.separator +"output"+ File.separator +main1+File.separator+sub+File.separator+filename;
uploadFile = new File(location);
long size = item.getSize();
if(size <= 1024*1024*1024)
{
item.write(uploadFile);
out.println("Your File is uploaded successfully ");
}else{
out.println("Your File is not uploaded.File size should be less than 1gb");
}
}
}
} catch (Exception e) {
}
}
}