java.lang.NumberFormatException: null - java

I have created a login form which contains validations for each field. When i click on submit button function validation() will be invoked to validate all the fields and after successful validation it will redirect to another jsp page where all the details will be inserted in to the Oracle database.
But I'm getting "org.apache.jasper.JasperException: java.lang.NumberFormatException: null" exception. Also "The server encountered an internal error () that prevented it from fulfilling this request" error. I hope you will help me.
Here is the code:
<html>
<head>
<script type="text/javascript">
function validate()
{
if(document.frm.username.value=="")
{
alert("Please enter Username");
document.frm.username.focus();
}
else if(document.frm.mobile.value=="")
{
alert("Please Enter your contact number");
document.frm.mobile.focus();
}
else
{
window.location = "insert.jsp";
}
}
</script>
</head>
<body>
<form name="frm">
<table>
<tr><td>User Name:</td><td><input type="text" name="username"></td></tr>
<tr><td>Contact Number:</td><td><input type="text" name="mobile"></td></tr>
<tr><td><input type="submit" value="Submit" onclick="validate()"></td><td></td></tr>
</table>
</form>
</body>
insert.jsp:
<body>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
Connection con=null;
int mobile=Integer.parseInt(request.getParameter("mobile"));
String username=request.getParameter("username");
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","manager");
Statement st=con.createStatement();
st.executeUpdate("insert into stud values("+mobile+",'"+username+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
}
%>
</body>

You're redirecting the browser to do a GET on insert.jsp, but you're not supplying the request parameters to that new URL. Thus, your JSP fetches the mobile request parameter, which is null, and then tries to parse that to an integer, yielding the NumberFormatException.
What you could do is append the request parameters to the URL, like so:
window.location = "insert.jsp?mobile=" + document.frm.mobile.value + "&username=" + document.frm.username.value;
But it would be even better to submit those values in a POST request, instead of a GET. I think you could achieve that by adding a action="insert.jsp" attribute to the form tag, changing the onClick attribute to onSubmit and removing the
else {
window.location = "insert.jsp";
}
because that would allow the browser to resume its normal form submission. If you combine that with an return false; statement after focussing on the empty fields, you'll prevent the browser from submitting the form.

So what will happen if your mobile number is blank ?
int mobile=Integer.parseInt(request.getParameter("mobile"));
You're asking Integer.parseInt() to parse an empty or null string and that's causing your problem.
From the doc:
Throws:
NumberFormatException - if the string does not contain a parsable integer.
You need to check that mobile is populated and.or handle the scenario when it's not.
I wouldn't use an Integer to store a mobile number, btw. The number of digits could cause an overflow and/or you may want to maintain structure (e.g. country code and the number) etc.

If you are using parseInt(), you should catch an exception somewhere:
int mobile;
try {
mobile = Integer.parseInt(request.getParameter("mobile"));
} catch (NumberFormatException e) {
// do something
}
In your case, request.getParameter("mobile") is probably returning null.
Edit: as nother already noted - storing phone number in an integer may not be a good idea. Try Long instead.

First, your code is very dangerous. You should check null or empty on the server side! Using PreparedStatement instead of Statement.
Second, the code window.location = "insert.jsp"; will not work as your expectation.
Use action="insert.jsp" to make data send to that page. Then, on your js function, return false if it does not pass the condition, otherwise, return true;
Using onSubmit="return validate()" instead of onClick event.

Related

How to check JSP variable and hide if value is null/empty or some specific string?

