Display select List through iteration - java

<%# page import="java.sql.*" %>
<%# page import="javax.sql.*" %>
<%# page import="java.util.*" %>
<%
Connection con =null;
PreparedStatement pstmt=null;
List<String> list=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "xyz", "abc");
String strQuery = "SELECT batch_id,course_name FROM t_students_batch";
pstmt = con.prepareStatement(strQuery);
rs = pstmt.executeQuery();
list = new ArrayList<String>();
while(rs.next()) {
list.add(rs.getString("batch_id"));
list.add(rs.getString("course_name"));
}
}catch(Exception e) {
System.out.println("Error:: "+e.getMessage());
}
%>
<html>
<head>
<title>pay</title>
</head>
<body>
<form action="payment.jsp" method="get">
BatchId ::<select name="batchid">
<%
for (String temp : list) {
// how to i get this..
out.println("<option>"+ temp +"</option>");
}
%>
<input type="submit" value="continue" action="payment.jsp" />
</select>
</form>
</body>
</html>
output :::
1 java
2 jsp
Total column values are displaying like this
When I click the "1" it's working...
When I click the java or jsp, it will show me a null pointer exception..
I want to take the java value 1 display as it is the logic..

Try this one.
<%
for (int i = 0; i < list.size(); i = i+2) {
out.println("<option value='"+list.get(i) +"'>"+ list.get(i+1) +"</option>");
}
%>

missing value attr , now it should submit value.
<%
for (String temp : list) {
// how to i get this..
out.println("<option value='"+temp +"'>"+ temp +"</option>");
}
%>

Related

Exception Occured java.lang.NumberFormatException: null

