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.
Related
Following is my jsp page, where I am Searching Voucher Period in Oracle table
through servlet :- v_p_Search1.java, Which is working properly, Searched Result
Populating and displaying into ArrayList at jsp page. And I am Selecting a Specific Voucher Period from drop down Select Box. And Storing the Selected Voucher Period through the Following statement :-
type="text" name="voucherperiod" value="<%=request.getParameter("database1")%>"
Later I am searching Branch Code in Oracle table through servlet :- b_c_Search1.java, Which is also working properly, Searched Result Populating and displaying into ArrayList at same jsp page. And I am Selecting Multiple Branch Code from Listbox. And Storing the Selected Multiple Branch Code in another ArrayList through :- ar.add(clrs[i]);
But problem is that, when 2nd dropdown listbox populating in same jsp page,
the previous selected request.getParameter :-
type="text" name="voucherperiod" value="<%=request.getParameter("database1")%>"
is going null.
My requirement is to pass both the Parameter [selected voucher period] and
[selected multiple Branch Code] from branch_voucher.jsp to servlet :- b_c_Detail_Search.java for further Processing.
branch_voucher.jsp
===================
<%# page import="java.util.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<TITLE>VOUCHER PERIOD AND BRANCH CODE SELECTION</TITLE>
</HEAD>
<BODY>
<H1><center><color : blue>VOUCHER PERIOD AND BRANCH CODE SELECTION</center></H1>
<FORM NAME="form1" ACTION="branch_voucher.jsp" METHOD="GET">
<label1> Click To </label1>
<input type="submit" value="Generate Voucher Period List" onclick="form.action='v_p_Search1';">
<label1 for="name">Voucher Period</label1>
<td>
<select name="database1">
<option value="" selected>select</option>
<%
if (request.getAttribute("vpList") != null) {
ArrayList vlist = (ArrayList) request.getAttribute("vpList");
for(int i=0;i<vlist.size();i++) {
String VField=vlist.get(i).toString();
%>
<option value="<%=VField %>"><%=VField %></option>
<%
}
}
%>
</FORM>
</select>
</td>
<label1> And Click To </label1>
<input type="submit" value="Accept">
<table>
<tr>
<td>Voucher Period Selected</td>
<td> :- </td>
<%if(request.getParameter("database1")!=null){ %>
<td><input type="text" name="voucherperiod" value="<%=request.getParameter("database1")%>"></input>
<%}
%>
</td>
</tr>
</table>
<FORM NAME="form1" ACTION="branch_voucher.jsp" METHOD="GET">
<br />
<br />
<label1> Click To </label1>
<input type="submit" value="Generate Branch Code List" onclick="form.action='b_c_Search1';">
<br />
<label1 for="name">Branch Code List</label1>
<table border="1">
<tr><td></td>
<br />
</tr>
<select name="fstname" multiple size="10">
<%
if (request.getAttribute("BCList") != null) {
ArrayList list = (ArrayList) request.getAttribute("BCList");
for(int i=0;i<list.size();i++) {
String Field=list.get(i).toString();
int p=0;
%>
<option value="<%=Field %>"><%=Field %> </option>
<%
p++;
}
}
%>
</FORM>
<br />
<br />
<br />
</select>
<br>
<label1> And Click To </label1>
<input type="submit" value="Accept"><br/>
<%
String clrs[] = request.getParameterValues("fstname");
ArrayList ar=new ArrayList();
if(clrs != null){
%>
<p><b>You have selected the following Branchs</b></p>
<%
for(int i=0; i<clrs.length; i++){
ar.add(clrs[i]);
%>
<li><%=clrs[i]%></li>
<%
}
%>
<%
}
session.setAttribute("ARlistName",ar);
%>
<FORM NAME="form1" ACTION="branch_voucher.jsp" METHOD="POST">
<input type="submit" value="Search Branch Code Detail" onclick="form.action='b_c_Detail_Search';">
<%
%>
</FORM>
</BODY>
</HTML>
b_c_Detail_Search.java
======================
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.PrintWriter;
import java.io.IOException;
import java.sql.*;
import oracle.jdbc.driver.*;
import oracle.sql.*;
import oracle.jdbc.driver.OracleDriver;
import java.util.ArrayList;
import java.util.List;
public class b_c_Detail_Search extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter pwinsert = response.getWriter();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String Field_br_cd = " ";
String kk = " ";
String Field_br_nm = " ";
String v_p_Field=" ";
String v_p_Field_a = request.getParameter("voucherperiod");
ArrayList ar=ArrayList)request.getSession().getAttribute("ARlistName");
String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
"</body></html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Voucher Period Selected</title>");
out.println("</head>");
int b = 2;
out.println("<center><table border="+b+ "> ");
out.println("<tr>");
out.println("<td>"+ v_p_Field_a +"</td>");
out.println("</tr>");
out.println("<html>");
out.println("<head>");
out.println("<title>List Of Branch Code Selected</title>");
out.println("</head>");
int a = 2;
out.println("<center><table border="+a+ "> ");
out.println("<tr>");
for(int i=0;i<ar.size();i++) {
String Field=ar.get(i).toString();
Field_br_cd = Field.substring(0, 5);
out.println("<td>"+ Field_br_cd +"</td>");
Field_br_nm = " ";
kk = " ";
for (int j=7;j<Field.length();j++)
{
char k = Field.charAt(j);
kk = kk + Character.toString(k);
Field_br_nm=kk;
}
out.println("<td>"+ Field_br_nm +"</td>");
out.println("</tr>");
}
}
}
People, I am having a problem in my HTML form validation. Currently I am using JSP (at the back end) to extract the form data and jquery to validate the data in my HTML file. Problem is that when i run my HTML on server (apache tomcat), my jquery validation snippet doesn't work and data simply gets passed to the JSP file. Only if I remove the action attribute from form tag then the validation code runs but JSP doesn't get called. Here are my HTML and JSP scripts.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,javax.mail.*"%>
<%# page import="javax.mail.internet.*,javax.activation.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# page import = "java.util.regex.Pattern,java.util.regex.Matcher,java.util.regex.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Yay!</title>
</head>
<body>
<%
//-------------->
String first = request.getParameter("firstname");
String last = request.getParameter("lastname");
String Username = request.getParameter("username");
String Email = request.getParameter("email");
String day = request.getParameter("date");
String month = request.getParameter("month");
String year = request.getParameter("year");
String pass1 = request.getParameter("password");
String pass2 = request.getParameter("confirmpassword");
String date = day + '/'+ month + '/' + year ;
%>
<%= first %><br>
<%= last %><br>
<%= Username %> <br>
<%= Email%> <br>
<%= date%> <br>
<%= pass1%> <br>
<%= pass2%> <br>
</body>
</html>
<!-- HTML file-->
<form class = ".form-inline"
method = "POST" action = "process.jsp"
onSubmit="return validate(this);" name="form" >
<lable><b>Name:</b></lable>
<input type = "text" placeholder = "first"
id = "firstname"
name = "firstname"></input>
<input type = "text" placeholder = "last"
id = "lastname"
name = "lastname"></input><br><br>
<label>Birthday:</label>
<div class = "date">
<input type = "text" placeholder = "dd"
id = "date" name = "date"></input>
<input type = "text" placeholder = "mm"
id = "month" name = "month"></input>
<input type = "text" placeholder = "yy"
id = "year" name="year"></input>
<br><br>
</div>
<div class="form-group ">
<label><b>User Name:</b></label>
<input type = "text"
class = "form-control"
id = "username" name="username"></input>
<br>
<label for="password">Password:</label>
<input type="password"
class="form-control"
id="password" name = "password">
<br>
<label for="confirmpassword">
Confirm Password:</label>
<input type="password"
class="form-control"
id="confirmpassword" name = "confirmpassword">
<label for="email">Email:</label>
<input type="email"
class="form-control" id="email" name ="email">
<br>
<button type="submit"
class="btn btn-primary btn-block"
id = "submission"
value ="submit">Submit</button>
<script type="text/javascript">
/*global $*/
$(function(){ // JS form validation snippet.
// variables are used to
store different types of
regex expressions.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email
= /^([\w-]+ (?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-] {0,66})
\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
var ck_username =
/^[A-Za-z0-9_] {1,20}$/;
var ck_password =
/^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
var flag;
$("#submission").on("click",
function validate(form){
var day = $("#date").val();
var month = $("#month").val();
var year = $("#year").val();
if ((day >= 1 && day <= 31 ) &&
(month >= 1 && month <= 12) &&
(year >= 1930)) {
//alert("correct date ");
}
else {
//alert("wrong date");
}
//alert("submission active");
// variable extracts
the specific user input from the form.
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
var confirmpassword = $("#confirmpassword").val();
var errors = [];
if (!ck_name.test(firstname)) {
errors[errors.length] = "Your valid first Name .";
}
if (!ck_name.test(lastname)) {
errors[errors.length] = "Your valid last Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] =
"Yor must enter a valid email address.";
}
if(!ck_username.test(username)) {
errors[errors.length] =
"Your valid UserName no special char .";
}
if (!ck_password.test(password) ) {
errors[errors.length] =
"Your must enter a valid Password ";
}
if (!ck_password.test(confirmpassword) ||
password !== confirmpassword) {
errors[errors.length] = "password doesn't match ";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
//$.get("process.jsp", [firstname, lastname, email, username,
password, confirmpassword, day, month, year]);
//alert(".get() executed");
return true;
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
//alert(msg);
}
});
});
</script>
</div>
</form>
there is a syntax error in your javascript please check your code properly
if i remove all your javscript code then i am able to do validation.
check my code you will get an idea.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,javax.mail.*"%>
<%# page import="javax.mail.internet.*,javax.activation.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# page import = "java.util.regex.Pattern,java.util.regex.Matcher,java.util.regex.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Yay!</title>
</head>
<body>
<%
//if(request.getParameter("btnsubmit")!=null){
//-------------->
String first = request.getParameter("firstname");
String last = request.getParameter("lastname");
String Username = request.getParameter("username");
String Email = request.getParameter("email");
String day = request.getParameter("date");
String month = request.getParameter("month");
String year = request.getParameter("year");
String pass1 = request.getParameter("password");
String pass2 = request.getParameter("confirmpassword");
String date = day + '/'+ month + '/' + year ;
// }
%>
<%= first %><br>
<%= last %><br>
<%= Username %> <br>
<%= Email%> <br>
<%= date%> <br>
<%= pass1%> <br>
<%= pass2%> <br>
</body>
</html>
<!-- HTML file-->
<script type="text/javascript">
function validate(form) {
alert('hi');
}
</script>
<form class = ".form-inline"
method = "POST" action ="index.jsp"
onSubmit="return validate(this);" name="form" >
<lable><b>Name:</b></lable>
<input type = "text" placeholder = "first"
id = "firstname"
name = "firstname"></input>
<input type = "text" placeholder = "last"
id = "lastname"
name = "lastname"></input><br><br>
<label>Birthday:</label>
<div class = "date">
<input type = "text" placeholder = "dd"
id = "date" name = "date"></input>
<input type = "text" placeholder = "mm"
id = "month" name = "month"></input>
<input type = "text" placeholder = "yy"
id = "year" name="year"></input>
<br><br>
</div>
<div class="form-group ">
<label><b>User Name:</b></label>
<input type = "text"
class = "form-control"
id = "username" name="username"></input>
<br>
<label for="password">Password:</label>
<input type="password"
class="form-control"
id="password" name = "password">
<br>
<label for="confirmpassword">
Confirm Password:</label>
<input type="password"
class="form-control"
id="confirmpassword" name = "confirmpassword">
<label for="email">Email:</label>
<input type="email"
class="form-control" id="email" name ="email">
<br>
<button type="submit"
class="btn btn-primary btn-block"
id = "submission"
value ="submit" name='btnsubmit'>Submit</button>
</div>
</form>
<%# 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>");
}
%>
In this portion of the code:
try {
connection = DriverManager.getConnection(
connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT text_pub, path_photo FROM publication,publier, consomateur WHERE publication.id_publication=publier.publication_id_publication AND publier.users_id_user=consomateur.code_bar AND consomateur.code_bar = "+idUser+" AND 'path_photo' IS NOT NULL AND 'text_pub' IS NOT NULL";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130"></td>
<%}
%>
I'm trying to select two values from my table, some of the values can be null, for example I can have a value for my column text_pub and not have a value in my column path_photo and vice versa, so in case I have text_pub and don't have path_photo, I want to display only the text_pub, but the probleme is that the value of text_pub is displayed but also the value of path_photo which is null.
PS: I know that treatements like these are better done in servlets, but I really want to make it work in a jsp. Thank you.
Either add a IFNULL check to the sql query:
SELECT IFNULL(text_pub,DEFAULT("")), IFNULL(path_photo,DEFAULT("")) FROM publication,publier,...
or add a check for the return value of resultSet.getString(..)
String text = resultSet.getString("text_pub");
if (text==null) {
text = "";
}
Edit:
in case I have text_pub and don't have path_photo, I want to display
only the text_pub this answer doesn't cover this
<%
while (resultSet.next()) {
String pub = resultSet.getString("text_pub");
if (pub==null) {
pub = "";
}
String photo = resultSet.getString("path_photo");
%>
<tr bgcolor="#8FBC8F">
<td><%= pub %></td>
<%
if (photo!=null) {
%>
<td><img src="images/<%=photo%>" width="150" height="130"></td>
<%
}
}
%>
I know that treatements like these are better done in servlets, but I really want to make it work in a jsp.
You're wrong here. This kind of things are handled in JSP, not in servlet, since logic to present the contents in the view belongs to the View (JSP) and not to the Controller (Servlet). Since you're using scriptlets, you should use an if sentence to validate if you should display the image or not:
while (resultSet.next()) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<td>
<%
if (resultSet.getString("path_photo") != null) {
%>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130">
<%
}
%>
</td>
</tr>
<%
}
%>
If you don't want to display anything if resultSet.getString("text_pub") is null:
while (resultSet.next()) {
if (resultSet.getString("text_pub") != null) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<td>
<%
if (resultSet.getString("path_photo") != null) {
%>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130">
<%
}
%>
</td>
</tr>
<%
}
}
%>
If you happen to write the code in the right way and use a Servlet to handle the data retrieval from database, fill the data in a List<SomeEntity>, add this list into a request attribute (probably with name "photoList") and forward to the desired JSP, then you could use JSTL to control the flow of the image display:
<c:forEach items="${photoList}" var="photo">
<tr bgcolor="#8FBC8F">
<td>${photo.textPub}</td>
<td>
<c:if test="${not empty photo.pathPhoto}">
<img src="images/${photo.pathPhoto}" width="150" height="130">
</c:if>
</td>
</tr>
</c:forEach>
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.