Populating Java List in Spring MVC - java

I am populating a list in backend in java. Setting attribute in spring model and want to iterate and show that list in front end.
But the list turns out to be empty. I debugged and checked that list is getting populated at the backend.
Can we anyone help to debug and tell what I am missing.
In the model I am setting the values to model.addAttribute("videos", temp);
<table class="table table-bordered" style="width:100%">
<col width = 33%>
<col width = 33%>
<col width = 33%>
<thead>
<tr>
<th style="text-align:center">Title</th>
<th style="text-align:center">Source</th>
<th style="text-align:center">Link</th>
</tr>
</thead>
<tbody>
<c:forEach items="${videos}" var="temp">
<tr>
<td><c:out value="${temp.title}"/></td>
<td><c:out value="${temp.source}"/></td>
</tr>
</c:forEach>
</tbody>
</table>
Browser Console Image
Controller Code:
UserLoginJDBCTemplate uLoginJDBCTemplate =
(UserLoginJDBCTemplate)context.getBean("userLoginJDBCTemplate");
List<VideoList> videos = uLoginJDBCTemplate.listVideos(user.getName(),true);
// model.addAttribute("modules", modules);
model.addAttribute("videos", videos);
return "result";
JDBC Connection -
List <VideoList> videos = new ArrayList<VideoList>();// jdbcTemplateObject.query(SQL, new VideoListMapper());
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(SQL);
ps.setString(1, uname);
ResultSet rs = ps.executeQuery();
VideoList temp;
rs = ps.executeQuery();
if (rs.next()) {
temp = new VideoList(rs.getString("title"),rs.getString("source"),rs.getString("actual_url"));
videos.add(temp);
}
rs.close();
ps.close();
return videos;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}

Related

How can I insert and delete value in a database in derby in JSP? [3]