I am getting following error in JSP page
SELECT * FROM books WHERE id =1001
Exception Occuredjava.lang.NumberFormatException: null
while running below code.
I doubt this is due to
input type='text' size='3' value='1' name='qty'<%=id% in JSearch.jsp is not properly linked to
int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id)); in JOrder.jsp.
Can any one please help me on this.
Code: JSearch.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>Search Page</title>
</head>
<body>
<% try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#//XXXXX.XXX:1521/xe", "sai", "harisai");
Statement stmt=conn.createStatement();
// Retrieve and process request parameters: "author" and "search"
String author = request.getParameter("author");
boolean hasAuthorParam = author != null && !author.equals("Select...");
String searchWord = request.getParameter("search");
boolean hasSearchParam = searchWord != null && ((searchWord = searchWord.trim()).length() > 0);%>
<h2>Query Results</h2>
<%if (!hasAuthorParam && !hasSearchParam) { %> <%--No params present--%>
<h3>Please select an author or enter a search term!</h3>
<p><a href='Entryscreen.jsp'>Back to Select Menu</a></p>
<% }
else {
// Form a SQL command based on the param(s) present
StringBuilder sqlStr = new StringBuilder(); // more efficient than String
sqlStr.append("SELECT * FROM books WHERE qty > 0 AND (");
if (hasAuthorParam) {
sqlStr.append("author = '").append(author).append("'");
}
if (hasSearchParam) {
if (hasAuthorParam) {
sqlStr.append(" OR ");
}
sqlStr.append("author LIKE '%").append(searchWord)
.append("%' OR title LIKE '%").append(searchWord).append("%'");
sqlStr.append(") ORDER BY author, title");
}//
out.println(sqlStr); // for debugging
ResultSet rset = stmt.executeQuery(sqlStr.toString());
if (!rset.next()) { %> <%--// Check for empty ResultSet (no book found)--%>
<h3>No book found. Please try again!</h3>
<p><a href='start'>Back to Select Menu</a></p>
<%}
else {%>
<%--// Print the result in an HTML form inside a table--%>
<form method='get' action='JOrder.jsp'>
<table border='1' cellpadding='6'>
<tr>
<th> </th>
<th>AUTHOR</th>
<th>TITLE</th>
<th>PRICE</th>
<th>QTY</th>
</tr>
<%-- // ResultSet's cursor now pointing at first row--%>
<% do {
// Print each row with a checkbox identified by book's id
String id = rset.getString("id");%>
<tr>
<td><input type='checkbox' name='id' value='<%=id%>' /></td>
<td><%=rset.getString("author")%></td>
<td><%=rset.getString("title")%></td>
<td>$<%=rset.getString("price")%></td>
<td><input type='text' size='3' value='1' name='qty'<%=id%>/></td>
</tr>
<%} while (rset.next()); %>
</table><br/>
<%--// Ask for name, email and phone using text fields (arranged in a table)--%>
<table>
<tr><td>Enter your Name:</td>
<td><input type='text' name='cust_name'/></td></tr>
<tr><td>Enter your Email (user#host):</td>
<td><input type='text' name='cust_email' /></td></tr>
<tr><td>Enter your Phone Number (8-digit):</td>
<td><input type='text' name='cust_phone' /></td></tr></table><br />
<%-- // Submit and reset buttons--%>
<input type='submit' value='ORDER' />
<input type='reset' value='CLEAR' /></form>
<%
}
}
}
catch (Exception e){
out.println("Exception Occured:" +e);
} %>
</body>
</html>
Code:
JOrder.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>Order Confirmation</title>
</head>
<body>
<h1>Order Confirmation</h1>
<% try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#//XXXXX.XXX.LOCAL:1521/xe", "sai", "harisai");
Statement stmt=conn.createStatement();
// Retrieve and process request parameters: id(s), cust_name, cust_email, cust_phone
String[] ids = request.getParameterValues("id"); // Possibly more than one values
String custName = request.getParameter("cust_name");
boolean hasCustName = custName != null && ((custName = custName.trim()).length() > 0);
String custEmail = request.getParameter("cust_email").trim();
boolean hasCustEmail = custEmail != null && ((custEmail = custEmail.trim()).length() > 0);
String custPhone = request.getParameter("cust_phone").trim();
boolean hasCustPhone = custPhone != null && ((custPhone = custPhone.trim()).length() > 0);
// Validate inputs
if (ids == null || ids.length == 0) {%>
<h3>Please Select a Book!</h3>
<% } else if (!hasCustName) {%>
<h3>Please Enter Your Name!</h3>
<% } else if (!hasCustEmail || (custEmail.indexOf('#') == -1)) {%>
<h3>Please Enter Your e-mail (user#host)!</h3>
<%} else if (!hasCustPhone || (custPhone.length() != 8)) {%>
<h3>Please Enter an 8-digit Phone Number!</h3>
<%} else {%>
<%--// Display the name, email and phone (arranged in a table)--%>
<table>
<tr><td>Customer Name:</td><td><%=custName%></td></tr>
<tr><td>Customer Email:</td><td><%=custEmail%></td></tr>
<tr><td>Customer Phone Number:</td><td><%=custPhone%></td></tr></table>
<%--// Print the book(s) ordered in a table--%>
<br/>
<table border='1' cellpadding='6'>
<tr><th>AUTHOR</th><th>TITLE</th><th>PRICE</th><th>QTY</th></tr>
<% float totalPrice = 0f;
for(String id : ids) {
String sqlStr = "SELECT * FROM books WHERE id ="+ id;
out.println(sqlStr);
// for debugging
ResultSet rset = stmt.executeQuery(sqlStr);
rset.next();
int qtyAvailable = rset.getInt("qty");
String title = rset.getString("title");
String author = rset.getString("author");
float price = rset.getFloat("price");
int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id));
sqlStr = "UPDATE books SET qty = qty -"+ qtyOrdered +" WHERE id =" + id;
out.println(sqlStr); // for debugging
stmt.executeUpdate(sqlStr);
sqlStr = "INSERT INTO ORDER_RECORDS VALUES ("+ id + ", " + qtyOrdered + ", '" + custName + "', '"
+ custEmail + "', '" + custPhone + "')";
out.println(sqlStr); // for debugging
stmt.executeUpdate(sqlStr);%>
<%-- // Display this book ordered--%>
<tr>
<td><%=author%></td>
<td><%=title%></td>
<td><%=price%></td>
<td><%=qtyOrdered%></td></tr>
<% totalPrice += price * qtyOrdered;
}%>
<tr><td colspan='4' align='right'>Total Price: $
</td> <%out.println(totalPrice);%> </tr>
</table>
<h3>Thank you.</h3>
<%out.println("<p><a href='JEntryScreen.jsp'>Back to Select Menu</a></p>");
}
}
catch (Exception e) {
out.println("Exception Occured" +e);
}
finally {
}%>
</body>
</html>
What is a NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
-[Documentation][2]
NumberFormatException extends IllegalArgumentException. It tells us that it's more specialized IllegalArgumentException. Indeed, it's used for highlighting that although, the argument type was correct (String) the content of the String wasn't numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).
Ad. 2.
When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It's available [here][3].
The description of solving unexpected nulls is well described in a topic [What is a NullPointerException and how can I fix it?][4].
The answer is taken from this topic - I couldn't mark it as a duplicate because I have raised another flag before the question was edited.

