Checking the data into database before insertion - java

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

Related

How do I output results of an SQL query using java servlet

I'm trying to implement a search feature to my web application that allows a user to search a database of products. I've attempted to do this using the following:
The .jsp file for the web page which starts by listing all products (productSearch.jsp):
<%#page import="java.sql.Connection"%>
<%#page import="databaseManagement.DBConnection"%>
<%#page import="java.sql.ResultSet" %>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Search Our Products</title>
</head>
<body>
<form method="post">
Search:<input type="text" name="Search">
<input type="submit" value="Go">
<table border="2">
<tr>
<td>ID</td>
<td>NAME</td>
<td>DESCRIPTION</td>
<td>PRICE</td>
</tr>
<%
try
{
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getString("DESCRIPTION") %></td>
<td><%=rs.getString("PRICE") %></td>
</tr>
<%
}
%>
</table>
<%
rs.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</body>
</html>
The class to take the user's input and run the query (ProductSearch.java):
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import databaseManagement.DBConnection;
#WebServlet("/ProductSearch")
public class ProductSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductSearch() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
try {
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement("select * from products where name like %?%");
ps.setString(1, searchTerm);
ResultSet rs = ps.executeQuery();
return;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And lastly a class to handle the connection to the database (DBConnection):
package databaseManagement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
// TODO: finish
//CHANGE USERNAME AND PASSWORD WHEN IMPLIMENTING ON VM
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/applicationdata", "root", "safepassword");
return con;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
}
The issue I'm now having is that I'm not sure how to take the results I got from the ProductSearch class and display them back in the productSearch.jsp page.
I'm quite new to this, so I apologise if I've made any glaring mistakes. Any help is greatly appreciated :)
Firstly , create a class where all values which you want return back is declared and also getter/setter of that variable .
i.e Suppose variable user.
import java.util.*;
public class Abc{
private String user;
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Abc(String user) {
this.user = user;
}
}
Next , In your ProductSearch.java file put this code :
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
ArrayList<Abc> ab= new ArrayList();
try
{
String sql1 ="select * from products where name like %?%";
PreparedStatement ps = conn.prepareStatement(sql1);
ps.setString(1,searchTerm);
resultSet = ps.executeQuery();
while(resultSet.next())
{
Abc b=new Abc();
b.setUser(resultSet.getString("user"));
ab.add(b);
}
request.setAttribute("r1", ab);
request.getRequestDispatcher("productSearch.jsp").forward(request, response);
}
catch(Exception s2)
{
s2.printStackTrace();
}
}
}
Lastly print result back in your productSearch.jsp page using jstl
<!-- this is use because we use jstl tag-->
<%#taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<table align="center" border="1">
<tr bgcolor="#d9ac26">
<td><b>search</b></td>
</tr>
<!--Here we are printing result-->
<c:forEach var="book" items="${r1}">
<tr bgcolor="">
<td>${book.user}</td>
</tr>
</c:forEach>
</table>
Hope this helps you. Make necessary changes as per your requirement . This is not complete code .

Why deos Weblogic log says bean can not be resolved when I try to use the bean class object in a jsp file?