The history:
History I.
History II.
So the problem is still here. If I select somebody and press the delete button, not to delete from database else a new empty record created.
The client.java:
public class client implements DatabaseConnection{
private static Connection conn = null;
private static void createConnection(){
try {
conn = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void closeConnection(){
if (conn != null){
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(client.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public List clientList(){
createConnection();
List list=new ArrayList();
try {
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM customer");
while(rs.next()){
**list.add(rs.getString("ID"));**
list.add(rs.getString("CNAME"));
list.add(rs.getString("ADDRESS"));
list.add(rs.getString("PHONENUMBER"));
}
stmt.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
return list;
}
public void newClient(String name, String address, String phoneNumber)
throws SQLException{
PreparedStatement ps = null;
try {
createConnection();
String insert="INSERT INTO CUSTOMER(CNAME,ADDRESS, PHONENUMBER)
VALUES(?,?,?)";
ps=conn.prepareStatement(insert);
ps.setString(1, name);
ps.setString(2, address);
ps.setString(3, phoneNumber);
ps.executeUpdate();
ps.close();
} catch (Exception e) {
e.printStackTrace(System.err);
}
finally {
ps.close();
closeConnection();
}
}
public void deleteClient(String ID){
try {
createConnection();
String delete="DELETE FROM CUSTOMER WHERE ID=?";
PreparedStatement ps=conn.prepareStatement(delete);
ps.setString(1, ID);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace(System.err);
}
**finally {
closeConnection();
}**
}
}
The index.jsp:
<jsp:useBean id="client" class="database.client" scope="page" />
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body bgcolor="lightgrey">
<%
String ID=request.getParameter("ID");
String NAME=request.getParameter("CNAME");
String ADDRESS=request.getParameter("ADDRESS");
String PHONENUMBER=request.getParameter("PHONENUMBER");
%>
<form method="post" action="">
<table border="0" align="left">
<th colspan="2" align="center" style="color: brown">Field</th>
<tr>
<td>Name:</td>
<td><input type="text" name="CNAME" style="background-
color:beige"/></td>
</tr>
<tr>
<td>Address?</td>
<td><input type="text" name="ADDRESS" style="background-
color:beige"/></td>
</tr>
<tr>
<td>PhoneNumber:</td>
<td><input type="text" name="PHONENUMBER" style="background-
color:beige"/></td>
</tr>
<input type="submit" name="OK" onclick="
<%
if(NAME!=null && ADDRESS!=null && PHONENUMBER!=null){
client.newClient(NAME, ADDRESS, PHONENUMBER);
}
%>" value="OK"/>
<input type="submit" name="Cancel" onclick="
<%
//nothing
%>" value="Cancel"/>
<input type="submit" name="Delete" onclick="
<%client.deleteClient(ID);%>" value="Delete"/>
</table>
<table border="2">
<th colspan="4" align="center" bgcolor="orange">Clients</th>
<tr bgcolor="silver" align="center">
<td> </td>
**<td>ID</td>**
<td>Name</td>
<td>Address</td>
<td>PhoneNumber</td>
</tr>
<%
List list=client.clientList();
Iterator it=list.iterator();
while(it.hasNext()){
out.print("<tr bgcolor='lightgreen'>");
out.print("<td>");
**ID**=(String)it.next();
out.print("<input type='radio' name='ID' value="+**ID**+"/>");
out.print("</td>");
out.print("<td>");
out.print(**ID**);
out.print("</td>");
for (int i = 0; i < **3**; i++) {
out.print("<td>");
out.print(it.next());
out.print("</td>");
}
out.print("</tr>");
}
%>
</table>
</form>
</body>
</html>
Just create a new Servlet (Delete Servlet) and pass the ID in url and handle it in new jsp page ...You can change your code likethis :
Index JSP:
Delete
Delete Servlet : Updated
#WebServlet(name = "DeleteServlet", urlPatterns = {"/DeleteServlet"})
public class DeleteServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(CurdOperationsImpl.class.getName());
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String ID = request.getParameter("id");
int id = Integer.parseInt(PersonId);
deleteClient(id); // add your own code
out.println("<h2 style='color: green'>Person Deleted Sucessfully.</h2>");
response.sendRedirect("index.jsp");
}else {
}
}
Bonus : get this my ugly Servlet-JSP-Mysql project is ready to use Github link
I hope this help you.

print complete rows in table which is passed from servlet

I have one jsp page and one servlet, In servlet i want to fetch some rows from a particular table and pass them to jsp .I am able to retrieve in servlet and trying to pass them in jsp it is not getting displayed please anyone help me out here...
public class TimeDetail extends HttpServlet {
#SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession(true);
String eid = (String) session.getAttribute("eid");
int count = 0;
Connection con = ConnectionManager.getConnection();
try {
Statement st = con.createStatement();
Statement st1 = con.createStatement();
String Query = "select date, intime, outtime, eid from fulltime where eid='" + eid + "'";
ArrayList Rows = new ArrayList();
ResultSet rs = st.executeQuery(Query);
List agentList = new ArrayList();
while (rs.next()) {
ArrayList row = new ArrayList();
for (int i = 1; i <= 4; i++) {
row.add(rs.getString(i));
}
String n1 = rs.getString("date");
String n2 = rs.getString("intime");
String n3 = rs.getString("outtime");
String n4 = rs.getString("eid");
session.setAttribute("n1", n1);
session.setAttribute("n2", n2);
session.setAttribute("n3", n3);
session.setAttribute("n4", n4);
// response.sendRedirect("TimeDetail.jsp");
Rows.add(row);
}
request.getSession().setAttribute("results", Rows);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/TimeDetail.jsp");
rd.forward(request, response);
} catch (Throwable theException) {
System.out.println(theException);
}
}
}
and here is jsp code
<tr><td>
<table width="600" height="300"align=center cellspacing=0 border="0"
<caption><h2>List of users</h2></caption>
<tr>
<th>date</th>
<th>intime</th>
<th>outtime</th>
<th>eid</th>
</tr>
<c:forEach var="user" items="${Rows.rows}">
<tr>
<td><c:out value="${user.date}" /></td>
<td><c:out value="${user.intime}" /></td>
<td><c:out value="${user.outtime}" /></td>
<td><c:out value="${user.eid}" /></td>
</tr>
</c:forEach>
</table>
</div>
</table><BR>
</fieldset>
</td></tr></table>
</td></tr>
</table>
</body>
</html>
Your for each loop should be like this ,
<c:forEach var="user" items="${results}">
<tr>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
<td><c:out value="${user}" /></td>
</tr>
</c:forEach>
And your servlet as ,
try {
Statement st = con.createStatement();
Statement st1 = con.createStatement();
String Query = "select date, intime, outtime, eid from fulltime where eid='" + eid + "'";
ArrayList row = new ArrayList();
ResultSet rs = st.executeQuery(Query);
while (rs.next()) {
row.add(rs.getString("date"));
row.add(rs.getString("intime"));
row.add(rs.getString("outtime"));
row.add(rs.getString("eid"));
}
}
request.getSession().setAttribute("results", row);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/TimeDetail.jsp");
rd.forward(request, response);
Hope this helps !!

Getting list of strings from servlet to jsp

I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")

How to get jquery text editor in multiple text area in one action

I have a jquery text Editor & Have a Multiple Text area I want to show jquery text editor in every text area in one action but only first text area i able to show text editor
Here is my Jquery Code
<script type="text/javascript" id="themeUIPhysicalFinding">
$(document).ready(function () {
var options = {
width: 962,
height: 230,
controls: "bold italic underline strikethrough subscript superscript | font size " +
"style | color highlight removeformat | bullets numbering | outdent " +
"indent | alignleft center alignright justify | undo redo | " +
"rule link image unlink | cut copy paste pastetext | print source"
};
var editor = $("#editor").cleditor(options)[0];
// $("#editor").kendoEditor({
// encoded: false
// });
//alert("asdfasdf");
$("#Generate").click(function () {
alert($("#editor").value());
//$("#editor").val("");
});
});
</script>
My Java Script Action Code is
function getPatientInformationTest(){
var admissionNo=document.getElementById("apnNo").value;
var url = "getPatientDemographyActionTestIPDPatientInfo.do?patientAdmissionNo="+admissionNo;
makeRequestNoImage(url,"patientDischargeDiv" ,"themeUIPhysicalFinding");
here is my HTML code
<%#taglib prefix="s" uri="/struts-tags"%>
<!--
-->
<div>
<table border="0" class="" width="100%">
<tr>
<td><fieldset><legend>Patient Demography </legend><table width="100%" style="border:0px solid #FFFFFF" cellpadding="0" cellspacing="0">
<tr>
<td>HN</td>
<td><s:property value='deschargeInfo.patientRegistrationNo'/></td>
</tr>
<tr>
<td>Age</td>
<td><s:property value='deschargeInfo.patientAge'/></td>
</tr>
<tr>
<td>Name</td>
<td><s:property value='deschargeInfo.patientName'/></td>
</tr>
<tr>
<td>Gender</td>
<td><s:property value='deschargeInfo.patientGender'/></td>
</tr>
<tr>
<td>Contact Info</td>
<td><s:property value='deschargeInfo.patientContactNo'/></td>
</tr>
</table></fieldset></td>
<td><fieldset><legend>Doctor's Info</legend><table width="100%" border="0" style="border:0px solid #FFFFFF" cellpadding="0" cellspacing="0">
<tr>
<td>Admitted Under</td>
<td><s:property value='deschargeInfo.patientAdmittingUnder'/></td>
</tr>
<tr>
<td>Admitted By</td>
<td><s:property value='deschargeInfo.patientAdmittingDoctor'/></td>
</tr>
<tr>
<td>Department Name</td>
<td><s:property value='deschargeInfo.departmentName'/></td>
</tr>
</table></fieldset></td>
<td><fieldset><legend>Admission Information</legend><table width="99%" border="0" style="border:0px solid #FFFFFF" cellpadding="0" cellspacing="0">
<tr>
<td>Date Of Admission</td>
<td><s:property value='deschargeInfo.patientDateOfAdmission'/></td>
</tr>
<tr>
<td>Date Of Discharge</td>
<td><s:property value='deschargeInfo.patientDateOfDischarge'/></td>
</tr>
<tr>
<td>Length of LOS</td>
<td><s:property value=''/></td>
</tr>
<tr>
<td>Ward No</td>
<td><s:property value='deschargeInfo.patientWordNo'/></td>
</tr>
<tr>
<td>Bed/Cabin No</td>
<td><s:property value='deschargeInfo.patientBedNo'/></td>
</tr>
</table></fieldset></td>
</tr>
<tr>
<td height="265" colspan="3"><div id="headerRemoveDiv">
<table class="subTableCC" width="100%">
<tr>
<th width="100%">Header Name</th>
<!-- <th width="42">Remove</th>-->
</tr>
<s:iterator status="stat" value="deschargeList">
<tr>
<td width="100%">
<s:property value="headerName" />
</td>
</tr>
<tr>
<td width="100%" height="211" colspan="8" style="padding:0px;">
<textarea name="textarea" cols="150" rows="13" id="<s:property value='headerNo'/>" ></textarea></td>
</tr>
</s:iterator>
</table></div></td>
</tr>
</table>
</div>
Here is my Java action class code
public String getPatientDemographyActionTest(){
PatientDischargeInfo patientDischargeInfo = new PatientDischargeInfo();
deschargeInfo=patientDischargeInfo.getPatientInfoForDescharge(patientAdmissionNo);
DepartmentHeaderInfo departmentHeaderInfo = new DepartmentHeaderInfo();
deschargeList=departmentHeaderInfo.getDepartmentHeader(patientAdmissionNo);
ActionContext.getContext().getSession().put(sessionVariable.getHeaderInfo(), deschargeList);
return "getPatientDemographyActionTest";
}
Here is my SQL code
public PatientDeschargeInfo getPatientInfoForDescharge(
String p_admission_no) {
//String vDAY_PK_NO = "";
if (dbConnection == null) {
dbConnection = new DatabaseConnection();
}
String strProcedure = "{call pkg_discharge.prc_dispatinfo(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}";
try {
connection = dbConnection.connectDB();
cs = connection.prepareCall(strProcedure);
cs.setString(1, p_admission_no);
cs.registerOutParameter(2, java.sql.Types.DATE);
cs.registerOutParameter(3, java.sql.Types.DATE);
cs.registerOutParameter(4, java.sql.Types.VARCHAR);
cs.registerOutParameter(5, java.sql.Types.VARCHAR);
cs.registerOutParameter(6, java.sql.Types.VARCHAR);
cs.registerOutParameter(7, java.sql.Types.VARCHAR);
cs.registerOutParameter(8, java.sql.Types.VARCHAR);
cs.registerOutParameter(9, java.sql.Types.VARCHAR);
cs.registerOutParameter(10, java.sql.Types.VARCHAR);
cs.registerOutParameter(11, java.sql.Types.VARCHAR);
cs.registerOutParameter(12, java.sql.Types.VARCHAR);
cs.registerOutParameter(13, java.sql.Types.VARCHAR);
cs.registerOutParameter(14, java.sql.Types.VARCHAR);
cs.registerOutParameter(15, java.sql.Types.VARCHAR);
cs.registerOutParameter(16, java.sql.Types.VARCHAR);
cs.registerOutParameter(17, java.sql.Types.VARCHAR);
cs.execute();
//deschargeInfo = new PatientDeschargeInfo();
deschargeInfo.setPatientDateOfAdmission(cs.getDate(2));
deschargeInfo.setPatientDateOfDischarge(cs.getDate(3));
deschargeInfo.setPatientRegistrationNo(cs.getString(4));
deschargeInfo.setPatientName(cs.getString(5));
deschargeInfo.setPatientNationalId(cs.getString(6));
deschargeInfo.setPatientGender(cs.getString(7));
deschargeInfo.setPatientBloodGroup(cs.getString(8));
deschargeInfo.setPatientContactNo(cs.getString(9));
deschargeInfo.setPatientAge(cs.getString(10));
deschargeInfo.setPatientAdmittingDoctor(cs.getString(11));
deschargeInfo.setPatientAdmittingUnder(cs.getString(12));
deschargeInfo.setPatientBedNo(cs.getString(13));
deschargeInfo.setPatientWordNo(cs.getString(14));
deschargeInfo.setPatientAddress(cs.getString(15));
deschargeInfo.setDepartmentId(cs.getString(16));
deschargeInfo.setDepartmentName(cs.getString(17));
// vDAY_PK_NO = cs.getString(9);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
cs.close();
connection.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// System.out.println("pkStrring " + vDAY_PK_NO);
return deschargeInfo;
}
SQL code is ..
public List<PatientDeschargeInfo> getDepartmentHeader(String ADMISSION_NO){
List<PatientDeschargeInfo> deschargeInfo = new ArrayList<PatientDeschargeInfo>() ;
boolean fg = true;
con = dbc.connectDB();
if (con == null) {
fg = false;
}
if(fg){
try{
st=con.createStatement();
String qty ="select LKP_ID , (select lkp_name " +
"from m00_lkp " +
"where grp_id =10 " +
"and rsta = 0 " +
"and lkp_id = a.lkp_id) head_name " +
"from eh_discheadmap a " +
"where dept_no = ( select parent_dept " +
"from hr_dept " +
"where dept_no = (select dept_no " +
"from ip_admission " +
"where admission_no = '"+ADMISSION_NO+"'))";
System.out.println("Qry :"+qty);
rs = st.executeQuery(qty);
while (rs.next()) {
//deschargeInfo.setPatientAddress(rs.getString(""));
//deschargeInfo.setPatientAdmissionNo(rs.getString(""));
PatientDeschargeInfo patientDeschargeInfo = new PatientDeschargeInfo();
patientDeschargeInfo.setHeaderName(rs.getString("head_name"));
patientDeschargeInfo.setHeaderNo(rs.getInt("LKP_ID"));
deschargeInfo.add(patientDeschargeInfo);
//resultList.add(deschargeInfo);
}
} catch (SQLException sq) {
sq.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
}
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
return deschargeInfo;
}

Querying data from Oracle database using java servlet with Netbeans

From index.jsp code,
statement.executeQuery("select * from fus where tester_num like 'hf60' ") ;
Example I want "hf60" to be a variable(userinput), wherein USER must input/write data from input text then submit and get the data so that the result will be
("select * from fus where tester_num like 'userinput' ")
Where should I insert that code, Is it in InsertServlet .java or in Index.jsp.? or make another filename.java code? Please help. Thanks;)
Index.jsp
<%# page import="java.sql.*" %>
<% Class.forName("oracle.jdbc.driver.OracleDriver"); %>
<HTML>
<HEAD>
<TITLE>SHIFT REPORT </TITLE>
</HEAD>
<BODY BGCOLOR=##342D7E>
<CENTER>
<H2><FONT COLOR="#ECD672" FACE="Verdana" >SHIFT REPORT</FONT></H2></CENTER>
<hr>
<%
Connection connection=DriverManager.getConnection ("jdbc:oracle:thin:#oradev2.*****.com:1521:RPADB","shift_admin", //
"shift_admin"
);
Statement statement = connection.createStatement() ;
//**Should I input the codes here?**
ResultSet resultset =
statement.executeQuery("select * from fus where tester_num like 'hf60") ;
%>
<TABLE BORDER="1" BGCOLOR="CCFFFF" width='200%' cellspacing='1' cellpadding='0' bordercolor="black" border='1'>
<TR>
<TH bgcolor='#DAA520'> <font size='2'>RECORD NUMBER</TH>
<TH bgcolor='#DAA520'><font size='2'>TESTER NUMBER</TH>
<TH bgcolor='#DAA520'><font size='2'>DATE</TH>
<TH bgcolor='#DAA520'><font size='2'>TIME</TH>
<TH bgcolor='#DAA520'><font size='2'>SYSTEM TYPE</TH>
<TH bgcolor='#DAA520'><font size='2'>PACKAGE</TH>
<TH bgcolor='#DAA520'><font size='2'>SOCKETS</TH>
<TH bgcolor='#DAA520'><font size='2'>VALIDATED BY</TH>
</TR>
<% while(resultset.next()){ %>
<TR>
<TD> <font size='2'><center><%= resultset.getLong(1) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(2) %></center></TD>
<TD> <font size='2'><center><%= resultset.getDate(3) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(4) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(5) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(6) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(7) %></center></TD>
<TD> <font size='2'><center><%= resultset.getString(8) %></center></TD>
</TR>
<% } %>
</TABLE>
</BODY>
</HTML>
InsertServlet.java
package fusion.shift.servlets.db;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class InsertServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
public void destroy() {
}
public boolean processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String rec_num = request.getParameter("rec_num");
String tester_num = request.getParameter("tester_num");
String t_date = request.getParameter("t_date");
String t_time = request.getParameter("t_time");
String sys_type = request.getParameter("sys_type");
String packages = request.getParameter("package");
String sockets = request.getParameter("sockets");
String sockets = request.getParameter("val");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
PreparedStatement ps = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#oradev2.*****.com:1521:RPADB","shift_admin", //
"shift_admin"
);
String sql;
sql = "INSERT INTO fusion_shiftrpt(RECORD_NUM, TESTER_NUM, T_DATE, T_TIME, SYSTEM_TYPE, PACKAGE, SOCKETS,VAL) VALUES (?,?,?,?,?,?,?,?)";
ps = con.prepareStatement(sql);
stmt = con.createStatement();
ps.setString(1, rec_num);
.0+ ps.setString(2, tester_num);
ps.setString(3, t_date);
ps.setString(4, t_time);
ps.setString(5, sys_type);
ps.setString(6, packages);
ps.setString(7, sockets);
ps.setString(8, val);
ps.executeUpdate();
} catch (SQLException e) {
throw new ServletException(e);
} catch (ClassNotFoundException e) {
throw new ServletException(e);
} finally {
try {
if(rs != null)
rs.close();
if(stmt != null)
stmt.close();
if(ps != null)
ps.close();
if(con != null)
con.close();
} catch (SQLException e) {}
}
return(true);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request,response);
//String url = request.getRequestURI();
//System.out.println(url);
}
}
If you insist on staying with this design, I would suggest that you use JSTL. This provides a set of tags for accessing data, controlling logic, and performing SQL access.
See the Sun Tutorial on the Standard Tag Library and the SQL tags. This is a much better approach than embedding scriptlets into your JSP. That said, I would recommend this approach (or scriplets) only be used for prototypes or as a very-temporary fix.
With JSTL, you could replace all of the scriptlets with something similar to:
<sql:query var="rows" >
select * from fus where tester_num like ?
<sql:param value="${param.user_input}" />
</sql:query>
<table>
<c:forEach var="row" items="${rows}">
<tr>
<td>${row.column1name}</td>
<td>${row.column2name}</td>
<td>${row.column3name}</td>
</tr>
</c:forEach>
</table>
You have access to the request in a JSP. So if your JSP were to be accessed like this:
test.jsp?q=userinput
You could get to it like this in the JSP:
request.getParameter('userinput');
You should convert your JSP code to at least use a preparedStatement when you do this:
PreparedStatement ps = connection.prepareStatement("select * from fus where tester_num like ?");
ps.setString(1, "%" + request.getParameter('userinput') + "%");
ResultSet resultSet = ps.executeQuery();
As tvanfosson said, you should remove all database access code from your view logic (JSP). You should just show the info in your JSP, let the Servlet do all the processing. I also strongly recommend you to use an OMR framework like Hibernate.

Categories

Resources