JSP code to generate excel sheet of data retrieved in jsp page

I want to export data to Excel sheet
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#include file="connection.jsp" %>
<!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>
<%
String ht = (String)session.getAttribute("ht");
%>
<table border="1">
<%
pst = con.prepareStatement("select * from attendance where ht='"+ht+"'");
res = pst.executeQuery();
if(res.next())
{
String uname = res.getString(2);
%>
<b>Student Name:<%=uname%></b>
<%
String hlt = res.getString(1);
%>
<b>Hallticket:<%=hlt%></b>
<tr><th>CG</th><th>CD</th><th>MPI</th><th>HCI</th><th>WT</th><th>MPI-Lab</th><th>CT=Lab</th><th>WT-Lab</th></tr>
<%
String cg = res.getString(3);
String cd = res.getString(4);
String mpi = res.getString(5);
String hci = res.getString(6);
String wt = res.getString(7);
String mpi_lab = res.getString(8);
String ct_lab = res.getString(9);
String wt_lab = res.getString(10);
%>
<tr>
<td align="center"><%=cg%></td>
<td align="center"><%=cd%></td>
<td align="center"><%=mpi%></td>
<td align="center"><%=hci%></td>
<td align="center"><%=wt%></td>
<td align="center"><%=mpi_lab%></td>
<td align="center"><%=ct_lab%></td>
<td align="center"><%=wt_lab%></td>
</tr>
<br/><br/>
<%
}
%>
</table>
</body>
</html>
I want the data that is retrieved from database and displayed in table should be printed on excel sheet
Please can any one tell me how to do it ... :(
I used mysql databse.
Try using a servlet to do the Excel writing.
You could use it as a JSP:Include in your existing page if you wanted
to.
From the servlet you'll have to do something like this:
ServletOutputStream out = resp.getOutputStream();
resp.setContentType("application/vnd.ms-excel")
/*
* get data
*/
if (data != null) {
for (int i=0; i data.length; i++) {
String dataRow = "";
for (int j = 0; j data[0].length; j++) {
dataRow += data[i][j] + "\t";// add tab delimiter
}
out.println(dataRow);// print data
}
} else {//Bad data...
out.println("No data to report.");
}
out.flush();
Hope it helps you. :)
You must add following lines to your jsp page which you want to export to excel:
response.setContentType("application/xls");
response.setHeader("Content-Disposition", "attachment;filename=File.xls");
Or you must learn about POI
And you must change if(res.next()) with while(res.next())

Java Login JSP Page (Uses Access Database)