I am creating a project where i am getting set data in JSP page from database.
if any field data value is null the jsp page is showing null but i do not want to show it on jsp page. please help. i am getting data from bean.
<%=p.getOffer()%>
<% String s = p.getOffer() %>
<% if (<%=s ==null) { %>
show nothing
If you are coding java inside a jsp, you need to use scriptlet tags(<% and %>). So if you are checking for conditions you need to open a scriptlet tag.
<%
String s = p.getOffer();
if (s != null && !s.equals("")) {
out.print(s);
} else { %>
<!-- s is either null or empty. Show nothing -->
<% }%>
What exactly do you want to show when the value is null? Anyway, your approach looks good:
<%=p.getOffer()%> // Here you print the value "offer". If you don't want to show it when it is null, remove this line
<% String s = p.getOffer() %>
<% if (<%=s ==null) { %> // the <%= is unnecessary. if(s==null) is enough
show nothing // show nothing, why not inverse the if and show something
Here another approach:
<%
String s= p.getOffer();
if(s != null){ %>
Offer: <%= s%>
<% }%>
That way you only print the offer when the variable is not null.
By the way: naming a String variable "s" is not recommended, call it "offer" or something to facilitate the reading.

Google reCAPTCHA: How to get user response and validate in the server side?

I am doing a Java (JSP + Servlet) web application (I understand that this question is technology-independent). I hope to use the latest Google reCAPTCHA service.
I am playing with a Google reCAPTCHA example found here:
https://developers.google.com/recaptcha/docs/display#config
<html>
<head>
<title>reCAPTCHA demo: Simple page</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="my_site_key"></div>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
I am able to see the displayed recaptcha image as follows:
When I check "I'm not a robot", I get the following:
As you can see, there is a Verify button and based on my tests, user response is sent to Google for verification.
How can I get the user response so that I can verify user response in my own backend code (as suggested by Google at https://developers.google.com/recaptcha/docs/verify).
g-recaptcha-response POST parameter when the user submits the form on your site
On the server side, I can, by clicking on the "Submit" button, get user input from parameter "g-recaptcha-response" only when a user is verified successfully with Google first. Otherwise, "g-recaptcha-response" is blank on the server side. This means that I can do server-side verification only after the client-side's verification success. If so, what is the point of doing another verification on the server-side, which is the option provided by Google reCAPTHA?
Do I miss anything?
The cool thing about the new Google Recaptcha is that the validation is now completely encapsulated in the widget. That means, that the widget will take care of asking questions, validating responses all the way till it determines that a user is actually a human, only then you get a g-recaptcha-response value.
But that does not keep your site safe from HTTP client request forgery.
Anyone with HTTP POST knowledge could put random data inside of the g-recaptcha-response form field, and fool your site to make it think that this field was provided by the google widget. So you have to validate this token.
In human speech, it would be like,
Your Server: Hey Google, there's a dude that tells me that he's not a robot. He says that you already verified that he's a human, and he told me to give you this token as proof of that.
Google: Hmm... let me check this token... yes I remember this dude I gave him this token... yeah he's made of flesh and bone let him through.
Your Server: Hey Google, there's another dude that tells me that he's a human. He also gave me a token.
Google: Hmm... it's the same token you gave me last time... I'm pretty sure this guy is trying to fool you. Tell him to get off your site.
Validating the response is really easy. Just make a GET request to
https://www.google.com/recaptcha/api/siteverify?secret=your_secret&response=response_string&remoteip=user_ip_address
And replace the response_string with the value that you earlier got by the g-recaptcha-response field.
You will get a JSON Response with a success field.
More information here:
https://developers.google.com/recaptcha/docs/verify
Edit: It's actually a POST, as per documentation here.
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:
<div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
<span id="captcha" style="margin-left:100px;color:red" />
This code put at head section on call get_action(this) method form button:
function get_action(form) {
var v = grecaptcha.getResponse();
if(v.length == 0)
{
document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
return false;
}
if(v.length != 0)
{
document.getElementById('captcha').innerHTML="Captcha completed";
return true;
}
}
Here is complete demo code to understand client side and server side process. you can copy paste it and just replace google site key and google secret key.
<?php
if(!empty($_REQUEST))
{
// echo '<pre>'; print_r($_REQUEST); die('END');
$post = [
'secret' => 'Your Secret key',
'response' => $_REQUEST['g-recaptcha-response'],
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec($ch);
curl_close ($ch);
echo '<pre>'; print_r($server_output); die('ss');
}
?>
<html>
<head>
<title>reCAPTCHA demo: Explicit render for multiple widgets</title>
<script type="text/javascript">
var site_key = 'Your Site key';
var verifyCallback = function(response) {
alert(response);
};
var widgetId1;
var widgetId2;
var onloadCallback = function() {
// Renders the HTML element with id 'example1' as a reCAPTCHA widget.
// The id of the reCAPTCHA widget is assigned to 'widgetId1'.
widgetId1 = grecaptcha.render('example1', {
'sitekey' : site_key,
'theme' : 'light'
});
widgetId2 = grecaptcha.render(document.getElementById('example2'), {
'sitekey' : site_key
});
grecaptcha.render('example3', {
'sitekey' : site_key,
'callback' : verifyCallback,
'theme' : 'dark'
});
};
</script>
</head>
<body>
<!-- The g-recaptcha-response string displays in an alert message upon submit. -->
<form action="javascript:alert(grecaptcha.getResponse(widgetId1));">
<div id="example1"></div>
<br>
<input type="submit" value="getResponse">
</form>
<br>
<!-- Resets reCAPTCHA widgetId2 upon submit. -->
<form action="javascript:grecaptcha.reset(widgetId2);">
<div id="example2"></div>
<br>
<input type="submit" value="reset">
</form>
<br>
<!-- POSTs back to the page's URL upon submit with a g-recaptcha-response POST parameter. -->
<form action="?" method="POST">
<div id="example3"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
</body>
</html>

How to pass message from servlet to jsp?

I want to pass a status parameter from servlet to jsp. I am sending it through
response.sendRedirect("newpage.jsp?status=yes");
If status = yes then show success message in <div> and then set status to null. But when the newpage.jsp loads at the first time the value of status is null and it gives null pointer exception.
Same thing happens with session also.
<%
String status = request.getParameter("status");
System.out.println("Check Successful of Status"+status);
if (status.equalsIgnoreCase("yes")) {
System.out.println("Check Successful of Status");
%>
<div style="color: green;" align="center">Selected tenant approved successfully</div>
<script type="text/javascript"> window.location.href = window.location.href.split("?")[0]; </script>
<%
request.setAttribute("status1", null);
%>
In Servlet you can use
request.setAttribute("status","yes")
in jsp, you can retrieve using
request.getAttribute("status");
Yes, I missed the point
for above u need to use
RequestDispatcher rd = request.getRequestDispatcher("somefile.jsp");
rd.forward(request,response);
If u want to use response.sendRedirect("somefile.jsp"),
u can set the variable in session as
HttpSession session = request.getSession(false);
session.setAttribute("status","yes")
and get it back as
session.getAttribute("status").
Once used, u can remove it as
session.removeAttribute("status")
request.setAttribute("status1", yourstatus);
getServletContext().getRequestDispatcher("yourpageyouwanttosend.jsp").forward(request, response);
your view <%= request.getAttribute("status1") %>
You are using status as parameter name and you are comparing status1 in your JSP
if (status1.equalsIgnoreCase("yes")) {
Note:
placing javacode on jsp is not good thing, switch to JSTL

Print javascript alert with the value available in request object

I am trying to alert a value which is available in request object, following is my code:
<%
String isValidTransaction="";
if (request.getAttribute("isValidTransaction") != null)
{
isValidTransaction = request.getAttribute("isValidTransaction").toString();
%>
<script>
var transactionAlert = "<%=isValidTransaction%>";
if(transactionAlert.length == 0)
{
alert(transactionAlert);
}
</script>
<span class="formError" id="isValidTransaction">
<h1><%=request.getAttribute("isValidTransaction").toString()%></h1>
</span>
<%}%>
but the alert message is printed and the whatever is printed in <h1><%=request.getAttribute("isValidTransaction").toString()%></h1> is getting printed.
so, how to alert a value using javascript which is available in request object?
thanks
You should use console.log() instead of alert() function. Because alert() just return object.toString().

using a scriplet inside a javascript function

I wanted to use a scriplet inside a java script function. I wanted to check for some attribute's vale and give an alert according to that. Following is the function in which the only scriplet statement gives an error.
function UploadMessage() {
<% if((String)request.getAttribute("SuccessMessage").compareTo("Uploaded successfully") == 0) { %>
alert("File Successfully uploaded !");
<%
} %>
}
Is there any way i can do this ? What is the problem here ?
NOTE : I have placed the above snippet in a jsp page
function UploadMessage() {
<% if(((String)request.getAttribute("SuccessMessage")).equals("Uploaded successfully")) { %>
alert("File Successfully uploaded !");
<%
} %>
}
Problem was -
The method compareTo(String) is undefined for the type
Object
Incompatible operand types String and int

Categories