how get and pass values in servlet in java? - java

I have Java code like this,
package my.ebill.pro.db;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import newt.com.properties.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
#WebServlet("/BG_Form")
public class BG_Form extends MyDbConn {
/**
*
*/
private static final long serialVersionUID = -2319984741700546377L;
static Statement st,st1;
public BG_Form() throws Exception {
super();
st=con.createStatement();
st1=con.createStatement();
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String poNumberBas=request.getParameter("poNo");
String fromPoBas=request.getParameter("toAddress");
String toPoBas=request.getParameter("toWhomname");
String[] productsBas = request.getParameterValues("product");
String[] pricesBas= request.getParameterValues("price");
String[] qtysBas= request.getParameterValues("qty");
String[] linetotalsBas = request.getParameterValues("linetotal");
System.out.println("Product"+productsBas);
/*out.println( poNumber + fromPo+toPo+products+prices+qtys+linetotals+"Adress");*/
PoGet poget=new PoGet();
poget.setFromPo(fromPoBas);
poget.setToPo(toPoBas);
poget.setProducts(productsBas);
poget.setPrices(pricesBas);
poget.setPoNumber(poNumberBas);
poget.setQtys(qtysBas);
poget.setLinetotals(linetotalsBas);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
here getter and setter;
public class PoGet {
private String poNumber;
private String fromPo;
private String toPo;
private String[] products;
private String[] prices;
private String[] qtys;
private String[] linetotals;
}
and jsp code is
<html>
<head>
<%#include file="includes/headscript.jsp" %>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
</head>
<body>
<form id="validationform" name="validationform" method="get" action="BG_Form">
<input type="text" style="border-right-width: 2px; margin-right: 0px; margin-left: 33px; margin-top: -15px;" id="F_Date" class="dateRagePicker leftPick1 hasDatepicker" maxlength="20" size="20">
<table class="order-list" style="margin-left: 228px;">
<thead>
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="product"></td>
<td><input type="text" name="price">
</td><td><input type="text" name="qty"></td>
<td><input type="text" readonly="readonly" name="linetotal"></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td style="text-align: center;" colspan="5">
<input type="button" value="Add Product" name="addrow" id="addrow">
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: Rs<span id="grandtotal"></span>
</td>
</tr>
<tr>
<td>
In Words <span id="inworDs" ></span>
</tr>
<tr>
<td>
<input type="submit"/>
</tr>
</tfoot>
</table>
</form>
<script>
$("#addrow").click(function(){
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product"/></td>';
cols += '<td><input type="text" name="price"/></td>';
cols += '<td><input type="text" name="qty"/></td>';
cols += '<td><input type="text" name="linetotal" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="qty"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="qty"]').val();
row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal(f) {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
</script>
</body>
</html>
from jsp i am getting the multiple values String array,
can any one tell me how can i retrive and set the values which i am sending from javascript.
i need to get values has to pass it to database.

String[] productsBas = request.getParameterValues("product");
String[] pricesBas= request.getParameterValues("price");
String[] qtysBas= request.getParameterValues("qty");
for(int i=0;i<productsBas.length;i++){
get values here using
productsBas[i] & pricesBas[i] and qtysBas[i] then save it
}

Related

return both count and list from DAO

I'm writing a web app where I need to return the total number of rows from the Servlet to my JSP.
I'm unable to know how can I send the count attribute to my JSP along with userBeans.
Below is my code.
Servlet
package org.servlet;
import org.DAO.*;
import org.bean.UserBean;
import java.io.IOException;
import java.util.List;
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("/GetData")
public class GetData extends HttpServlet {
private static final long serialVersionUID = 1L;
public GetData() {
super();
}
GetDataDAO getdatadao = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// set content type
try {
getdatadao = new GetDataDAO();
List<UserBean> userBeans = getdatadao.list();
int count = getdatadao.getTheCount();
request.setAttribute("userBeans", userBeans);
request.setAttribute("count", count);
request.getRequestDispatcher("GetCaseData.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JSP:
<div class="status">
<span class="totalTime"></span>
</div>
<input type="Submit" value="Get Case" name="getCase" id="getCase"
disabled="disabled" />
<table>
<tr>
<td>Case Number</td>
<td><input id="caseNumber" name="caseNumber" type="text"
value="${userBeans[0].getCaseNumber()}" /></td>
<td>Case Owner</td>
<td><input id="caseOwner" name="caseOwner" type="text"
value="${userBeans[0].getCaseOwner()}" /></td>
</tr>
I want this count value to be in <span class="totalTime"></span>. Please let me know how can I do this.
I know that this can be done with the below.
<span class="totalTime"><%=request.getAttribute("count")%></span>
But i don't want to include any java code in my JSP, but do it in just the standard MVC way.
Please let me know how can I get this done.
Thanks

setattribute value to be fetch in jsp by getattribute but getting nullpointer

I had tried from servlet set value by setattribute and it have to iterate in jsp by getattribute by setter and getter method without EL and JSTl but am getting this error .kindly help on this i searched in google but i cant found.
java.lang.NullPointerException
org.apache.jsp.Home_jsp._jspService(Home_jsp.java:138)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
here serlvet code
package servlet2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.TreeSet;
import javafx.css.PseudoClass;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import servlet.Dao;
import jdbc.jdbcconnection;
/**
* Servlet implementation class Homepage
*/
//#WebServlet(asyncSupported = true, urlPatterns = { "/Homepage" })
public class Homepage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Homepage() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("inside==========>");
String name=request.getParameter("name");
String password=request.getParameter("password");
String phone=request.getParameter("Phone");
String Deptmart=request.getParameter("Dep");
String gender=request.getParameter("gender");
String country=request.getParameter("country");
Dao d=new Dao();
try
{
jdbcconnection jc=new jdbcconnection();
Connection con=jc.getconnection();
String sql="insert into homepage(name,password,phone,Dept,gender,Country) values(?,?,?,?,?,?)";
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, phone);
ps.setString(4, Deptmart);
ps.setString(5, gender);
ps.setString(6, country);
System.out.println("ps=========>"+ps);
ps.execute();
con.commit();
String select="select * from homepage";
PreparedStatement ps1=con.prepareStatement(select);
ResultSet rs=ps.executeQuery();
ArrayList t=new ArrayList();
while(rs.next())
{
d.setid(rs.getInt(1));
d.setName(rs.getString(2));
d.setPassword(rs.getString(3));
d.setPhone(rs.getInt(4));
d.setDeptmart(rs.getString(5));
d.setGender(rs.getString(6));
d.setCountry(rs.getString(7));
t.add(d);
}
request.setAttribute("users",t);
RequestDispatcher rs1=request.getRequestDispatcher("/Home.jsp");
rs1.forward(request, response);
}
catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Jsp page:
<%#page import="servlet.Dao,java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Homepage" method="get">
<table>
<tr>
<td>Name:</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="text" name="password" id="password"></td>
<tr>
<td>Phone:</td>
<td><input type="text" name="Phone" id="Phone">
</tr>
</td>
<tr>
<td>Department:</td>
<td><select id="Dep" name="Dep">
<option value="it">IT</option>
<option value="finace">Finace</option>
<option value="market">Marketing</option>
</select></td>
</tr>
<tr>
<td>Gender:</td>
<td><input type="radio" name="gender" id="gender" Value="Male">Male
<input type="radio" name="gender" id="gender" Value="Female">Female</td>
</tr>
<tr>
<td>Country:</td>
<td><input type="checkbox" name="country" id="country"
Value="India">India <input type="checkbox" name="country"
id="country" Value="Other">Other</td>
</tr>
<br>
<tr>
<td><input type="submit" name="Add" Value="ADD" ></td>
<td><input type="button" name="Clear" Value="CLEAR"></td>
</tr>
</table>
</form>
<table border="1">
<tr><td>Id</td><td>name</td>
<td>Password</td>
<td>Phone</td>
<td>Deptmart</td>
<td>Gender</td>
<td>country</td>
<td>Edit</td>
<td>Delete</td>
</tr>
<%
try
{
List<Dao> al1 = (List) request.getAttribute("users");
// System.out.println(al1); // prints null
for(Dao user : al1) {
%>
<tr>
<td><%=user.getid() %></td>
<td><%=user.getName() %></td>
<td><%=user.getPassword() %></td>
<td><%=user.getPhone() %></td>
<td><%=user.getDeptmart() %></td>
<td><%=user.getGender() %></td>
<td><%=user.getCountry() %></td>
<td></td>
<td></td>
</tr>
<%} }
catch(Exception e)
{
e.printStackTrace();
}
%>
</table>
</body>
</html>
web.xml
<servlet>
<servlet-name>Homepage</servlet-name>
<servlet-class>servlet2.Homepage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Homepage</servlet-name>
<url-pattern>/Homepage</url-pattern>
</servlet-mapping>

How to uploading multiple csv file into mysql database using jsp and servlet?

I have to upload multiple .csv files,like I have five text boxes and for each text boxe corresponding browse button will be there . When I click on submit button, it has to create table in mysql database with name of text box value, and this table has to updated with .csv file.please can any one suggest me to how to do it.
thank you.
here is my code.
servlet.java:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class CommonsFileUploadServlet1 extends HttpServlet {
private static final String TMP_DIR_PATH=System.getProperty("user.home");
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
tmpDir = new File(TMP_DIR_PATH);
if(!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
}
String realPath =getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
/*
*Set the size threshold, above which content will be stored on disk.
*/
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
/*
* Set the temporary directory to store the uploaded files of size above threshold.
*/
fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
/*
* Parse the request
*/
int check=0;
String name1[]=new String[30];
String name2[]=new String[30];
String name3[]=new String[30];
String filename[]=new String[30];
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
/*
* Handle Form Fields.
*/
if(item.isFormField()) {
if(item.getFieldName().equals("text1"))
{
String name1[i]=item.getString();
}
if(item.getFieldName().equals("text2"))
{
String name2[i]=item.getString();
}
if(item.getFieldName().equals("text3"))
{
String name3[i]=item.getString();
}
if(item.getFieldName().equals("check"))
{
check=Integer.parseInt(item.getString());
}
} else {
//Handle Uploaded files.
String filename[i]=item.getName();
}
i++;
}
request.setAttribute("name1",name1);
request.setAttribute("name2",name2);
request.setAttribute("name3",name3);
request.setAttribute("filename",filename);
if(check==1)
{
RequestDispatcher dispatcher = request.getRequestDispatcher("programmelink.jsp");
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
out.close();
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
programmelink.jsp:
<%#page import="com.hcu.mysql.connection.ConnectionDemo1"%>
<%#include file="dbconnection.jsp"%>
<%#page import="java.sql.*"%>
<%#page import="java.io.OutputStream"%>
<%#page import="java.io.FileOutputStream"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.io.FileInputStream"%>
<%#page import="java.io.File"%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<center>
<table border="2">
<%
String pname[]=(String[])request.getAttribute("name1");
String saveFile[]=(String[])request.getAttribute("filename");
Statement st1=con.createStatement();
Statement st2=con.createStatement();
try
{
int i;
for(i=0;i<pname.length;i++)
{
pname[i]=pname[i].replace('-', '_');
String realPath =getServletContext().getRealPath("/");
File f1 = new File(realPath+saveFile[i]);
File f2 = new File("/var/lib/mysql/dcis_attendance_system/"+saveFile[i]);
InputStream in = new FileInputStream(f1);
OutputStream out1 = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out1.write(buf, 0, len);
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("driver connected");
st1.executeUpdate("create table if not exists "+pname[i]+"_curriculum(subjid varchar(20),subjname varchar(100),credits varchar(20),semister varchar(20),sno INT) ");
String qry2="LOAD DATA INFILE '"+saveFile[i]+"' INTO TABLE "+pname[i]+"_curriculum FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' (subjid,subjname,credits,semister,sno)";
st2.executeUpdate(qry2);
}
out.println("<center><h1>File uploaded sucessfully</h1></center>");
}
catch(Exception e)
{
out.println("<center><h1>File not uploaded sucessfully</h1></center>");
}
%>
</table>
</center>
jsppage.jsp
<form action="servlet" enctype="multipart/form-data" method="POST">
<input type="hidden" name="check" value="7" />
</table>
<table align="center" border="1" id="table1">
<tr>
<td class="heading" align="center">Programme Name</td>
<td class="heading" align="center">Programme Code</td>
<td class="heading" align="center">Browse Curriculum</td>
</tr>
<%int i;
for(i=0;i<2;i++)
{
%>
<tr>
<td><input type="text" name="text1" size="11" value=""> </td>
<td><input type="text" name="text2" size="10" value=""> </td>
<td><input type="file" name="file1" class="multi" id="file"></td>
</tr>
<%}%>
</table>
<table align="center">
<tr>
<td><input type="submit" name="submit" value="submit"></td>
<td><input type="button" name="add" value="Add" onclick="next();"></td>
</tr>
</table>
</form>
I think this will give you idea :D use array for multi uploading rather than using many upload button.
<td><input type="file" name="file[]" class="multi" id="file"></td>

image not retrieving when submitting form using servlet

I have a image in my sql and I want to retrieve it in web page
so i have developed a servlet. now when I hit the submit button then it calls to the servlet but image is not displayed but in the browser if if I am writing localhost:8080/y/testimageServlet then the image is displayed.
imagetestServlet.java
import java.sql.*;
import DB.DataBaseConnection;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class imagetestServlet
*/
#WebServlet("/imagetestServlet")
public class imagetestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public imagetestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException,ServletException {
Blob image = null;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DataBaseConnection db= new DataBaseConnection();
ServletOutputStream out = response.getOutputStream();
try {
Class.forName("com.mysql.jdbc.Driver");
con=db.connet();
stmt = con.createStatement();
rs = stmt.executeQuery("select img from one where id = '4'");
if (rs.next()) {
image = rs.getBlob(1);
} else {
response.setContentType("text/html");
out.println("<font color='red'>image not found for given id</font>");
return;
}
response.setContentType("image/gif");
InputStream in = image.getBinaryStream();
int length = (int) image.length();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
} catch (Exception e) {
response.setContentType("text/html");
out.println("<html><head><title>Unable To Display image</title></head>");
out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
"</font></h4></body></html>");
return;
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
login
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
<img src="header.png"><br><br><br><br><br>
<table >
<tr>
<td>
<table class="table">
<tr>
<td>
<table class="table">
<tr>
<td>
<div class="content"><div class="signin-header"><h3>Welcome to DiaEmr</h3></div></div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div class="signin-box">
<p class="one">
Welcome to all at the <b>"Workshop on Ileal Interposition".</b><br>
<b>Brazil</b> to inaugurate & launch this very important Data Registry<br>
Key features of the solution-<br>
</div>
</div>
</td>
</tr>
</table>
</td>
<td>image</td>
<td>
<table class="table" >
<tr>
<td>
<div class="content">
<div class="signin-header">
<h3>Portal Login</h3>
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="content">
<div align="center" class="signin-box">
<table class="table">
<tr>
<td><b>User ID</b></td>
<td><input name="uid" type="text" /></td>
</tr>
<tr >
<td><b>Password</b></td>
<td><input name="cpass" type="password" /></td>
</tr>
<tr >
<td><input type="submit"
class="button button-submit" value="Submit" /></td>
<td><input type="reset" class="button button-submit"
value="Reset" /></td>
<tr>New UserRegister</tr><br>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div class="footer-bar">
<img align="left" src="footer.png">
</div>
</form>
your form sends a post request,
<form id="f1" name="f1" action="imagetest" method="post" onsubmit="return ccheck()">
but you only define a doGet method in your servlet. This is resulting in your page working if you navigate in a browser (GET) but not when submitting your form (POST).
You will either need to change your form to use get or implement your code in the doPost method

completing read CRUD sql in jsp servlet

I asked this questions last night, and was kind of foolish not to ask how to complete the coding on it. I now have a dropdown box in a JSP populated with some data from an SQL database. I am trying to get the selected data to direct to the final viewing page, but again am running into some difficulty with this.
When I run the program, it either populates the page with all the data from the list database, or will give me an unfriendly error.
My current coding is as such:
the Bean:
package com.login.read;
public class ReadBean {
protected int id;
protected String title;
protected String author;
protected String text;
public int getId(){
return id;
}
public void setId(int newID){
id = newID;
}
public String getTitle(){
return title;
}
public void setTitle(String newTitle){
title = newTitle;
}
public String getAuthor(){
return author;
}
public void setAuthor(String newAuthor){
author = newAuthor;
}
public String getText(){
return text;
}
public void setText(String newText){
text = newText;
}
}
The Controller:
package com.login.read;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet (urlPatterns={"/com/defaultValidate/ReadController"})
public class ReadController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String address;
List<ReadBean> myList = new ArrayList<ReadBean>();
if(request.getParameter("ReadConfirm") != null){
try {
Connection connect = ConnectionManager.getConnection();
String SQL = "SELECT * FROM prayers ORDER BY prayerTitle DESC";
PreparedStatement ps = connect.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();
while(rs.next()){
ReadBean reader = new ReadBean();
reader.setTitle(rs.getString("prayerTitle"));
reader.setAuthor(rs.getString("author"));
reader.setText(rs.getString("text"));
myList.add(reader);
}
request.getSession().setAttribute("ref", myList);
rs.close();
ps.close();
connect.close();
} catch (Exception e) {
}
address = "ReadConfirm.jsp";
} else if(request.getParameter("ReadView") != null){
address = "ReadView.jsp";
} else{
address = null;
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
And my jsp pages that link the drop-down box to the selected material:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<h2 id="contentHeader">Select a prayer</h2>
<form action="ReadController">
<table border="1" width="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="prayer_id">
<c:forEach var="view" items="${ref}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="ReadView" value="View"> </td>
</tr>
</tbody>
</table>
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
and the final viewing page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<c:forEach var="view" items="${res}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
<form action="../Read.jsp">
<p>Click on the return button to return to the main menu</p>
<input type="submit" name="return" value="Return">
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
As always, any and all assistance in this regard is incredibly helpful. I am a relative newbie to the world of jsp and servlets.
If one needs any reference as to the continuation of this sequence, kindly view the previous question I posted regarding dynamically displaying data in a jsp combo-box.
Thank you for your time and help.
By reading above code, I can just ask you that where you have stored your session attribute in variable "var", which is being used in c:foreach loop ?

Categories

Resources