I have a Java login application that works and uses a microsoft access database to validate login details. I'm currently in the process of building a java web application and I'm just trying to implement code from my working example.
My problem is that I have 2 input fields here for username and password, (called "name" and "password") But my SQL code which works in the previous example cannot detect the fields on this page called name and password, where the user would input their details respectively.
Any help would be much appreciated!
<%#page import="javax.swing.JOptionPane"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.DriverManager"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Angels & Demons</title>
Home Page
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><center>Login</center></h1>
<center><form action="login.jsp">
<h2>Please make sure to fill all fields! </h2>
<table>
<tr><td>User:<input name="name" type="text" size="10"></td></tr>
<tr><td>Password:<input name="password" size="10"></td></tr>
<td><input type="submit" value="Submit"></input></td>
</table>
</center>
<%
if ((request.getParameter("name") != null )
&& (request.getParameter("password") != null )
)
{
Connection conn = null;
Statement st = null;
ResultSet rs;
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
conn = DriverManager.getConnection(db);
st = conn.createStatement();
String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+password+"'";
rs = st.executeQuery(sql);
int count = 0;
while(rs.next())
{
count = count + 1;
}
if(count == 1)
{
JOptionPane.showMessageDialog(null,"User found, Access Granted!");
}
else if(count > 1){
JOptionPane.showMessageDialog(null,"Duplicte User, Access Denied");
}
else{
JOptionPane.showMessageDialog(null,"User not found");
}
}
catch(Exception ex)
{
}
}
%>
There was Problem in Login.
<%
%>
}
</form>
</body>
</html>
There are two problems in your code..
1) You want your java code to be executed on button click..so you should check for button click and then write code within it as:
<input type="submit" value="Submit" name="bt"></input></td> //Define a name for button
<%
if(request.getParameter("bt")!=null)
{
if ((request.getParameter("name") != null )
&& (request.getParameter("password") != null ))
{
//your code
}
}
%>
2) You have not stored your username and password in any variable and still accessing them in your query by using the name of your text field which is wrong..Save them in a variable and use that variable in the query as :
String name= request.getParameter("name");
String pass= request.getParameter("password");
String sql = "select user,pass from AngelsAndDemons where user = '"+name+"'and pass = '"+pass+"'";
Do not concatenate Strings. Used PreparedStatements to avoid SQL injection.
Also avoid storing passwords on String variables. Use char[] when possible, and wipe it after using it, to avoid leaving a cleartext password on memory.
Congrats on trying web server development.
First a corrected version.
<%#page contentType="text/html" pageEncoding="UTF-8"
import="java.sql.*"
import="javax.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Angels & Demons</title>
Home Page
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1><center>Login</center></h1>
<%
String name = request.getParameter("name");
String password = request.getParameter("password");
if (name == null || password == null) {
%>
<center>
<form action="login.jsp" method="POST">
<h2>Please make sure to fill all fields! </h2>
<table>
<tr><td>User:<input name="name" type="text" size="10"></td></tr>
<tr><td>Password:<input name="password" size="10"></td></tr>
<td><input type="submit" value="Submit"></input></td>
</table>
</center>
</form>
<%
} else {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:AngelsAndDemons";
try (Connection conn = DriverManager.getConnection(db)) {
String sql = "select count(*) from AngelsAndDemons where user = ? and pass = ?";
try (PreparedStatement st = conn.prepareStatement(sql)) {
st.setString(1, user);
st.setString(2, password);
try (ResultSet rs = st.executeQuery()) {
int count = 0;
if (rs.next()) {
count = rs.getInt(1);
}
if(count == 1) {
%><h2>User found, Access Granted!</2><&
} else if(count > 1) {
%><h2>Duplicate User, Access Denied</2><&
} else {
%><h2>Duplicate User, Access Denied</2><&
}
}
}
} catch (Exception ex) {
%><h2>There was Problem in Login.</2>
<p><%= ex.getMessage() %></p>
<&
}
}
%>
</body>
</html>
With the imports I was a bit lazy and used * - which is bad style.
The page is delivered on a browser request (HTTP GET) back to the browser, the client.
No parameters were in the request, so the form is output.
After the form is submitted by the browser, here as HTTP POST request,
there are parameters.
Now a database query can be done.
Try-with-resources ensure that all is closed (connection, prepared statement and result set). Even on return/break/exception.
A PreparedStatement takes care of escaping (say a Name with an apostrophe in it). And most important prevents hacking, SQL injection (=creating evil SQL). Like a name admin and password xxx' OR 1=1.
Access was in my time not a multiuser database. You might use a Derby or H2 database.
JOptionPane does not work in an HTML page delivered, or even on creating the page on the server. The alternatives is writing on the result page.
You picked a hard topic with many features. Good luck.
As JSPs get soon ugly, unreadable, try servlets, maybe in combinations, pure servlet for coding and delivering results in a JSP page.

