put rows with same name together - java

I have table like this-
fnumber|fstatus|department|date&time
f1 out d1 a
f2 out d2 b
f1 in d3 c
f1 out d3 d
f2 in d1 e
f1 in d1 f
f2 out d1 g
f2 in d2 h
Is there a way such that same fnumber are automatically be together and arranged according to date and time(from old to new) like this-
fnumber|fstatus|department|date&time
f1 out d1 a
f1 in d3 c
f1 out d3 d
f1 in d1 f
f2 out d2 b
f2 in d1 e
f2 out d1 g
f2 in d2 h
right now i am using servlet and jsp for simply inserting the value but i want them to get arranged like above (Suppose I insert f1 then f2 then f3 now if f1 is inserted again i want it to be inserted between f1 and f2 not after f3.
Is ther some way i could do that.
fileStatus.jsp This is the file where user submits the value.
<%#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>File Status Page</title>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}
section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("admin")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<font color="black">back</font>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<h3>Change Status</h3>
<form action="statusServlet" method="post">
<table>
<tbody>
<tr>
<td>
File Number :<select name="files">
<%
try{
String sql="select * from files";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
"root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>
<option value="<%=rs.getString("fileno")%>"><%=rs.getString("fileno")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</select></td>
</tr>
<tr>
<td>
File Department :<select name="departments">
<%
try{
String sql="select * from department";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
"root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>
<option value="<%=rs.getString("departmentname")%>"><%=rs.getString("departmentname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</select></td>
</tr>
<tr>
<td>
File Status :<select name="input">
<option>IN</option>
<option>OUT</option>
</select></td>
</tr>
<tr>
<td>
<input type="submit" value="submit" name="submit" />
</td>
</tr>
</tbody>
</table>
</form>
</section>
<footer>
Copyright example. All right reserved.
</footer>
</body>
</html>
stausServlet.java In this i am using sql query to insert the data.
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class statusServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
HttpSession session = request.getSession(false);
System.out.println("admin="+session.getAttribute("admin"));
if(session!=null && session.getAttribute("admin") != null){
String user=(String)session.getAttribute("admin");
boolean status=false;
try{
String fno=request.getParameter("files");
String departments=request.getParameter("departments");
String input=request.getParameter("input");
Connection con=ConnectionProvider.getCon();
String sql="insert into status(fnumber,fstatus,department) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,fno);
pstmt.setString(2,input);
pstmt.setString(3,departments);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
if(status){
response.sendRedirect("fileStatus.jsp");
PrintWriter out= response.getWriter();
out.println("Values have been inserted,"+user);
//out.flush();
}
else
{
PrintWriter out= response.getWriter();
out.println("failed");
response.sendRedirect("create.jsp");
}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}

If you are using sql to get your data you should use the Order By clause.
If you are using a java List, you can sort the List by using a Comparator, see for example https://stackoverflow.com/a/18441978/3543153

Related

Error message "The origin server did not find a current representation for the target resource or is not willing to disclose that one exists"

I am currently working on my login and registration page using sublime text. When I try to register users for my registration page or try to login, the error message will pop up shown below.
This is the format for my code shown below:
login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="loginRegister" method="post">
<table
style="background-image: url('https://static.abbottnutrition.com/cms-prod/abbottfamily.com.sg/img/Article%201%20banner_tcm150-71042.jpg'); width: 500px; height: 200px; margin-left: 20px; margin-left: 20px;">
<tr>
<td><h3 style="color: red;">${message}</h3>
<h3 style="color: green;">${SuccessMessage}</h3></td>
</tr>
<tr>
<td><h3 style="color: Red;">Recipe Login Page</h3></td>
<td></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="login"></td>
<td>Registration</td>
</tr>
</table>
</form>
</body>
</html>
register.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="loginRegister" method="post">
<table
style="background-image: url('https://static.abbottnutrition.com/cms-prod/abbottfamily.com.sg/img/Article%201%20banner_tcm150-71042.jpg'); width: 500px; height: 200px; margin-left: 20px; margin-left: 20px;">
<tr>
<td><h3 style="color: Black;">Recipe Registration Page</h3></td>
<td></td>
</tr>
<tr>
<td><h3 style="color: red;">${message}</h3>
<h3 style="color: green;">${SuccessMessage}</h3></td>
</tr>
<tr>
<td>Email :</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="register"></td>
<td>Login</td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MyRecipeProject</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
</web-app>
CustomerDAO.java
public interface CustomerDAO {
public int insertCustomer(Customer c);
public Customer getCustomer(String email,String pwd);
}
Customer.java
public class Customer {
private String email;
private String pwd;
public String getemail() {
return email;
}
public void setemail(String email) {
this.email = email;
}
public String getpwd() {
return pwd;
}
public void setpwd(String pwd) {
this.pwd = pwd;
}
}
LoginRegister.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginRegister
*/
#WebServlet("/loginRegister")
public class LoginRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginRegister() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
CustomerDAOImpl cd = new CustomerDAOImpl();
String email = request.getParameter("email");
String pwd = request.getParameter("pwd");
String submitType = request.getParameter("submit");
Customer c = cd.getCustomer(email, pwd);
//if (submitType.equals("login") && c!=null && c.getName()!=null)
if (submitType.equals("login") && c!=null && c.getName()!=null) {
request.setAttribute("message", c.getemail());
request.getRequestDispatcher("welcome.jsp").forward(request, response);
} else if (submitType.equals("register")) {
c.setemail(request.getParameter("email"));
c.setpwd(pwd);
cd.insertCustomer(c);
int t = 0;
/*if(cd.insertCustomer(c) > t) {
request.setAttribute("Successmessage", "Registration Done, please login to continue!!!!");
}
else {
request.setAttribute("not successful", "try again");
}
*/
request.setAttribute("SuccessMessage", "Registration Done, please login to continue!!!!");
request.getRequestDispatcher("register.jsp").forward(request, response);
} else {
request.setAttribute("message", "Data Not Found, click on Register !!!");
request.getRequestDispatcher("login.jsp").forward(request, response);
System.out.println(c.getemail());
}
}
}
CustomerDAOImpl.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class CustomerDAOImpl implements CustomerDAO {
static Connection con;
static PreparedStatement ps;
public int insertCustomer(Customer c) { //put from frontend data to database
int status = 0;
try {
con = MyConnectionProvider.getConnection();
ps = con.prepareStatement("insert into accountInfo values(?,?)"); // putting data in sql
ps.setString(1, c.getemail()); // before putting into sql, must put user data from frontend to customer object in servlet
ps.setString(2, c.getpwd()); //and then call from here using customer object call and push to database
status = ps.executeUpdate(); //if want to put data, always update
con.close();
} catch (Exception e) {
System.out.println(e);
}
return status;
}
public Customer getCustomer(String email, String pwd) { //call data from database
Customer c = new Customer();
try {
con = MyConnectionProvider.getConnection();
ps = con.prepareStatement("select * from accountInfo where email=? and pwd=?"); //prepare statement to just call all data containing username and password
ps.setString(1, email); //input
ps.setString(2, pwd);
ResultSet rs = ps.executeQuery(); //call from database
while (rs.next()) {
c.setemail(rs.getString(1));
c.setpwd(rs.getString(2)); //get data from database then put into the customer object
}
} catch (Exception e) {
System.out.println(e);
}
return c;
}
}
welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body style="color: yellow;">
<h1>Hi ${message} !!! We welcome you !!!</h1>
</body>
</html>
MyProvider.java
public interface MyProvider {
String username="root"; //password of database
String pwd="xxxx";
String connUrl = "jdbc:mysql://localhost:3306/userinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; //postgresql==.mysql
}
MyConnectionProvider.java
import java.sql.*;
public class MyConnectionProvider implements MyProvider {
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
// private static final String URL = "jdbc:mysql://localhost:3306/appdb";
// local machine
private static final String URL = "jdbc:mysql://localhost:3306/userinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
static {
try {
Class.forName(DRIVER_NAME).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
// Establish connection
/**
* Establish connection
*
* #return Connection object
* #throws SQLException throws SQLException
*/
public static Connection getConnection() throws SQLException {
// return DriverManager.getConnection(URL, "root", "yJfcXQETOLH1");
// local machine
System.out.println(DriverManager.getDriver("jdbc:mysql://localhost:3306/userinfo?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC").toString());
return DriverManager.getConnection(URL, "root", "xxxx");
}
// Close connection
/**
* Close connection
*
* #param conn Connection object
* #param stmt Statement object
* #param rs ResultSet object
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
So basically, I create a folder called myWebProject, and I saved all my codings and pages under a sub-folder called DIPProject as shown below and I run using Tomcat[![][6]
I would appreciate if someone can help me on that. Thanks so much!

CRUD web application in Java with Servlet,JSP and MySQL without DAO

I am working on a simple home library web application using Java EE, Servlets, JSP, and MySQL. My Create, Read, and Delete are working fine but Update is not working. I am not using any form of design patterns, just servlets and POJO. All examples i try to learn from seem to have used MVC and DAO design patterns. Is there any way to achieve the CRUD application without using MVC and DAO patterns? What is the recommended and best practice for such a simple application?
here is code:
UpdateBook.jsp
<%# page language="java" contentType="text/html; charset=gbk"
pageEncoding="gbk"%>
<%# page import ="java.util.ArrayList"%>
<%#page import="book.Book"%>
<!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=gbk">
<link rel="stylesheet" type="text/css" href="../css/styles.css" />
<title>Updated Library Collection</title>
</head>
<body>
<div id="container">
<div id="header"><h1 align="center" style="color:blue">Edit Library Collection</h1></div>
<div id="wrapper">
<div id="content" align="center">
<%
request.setCharacterEncoding("gbk");
String ISBN=request.getParameter("Isbn");
String BookTitle=request.getParameter("Title");
String BookAuthor=request.getParameter("Author");
String Category=request.getParameter("Category");
String Description=request.getParameter("Description");
%>
<table width="100%" border="0" cellspacing="0" cellpadding="4" align="center" >
<tr>
<td width="100%" bgcolor="#EAEAEA" colspan="2">
<form name="bookUpdate" action="/homelibrary/UpdateBookServlet" method="POST">
<p>
<label for="Isbn">ISBN: </label>
<input type="text"readonly name="Isbn" id="Isbn" value=<%=ISBN%> >
<br><br>
<label for="Title">Title: </label>
<input type="text" name="Title" id="Title" value=<%=BookTitle%>>
<br><br>
<label for="Author">Author: </label>
<input type="text" name="Author" id="Author" value=<%=BookAuthor%>>
<br><br>
<label for="Category">Category: </label>
<input type="text" name="Category" id="Category" value=<%=Category%>>
<br><br>
<label for="Description">Description: </label>
<input type="text" name="Description" id="Description" value=<%=Description%>>
<br><br>
<p>
<input type="submit" name="Submit" value="Submit" onclick="goto">
<input type="button" name="Cancel" value="Cancel" onclick="javascript:history.go(-1);">
</p>
</form>
</td>
</tr>
</table>
</div>
</div>
<div id="footer" align="center">
<p>© Home Library</p>
</div>
</body>
</html>
UpdateBookServlet.java
package book;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
#WebServlet("/UpdateBookServlet")
public class UpdateBookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UpdateBookServlet(){
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String forward="";
String action = request.getParameter("action");
if (action == ("edit")){
String Isbn = request.getParameter("Isbn");
Book book = null;
try {
book = this.getBookByIsbn(Isbn);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("book", book);
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/UpdateBook.jsp");
dispatcher.forward(request,response);
}
//#SuppressWarnings("unused")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Book book = new Book();
response.setContentType("text/html");
request.setCharacterEncoding("gbk");
//Get data from form data
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
//#SuppressWarnings("unused")
//PreparedStatement preStmt = null;
//Connection cn =null;
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/ebookstore";
Connection cn = DriverManager.getConnection(url, "admin", "admin");
PreparedStatement prepStmt= null;
if(ISBN != null)
// create the java MySQL update PreparedStatement
prepStmt = cn.prepareStatement("UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=?");
//String update = "UPDATE book SET Title=?,Author=?,Category=?,Description=? "+" where Isbn=1111";
//prepStmt = cn.prepareStatement(update);
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));
//execute the java preparedStatment
prepStmt.executeUpdate();
cn.close();
prepStmt.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
//forwarding from Servlet to a JSP
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/Book/QueryBook.jsp");
dispatcher.forward(request,response);
}
public Book getBookByIsbn(String isbn) throws ClassNotFoundException {
Book book = new Book();
try {
//Create a java MySQL database connection
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/homelib";
Connection cn = DriverManager.getConnection(url, "root", "admin");
PreparedStatement preparedStatement = cn.
prepareStatement("SELECT * FROM book where Isbn=?");
preparedStatement.setString(1, isbn);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
book.setISBN(rs.getString("Isbn"));
book.setTitle(rs.getString("Title"));
book.setAuthor(rs.getString("Author"));
book.setCategory(rs.getString("Category"));
book.setDescription(rs.getString("Description"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return book;
}
}
Button in QueryBook.jsp
<td>Update</td>
This example is for updating a book's information when a user is logged in on the session
Insert this at the top of your JSP to identify the user on the session
if (session!=null && request.getSession().getAttribute("loggedin") != null) {
if (request.getSession().getAttribute("role").equals("Student")) {
response.sendRedirect("index.jsp");
return;
}
} else {
response.sendRedirect("index.jsp");
return;
} %>
<% if (request.getSession().getAttribute("loggedin") == null) {
response.sendRedirect("index.jsp");
return;
}
BookDTO dto = (BookDTO) request.getSession().getAttribute("book");
Then insert this code below in the JSP to post new data to the servlet
<form method="POST" action="EditBookServlet">
<div class="form-submit">
My Information
<div class="submit">
<div class="form-row">
<div class="x">
<label>Name</label>
<input type="text" class="form" value="<%= dto.getName()%>" name="name">
</div>
<div class="x">
<label>Author</label>
<input type="author" class="form" value="<%= dto.getAuthor()%>" name="author">
</div>
<div class="form x">
<button class="btn" type="submit">Save Changes</button>
</div>
</div>
</div>
</form>
In the EditBookServlet, insert this code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
BookDB db = new BookDB();
BookDTO dto = db.getBookByID(((BookDTO)
request.getSession().getAttribute("book")).getId());
dto.setName(request.getParameter("name"));
dto.setAuthor(request.getParameter("author"));
db.updateBook(dto);
request.getSession().setAttribute("book", dto);
In the StudentDB java file insert this to find the book by Id and then to update the book sql file
public BookDTO getBookByID(int id) {
BookDTO obj = null;
String query = "Select * from book where id=?";
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(query);
pst.setInt(1,id);
rs = pst.executeQuery();
if (rs != null) {
if (rs.next()) {
obj = new BookDTO();
obj.setId(rs.getInt(1));
obj.setName(rs.getString(2));
obj.setAuthor(rs.getAuthor(3));
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(BookDB.class.getName()).log(Level.SEVERE, null, ex);
}
}
public boolean updateBook(BookDTO obj) {
int affectedRows = 0;
String query = "update `book` set name=? , author=lower(?) where id=?";
PreparedStatement pst = null;
try {
pst = conn.prepareStatement(query);
pst.setString(1,obj.getName());
pst.setString(2,obj.getAuthor());
pst.setInt(10, obj.getId());
System.out.println(pst);
affectedRows = pst.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Book.class.getName()).log(Level.SEVERE, null, ex);
}
return affectedRows > 0;
}
You said in your comment:
The update page return with null for all the values.
That is, because you intantiate the Book object In UpdateBookServlet.java
Book book = new Book();
but you set the request parameters into separate string objects:
String ISBN = request.getParameter("Isbn");
String BookTitle = request.getParameter("Title");
String BookAuthor = request.getParameter("Author");
String Category = request.getParameter("Category");
String Description = request.getParameter("Description");
But never use them. Instead you add data from the empty Book object:
prepStmt.setString(1, book.getTitle());
prepStmt.setString(2, book.getAuthor());
prepStmt.setString(3, book.getCategory());
prepStmt.setString(4, book.getDescription());
prepStmt.setInt(5, Integer.parseInt(book.getISBN()));

How to insert and retrieve image database using jsp/Servlet?

I have got a Form Page index.jsp :
<%#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>
<style>
fieldset
{
width: 70px;
}
</style>
</head>
<body>
<form action="Upload" method="post" enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Select Photo</td>
<td><input type="file" name="photo"></td>
</tr>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
MyServlet Page Upload.java:
import java.sql.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
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(name = "Upload", urlPatterns = {"/Upload"})
#MultipartConfig(maxFileSize = 169999999) // upload file's size up to 16MB
public class Upload extends HttpServlet
{
private static final long serialVersionUID = 1L;
PrintWriter out;
InputStream inputStream = null;
int allField = 0;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try
{
out = response.getWriter();
String name=request.getParameter("name");
Part filePart = request.getPart("photo");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","root")
PreparedStatement ps = con.prepareStatement("insert into PhotoDetails(Name,Images)values(?,?)");
ps.setString(1,name);
ps.setBlob(2,inputStream);
ps.executeUpdate();
out.println("Image Inserted");
}
catch(Exception e)
{
out.println(e);
}
}
}
I am using mysql database and here is my table:
create table PhotoDetails
(
Name varchar(100),
Images blob
)
After filling all the form and when I click on the Update button then I get this error :
HTTP Status 500 - Servlet execution threw an exception
How could I resolve this problem?
This is the best way to show image in jsp file.
Just create showLogo.jsp
and include where ever you want it.
<%# page trimDirectiveWhitespaces="true" %>
<%# page import="java.sql.*,java.io.*,org.apache.struts2.ServletActionContext"%>
<%# page language="java" import="java.util.*, com.abc.util.dbutil.*,javax.servlet.http.HttpServletRequest" %>
<%
try{
InputStream sImage;
ResultSet resultSet = null;
PreparedStatement pstmt = null;
DBConnection dbConnection= null;
dbConnection= new DBConnection();
Connection con = null;
con= dbConnection.getConnection();
ServletInputStream sInIm = null;
Statement st=con.createStatement();
String company_id = request.getParameter("company_id");
resultSet=st.executeQuery("select logo from company where company_id='" + company_id + "'");
if(resultSet.next()){
byte[] bytearray = new byte[1048576];
int size=0;
sImage = resultSet.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1){
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
con.close();
}
catch(Exception ex){
}
%>
I am getting it like this.
/company/showLogo.jsp?company_id=" id="blah_s" class="logo-small">
Get image from file to FileInputStream
FileInputStream fs = null;
try {
fs = new FileInputStream(getUserImage());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
.................
ps.setBinaryStream(8, fs, fs.available());
insert into table(logo) values (?)
This is for mysql with blob column.

insert and update in mysql table using JDBC

There are two tables in my database (filedetails and filestatus).
I using the following code to insert value in filedetails table.
In filestatus table i have 3 columns
filenumber,
fdepartment,
status(either in or out).
In my status.jsp page I have given 3 dropdown list in which 2 dropdownlist take filenumber and department from filedetails table and 1 takes status(which is either IN or OUT).
If status is OUT values are simply inserted in filestatus table but if it is in the values are inserted into filestatus and department corresponding to filenumber gets updated.
The problem is the filenumber, if i use the following code to insert filenumber then how will i update the file number ?
Is ther some other way to do this?
file.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert File Page</title>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}
section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<font color="black">back</font>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<form action="FileServlet" method="post">
<h3>Insert File Details</h3>
<table border="1">
<tbody>
<tr>
<td>File Name :</td>
<td><input type="text" name="filename" value="" size="50" /></td>
</tr>
<tr>
<td>File Type</td>
<td><input type="text" name="type" value="" size="50" /> </td>
</tr>
<tr>
<td>Place of Origin(company) :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>HeadOffice :</td>
<td><input type="text" name="HO" value="" size="50" /> </td>
</tr>
<tr>
<td>File Location :</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Subject :</td>
<td><input type="text" name="subject" value="" size="50" /></td>
</tr>
<tr>
<td>File Number :</td>
<td><input type="text" name="fileno" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</section>
<footer>
Copyright 2008 NSIC. All right reserved.
</footer>
</body>
</html>
fileServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class FileServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("JSESSIONID")){
System.out.println("JSESSIONID="+cookie.getValue());
break;
}
}
}
HttpSession session = request.getSession(false);
System.out.println("User="+session.getAttribute("user"));
if(session!=null && session.getAttribute("user") != null){
String user=(String)session.getAttribute("user");
boolean status=false;
try{
String fname=request.getParameter("name");
String type=request.getParameter("type");
String company=request.getParameter("department");
String headoffice=request.getParameter("HO");
String location=request.getParameter("department");
String subject=request.getParameter("subject");
String fno=company+"/"+headoffice+"/"+location+"/"+type+"/"+fname;
Connection con=ConnectionProvider.getCon();
String sql="insert into files(fileno,fname,ftype,subject,company,headoffice,fdepartment) values (?,?,?,?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,fno);
pstmt.setString(2,fname);
pstmt.setString(3,type);
pstmt.setString(4,subject);
pstmt.setString(5,company);
pstmt.setString(6,headoffice);
pstmt.setString(7,location);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){System.out.println(e);}
if(status){
PrintWriter out= response.getWriter();
out.println("Values have been inserted"+user);
response.sendRedirect("create1.jsp");
}
else
{
PrintWriter out= response.getWriter();
out.println("failed");
response.sendRedirect("create1.jsp");
}
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
There is create.jsp which gives link to choose for filedetails.jsp or status.jsp
status.jsp
<%#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>File Status Page</title>
<style>
header {
background-color:teal;
color:white;
text-align:center;
padding:30px;
}
section {
width:350px;
float:left;
padding:150px;
}
footer {
background-color:black;
color:white;
clear:both;
text-align:center;
padding:5px;
}
</style>
</head>
<body style="background-color:lightsteelblue;">
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
%>
<header>
<h3>Hi <%=userName %></h3>
</header>
<font color="black">back</font>
<form action=" LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
<section>
<h3>Change Status</h3>
<form action="statusServlet" method="post">
<select name="files">
<%
try{
String sql="select * from files";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
"root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>
<option value="<%=rs.getInt("fileno")%>"><%=rs.getString("fname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</select>
<select name="departments">
<%
try{
String sql="select * from department";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login",
"root", "root");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next()){
%>
<option value="<%=rs.getInt("departmentid")%>"><%=rs.getString("departmentname")%></option>
<%}
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
%>
</select>
<select name="input">
<option>IN</option>
<option>OUT</option>
</select>
<input type="submit" value="submit" name="submit" />
</form>
</section>
<footer>
Copyright 2008 NSIC. All right reserved.
</footer>
</body>
</html>
I have not yet created statusServlet.java
I will seperate department into two parts like below.
1) Department from which the file is being originated
2) Current location of file.
I will use the file origin department for generating the filenumber and will update the current location separately (Initially the current location will be same as origin department).
If anyone having more effective way than this, then I will accept that too.

Checking the data into database before insertion

I need help in checking the data into the database before insertion.
Issue:
I have used the general method to insert the values into database.But I need to include this condition into my servlet code i.e if a data is already present in the database,then that data should not be inserted into the database and the remaining data should be inserted into the database.While doing this no alert should be raised to the user.
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());
}
}
}
}

Categories