I was trying to make a simple E-Commerce website using MVC architecture in java. Initially I made a controller servlet which is named TestingServlet,a web.xml file,a bean class in the package com.bean under classes folder named DbBean and a Default.jsp,Header.jsp,Menu.jsp to start with. I compiled bean and the servlet classes. Then finally when I deployed the application on WebLogic server and run it, I got the following error-
As you can see in the log that it says it failed to compile JSP JSP/Menu.jsp which means the problem must be with Menu.jsp. Moreover, it says that in line 28 bean cannot be resolved. So, I checked that part of the code but it looks fine to me. What is causing the problem?
Following are all the files that I made-
TestingServlet.java
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import com.bean.DbBean;
public class TestingServlet extends HttpServlet
{
public void init(ServletConfig conf)
{
System.out.println("Initiallizing ControllerServlet");
ServletContext ctx = conf.getServletContext();
ctx.setAttribute("base",conf.getInitParameter("base"));
System.out.println("base = " +conf.getInitParameter("base"));
ctx.setAttribute("imageUrl",conf.getInitParameter("imageUrl"));
System.out.println("imageUrl = " +conf.getInitParameter("imageUrl"));
DbBean bean = new DbBean();
bean.setDbUrl(conf.getInitParameter("dbUrl"));
bean.setDbUserName(conf.getInitParameter("userName"));
bean.setDbPassword(conf.getInitParameter("password"));
ctx.setAttribute("bean",bean);
System.out.println("bean object successfully made,its properties set
and set in app scope..");
try
{
Class.forName(conf.getInitParameter("jdbcDriver"));
System.out.println("Driver Class Loaded Successfully");
}
catch(Exception e)
{
System.out.println("Could not load the driver class");
}
}
protected void doGet(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
doPost(req,res);
System.out.println("in doGet method");
}
protected void doPost(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
System.out.println("in doPost method");
String base = "/jsp/";
String url = base + "Default.jsp";
String action = req.getParameter("action");
if(action!=null)
{
if(action.equals("search"))
url = base + "SearchResults.jsp";
else if(action.equals("browseCatalog"))
url = base + "BrowseCatalog.jsp";
if(action.equals("productDetails"))
url = base + "ProductDetails.jsp";
if(action.equals("addShoppingItem") ||
action.equals("updateShoppingItem") ||
action.equals("deleteShoppingItem") ||
action.equals("displayShoppingCart"))
url = base + "ShoppingCart.jsp";
if(action.equals("checkOut"))
url = base + "CheckOut.jsp";
if(action.equals("order"))
url = base + "Order.jsp";
}
System.out.println("if part successfully executed");
RequestDispatcher rd = req.getRequestDispatcher(url);
System.out.println("RD object made successfully..");
rd.forward(req,res);
System.out.println("forward successfully executed..");
}
}
DbBean.java
package com.bean;
import java.sql.*;
import java.util.Hashtable;
public class DbBean
{
public String dbUrl = "";
public String dbUserName = "";
public String dbPassword = "";
public void setDbUrl(String url)
{
dbUrl = url;
}
public void setDbUserName(String userName)
{
dbUserName = userName;
}
public void setDbPassword(String password)
{
dbPassword = password;
}
public Hashtable getCategories()
{
Hashtable categories = new Hashtable();
try
{
Connection conn =
DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
Statement stmt = conn.createStatement();
String sql = "select CategoryId,Category from Categories" +" ";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next())
{
categories.put(rs.getString(1),rs.getString(2));
}
rs.close();
stmt.close();
conn.close();
}
catch(SQLException e)
{}
return categories;
}
}
Default.jsp
<html>
<head>
<title>Welcome</title>
</head>
<body>
<table>
<tr>
<td colspan="2">
<jsp:include page="Header.jsp" flush = "true"/>
</td>
</tr>
<tr>
<td>
<jsp:include page="Menu.jsp" flush="true"/>
</td>
<td valign="top">
<H2>WELCOME TO MY E-MALL.</H2>
</td>
</tr>
</table>
</body>
</html>
Menu.jsp
<%# page import="java.util.*" %>
<jsp : useBean id = "bean" scope = "application" class="com.bean.DbBean" />
<%
String base = (String)application.getAttribute("base");
%>
<table cellspacing="0" cellpadding="5" width="150" border="0">
<tr>
<td bdcolor="F6F6F6">
<font face="Verdana">Search</font>
<form>
<input type="hidden" name="action" value="search">
<input type="text" name="keyword" size="10">
<input type="submit" value="Go">
</form>
</td>
</tr>
<tr >
<td bgcolor="F6F6F6">
<font face="Verdana">
Categories:
</font>
</td>
</tr>
<tr valign="top">
<td bgcolor="F6F6F6">
<%
Hashtable categories = bean.getCategories();
Enumeration categoryIds = categories.keys();
while(categoryIds.hasMoreElements())
{
Object categoryId = categoryIds.nextElement();
out.println("<a href=" +base +"?
action=browseCatalog&categoryId=" +categoryId.toString()
+">" +categories.get(categoryId) +"</a><br>");
}
%>
</td>
</tr>
</table>
The jsp : useBean is for use with Objects that are Java Beans.
Is it the case that DbBean does not adhere to the JavaBeans conventions i.e. have a look at What is a JavaBean exactly? and maybe you could change DBean to adhere to the conventions or you could just drop the use of jsp : useBean and just instansiate and manipulate it in the scriptlet?

simple login servlet not giving output [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 5 years ago.
I developed simple login servlet which runs well in eclipes but i am not getting any output from server side help to fix this
used create statement not prepared statement
help to improve logic
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>welcome to Student Account</title>
</head>
<body>
<font color="red">
<center>
Welcome to Student portal <br> <b>kindly login to your acccount</b></br> <b>Login
form</b>
<form method="post" action="./Account">
<table>
<tr>
<td>Student Login:</td>
<td><input type="text" name="sname"></td>
</tr>
<tr>
<td>Student Password:
<td><input type="password" name="spasswd"></td>
</tr>
<tr>
<td>
</td>
<td><input type="submit" value="login"> <input
type="reset" value="reset"></td>
</tr>
</table>
</center>
</body>
</html>
StudentAccInfo.java
import java.io.IOException;
import java.io.PrintWriter;
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("/Account")
public class StudentAccInfo extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String sname=request.getParameter("sname");
String spasswd=request.getParameter("spasswd");
String Status=UserService.validate(sname, spasswd);
out.println("<html><body><center>");
out.println("<font color='red' size='7'>");
if(Status.equals("success")){
out.println("Login Success");
}
if(Status.equals("failure")){
out.println("Login failure");
}
out.println("</center></body></html>");
}
}
UserService.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class UserService {
public static String validate(String sname, String spasswd)
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
String Status="";
try{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:ORCL", "scott", "tiger");
st=con.createStatement();
String sql="";
sql=sql+"select * from std where sname=";
sql=sql+"'"+sname+"'";
sql=sql+" "+"and spasswd=";
sql=sql+"'"+spasswd+"'";
rs=st.executeQuery(sql);
boolean b=rs.next();
if(b==true){
Status="success";
}else{
Status="failure";
}
}catch(Exception e){
e.printStackTrace();
}finally {
try{
con.close();
st.close();
rs.close();
}catch(Exception e){
e.printStackTrace();
}
}
return Status;
}
}
Note:- I have used create Statement not prepared statement
running well but not getting output
remove ./ from action attribute
<form method="post" action="Account">

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.

put rows with same name together

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

Categories