passing the value of an array to a method in javascript

I have to create an HTML table in which I will have images to display. further I want to pass this path to the next servlet page. for this I have created a separate method in javascript. Now the problem is this, whenever I click on any image it passes the same path everytime. please give me any solutions for this problem or tell me any alternate of passing the path to next page.
my code is--->
<%#page import = "java.util.*" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<link href="Style.css" rel="stylesheet" type="text/css"/>
<title>Home</title>
</head>
<body>
<center>
<h3>${requestScope.payment}</h3>
<jsp:include page="Header.jsp"/>
<jsp:include page="Menu2.jsp"></jsp:include>
<form method="post" action="ProductFeatures" id="myform">
<table border="1" bordercolor="green" bgcolor="yellow" align="center" id="store" >
</table>
</form>
<%
ArrayList<String> l = null;
if(request.getAttribute("list") instanceof ArrayList<?>){
l = (ArrayList<String>)request.getAttribute("list");
}
%>
<script type="text/javascript">
window.onload = function(){
var path = new Array();
var imagepath = new Array();
var table = document.getElementById("store");
var j=0;
var k=0;
var row = null;
<%for(int i=0;i<l.size();i++) {%>
path.push("<%=l.get(i)%>");
<%}%>
for(i=0;i<path.length;i++){
imagepath[i] =path[i].replace ("F:java_projectsApplication4images","F:\\java_projects\\Application4\\images\\");
}
for(i=0;i<path.length;i++){
if(i%4==0){
row = table.insertRow(j);
k=0;
j++;
}
var data = imagepath[i];
var cell = row.insertCell(k);
var image = document.createElement("img");
image.setAttribute("src",imagepath[i]);
image.setAttribute("height","160");
image.setAttribute("width","120");
image.setAttribute("onclick",function(){getDetails(data);});
cell.appendChild(image);
row.appendChild(cell);
k++;
}
};
function getDetails(imagepath){
document.write(imagepath);
if(path.length>10){
var form = document.getElementById("myform");
var input = document.createElement("input");
input.type="hidden";
input.value=imagepath;
input.name="imagepath";
form.appendChild(input);
form.submit();
}
}
</script>
<jsp:include page="Footer.jsp"/>
</center>
</body>
</html>
Here in this code in function getDetails variable imagepath always contains the same value. please somebody tell me wheres the bug in this code. I am not getting it properly.
Change the following line:
image.setAttribute("onclick",function(){getDetails(data);});
into:
image.setAttribute("onclick",(function(d){return function(){getDetails(d);}}(data));
Also, the line:
row.appendChild(cell);
is redondant because the cell was inserted with row.insertCell(k)

Jquery Autocomplete not passing values to java

I've created autocomplete with Jquery UI library and try to get the text box value in java, but not getting the value instead of getting null value. Please help to get value from text box. This is the line String query = (String)request.getParameter("country"); not getting values ?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
input {
font-size: 120%; }
</style>
</head>
<body>
<h3>Feature</h3>
<input type="text" id="country" name="country"/>
<script>
//$("#country").autocomplete("getdata.jsp");
$("#country").autocomplete({
source: "getdata.jsp",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
</script>
</body>
</html>
getdata.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
String query = (String)request.getParameter("country");
System.out.println("query"+query);
try{
String s[]=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =DriverManager.getConnection("XXXXX");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select name from table1 where name like '"+query+"%'");
List li = new ArrayList();
while(rs.next())
{
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while(it.hasNext())
{
String p = (String)it.next();
str[i] = p;
i++;
}
//jQuery related start
int cnt=1;
for(int j=0;j<str.length;j++)
{
if(str[j].toUpperCase().startsWith(query.toUpperCase()))
{
out.print(str[j]+"\n");
if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
break;
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
%>
it's not a form,so don't get the value use getParameter().
source: "getdata.jsp?country="+$("#country").val(),

Categories