JSP, Integer.parseInt throw error even when testing for null - java

here is the code
if(var!=null) {
int varInt= Integer.parseInt(var);
method.setProp(varInt);
}
After some reseach it normally throw error when we're not testing for null, but I am, so what's the problem?
The Error
org.apache.jasper.JasperException: An exception occurred processing JSP page /TravelSearch.jsp at line 81
80: if(var!=null) {
81: int varInt= Integer.parseInt(var);
82: method.setProp(varInt);
83: }
84:
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:567)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:469)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
cause mère
java.lang.NumberFormatException: For input string: ""

Take a look at this answer by Jon Skeet.
https://stackoverflow.com/a/1486082/891261
This is what you want - a method that checks if the string can be parsed to a number and returns an obvious illegal value when it does not, which you then can check for and act on.

The number you're trying to parse isn't null, it's an empty string "". The stacktrace was telling you this here:
java.lang.NumberFormatException: For input string: ""
Change your test to do this:
if(var!=null && !"".equals(var)) {

Related

JSP error at line 31

When i am running the jsp page drops me this error , any suggestion in order to fix it , (i know jsp with java its not good)...
type Exception report
message An exception occurred processing JSP page
/assets/jsp/create-dest-code.jsp at line 31
description The server encountered an internal error that prevented it
from fulfilling this request.
exception org.apache.jasper.JasperException: An exception occurred
processing JSP page /assets/jsp/create-dest-code.jsp at line 31
28: if(id > -1) 29: { 30: int insert_ch; 31: for(int
i=0;i
insert_ch=myStatement.executeUpdate("INSERT INTO Dest_has_Categories
(Dest_idDest,Categories_idCategories) VALUES
('"+id+"','"+cat[i]+"')"); 34: }
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:574)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause java.lang.NullPointerException
org.apache.jsp.assets.jsp.create_002ddest_002dcode_jsp._jspService(create_002ddest_002dcode_jsp.java:136)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache
Tomcat/8.0.33 logs.
my code :
<%
String id8=request.getParameter("id8"); //Country field
String id9=request.getParameter("id9"); //City field
String id10=request.getParameter("id10"); //URL field
int id = -1;
Class.forName("com.mysql.jdbc.Driver");
String myDatabase = "jdbc:mysql://localhost:3306/project_app?user=root&password=1234";
Connection myConnection = DriverManager.getConnection(myDatabase);
Statement myStatement = myConnection.createStatement();
String sqlInsert = "INSERT INTO dest(Country,City,URL) VALUES ('"+id8+"', '"+id9+"','"+id10+"')";
myStatement.executeUpdate(sqlInsert);
ResultSet rs = myStatement.executeQuery("SELECT idDest FROM dest WHERE Country='"+id8+"' AND City='"+id9+"' AND URL='"+id10+"'" );
while (rs.next()) {
id=rs.getInt(1);
}
String cat[]=request.getParameterValues("dest1");
if(id > -1)
{
int insert_ch;
for(int i=0;i<cat.length;i++)
{
insert_ch=myStatement.executeUpdate("INSERT INTO Dest_has_Categories (Dest_idDest,Categories_idCategories) VALUES ('"+id+"','"+cat[i]+"')");
}
}
myStatement.close();
myConnection.close(); %>
<h1 style="color:blue;">Successful Registration </h1>
I assume that once you know what is the line #31, you will be able to fix your NPE thanks to many other questions of this type so let's focus on how to find the line #31 in your case.
According to your stacktrace you are using Tomcat 8, so the source code of your jsp file /assets/jsp/create-dest-code.jsp is in $TOMCAT_HOME/work/Catalina/localhost/assets/org/apache/jsp/jsp/create-dest-code_jsp.java, from here check the line #31 and you will know how to fix it.
Actually you have already the answer here:
28: if(id > -1) 29: { 30: int insert_ch; 31: for(int i=0;i
insert_ch=myStatement.executeUpdate("INSERT INTO Dest_has_Categories
(Dest_idDest,Categories_idCategories) VALUES
('"+id+"','"+cat[i]+"')"); 34: }
It seems that your variable cat is null which probably means that you have no value for the parameter dest1.
Are you sure you connection string is valid? In the example here There is more details in the connection string that is missing in your code (like database name) :
Connection con = null;
try {
con = DriverManager.getConnection(
"jdbc:sqlserver://localhost\\SQLEXPRESS;"
+ "user=sa;password=HerongY#ng;"
+ "database=AdventureWorks2014");
source

HTTP Status 500 - An exception occurred processing JSP page /FinancialAssessment.jsp at line 440

Following is the exact error.
Type Exception report:
message An exception occurred processing JSP page /FinancialAssessment.jsp at line 440
Description:
The server encountered an internal error that prevented it from fulfilling this request.
Exception:
org.apache.jasper.JasperException: An exception occurred processing JSP page /FinancialAssessment.jsp at line 440
437:
438:
439:
440:
if(std.prev_treatment_start_date.equals("null"))
441: {
442: System.out.println("out by krishna------------");
443:
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
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:728)
root cause:
java.lang.NullPointerException
org.apache.jsp.FinancialAssessment_jsp._jspService(FinancialAssessment_jsp.java:542)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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:728)
If your error line is that one on the if statement which is the most prabably, try this:
if( std == null || std.prev_treatment_start_date == null ) {
.....
This is because in java you have to test each object to avoid a NullPointerException which means that an object is null and cannot have methods or attributes.
Either std or std.prev_treatment_start_date is null. You should use:
if (std == null || std.prev_treatment_start_date == null) {
The way you wrote it means "std.prev_treatment_start_date is a string and has a value, and this value equals the string null".

What type of exception is (0)null?

I am using Apache Axis, and I am getting exception of type (0)null. Here is partial stack trace:
....
....
org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at java.lang.Thread.run(Thread.java:744)
Caused by: (0)null
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:744)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.netsuite.webservices.platform_2012_1.NetSuiteBindingStub.upsertList(NetSuiteBindingStub.java:11841)
....
....
Following is what I see in HTTPSender source code.
....
AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);
....
throw fault;
....
So the exception is of type AxisFault, but it looks like statusMessage is null. Line 444 is:
AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);
The (0)null part comes from "(" + returnCode + ")" + statusMessage. statusMessage itself is assigned in line 742:
String statusMessage = msgContext.getStrProp(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
returnCode is set to 0 early on in the method. The next few statements should set it to its correct value:
Integer rc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
if (rc != null) {
returnCode = rc.intValue();
} else {
// No return code?? Should have one by now.
}
After this, the if block and none of the else if blocks get executed since the return code is 0 (because rc is null). It finally lands up in the else block where it generates the AxisFault exception.
You will notice that the statusMessage itself is null. The only place I can see it setting this property is on line 641, which is the readHeadersFromSocket method.
The only way the status message and the return code will not be set is if they are already null, or if there is an error earlier on in the method, which causes control to break out of the for loop that starts on line 581. Of particular interest are line 585 and line 598, both of which are if statements that will break out of the loop if their test-condition is true. One of these statements checks to see if the value of inp.read() is -1 (which means that the end of the stream has been reached), the other checks to see if the length of what was read in is 0. These conditions can hold true if there is a network error (i.e., nothing read from the socket) or if nothing was returned from the server (zero-length data). So if any of these conditions are true, control breaks out of the loop. Eventually, readFromSocket will throw the exception since it wasn't able to get a return code. But because the failure happened before it could even set an error message, you get a null error message.
tl; dr; There is probably some sort of network/read error.

JSP Exception error while converting from String to Int

There is one class as X.Java.In this below two lines I am doing
request.getSession.setAttribute("count",String.valueOf(rsp.getCount()));
In the above I am getting count from database in rsp.getCount(). Here getcount() is integer
type and I am changing to String as String.valueOf(rsp.getCount() and setting into one attribute as count.
There is one jsp as X.jsp
Now I am using getAttribute and storing the value in failCount variable of string type.
String failCount = request.getSession.getAttribute("count");
Now I want to convert this value into integer type for that I wrote this line
int countInt = Integer.parseInt(failCount);
I am getting error like the one below
127039 13-02-26 17:13:35 ERROR http-10.18.2.105-12205-Processor4 - <JSPFilter ServletException> - test.abc.common.filter.JSPFilter.doFilter(JSPFilter.java:111)
org.apache.jasper.JasperException: Exception in JSP: abc/x.jsp:66
63:
64: }
65: String failCount = (String)request.getSession().getAttribute("failCount");
66: int failCountint = Integer.parseInt(failCount);
67: //System.out.println(failCountint);
68:
69:
Stacktrace:
at org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:489)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:308)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:259)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:679)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:461)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:399)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:142)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:247)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1105)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:841)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:755)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:350)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:627)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
Please help me fix this.
Make sure you are setting session in HttpRequest
request.getSession.setAttribute("count",String.valueOf(rsp.getCount()));
Is this java file is servlet then it will work well.
One more thing make sure rsp.getCount() is not return "null".
In JSP file
String failCount = (String)request.getSession().getAttribute("failCount");
int failCountint = Integer.parseInt(failCount);
why are you using request.getSession() instead of session, and you are trying to get failcount instead of count
Try this
String failCount = session.getAttribute("count").toString();
int countInt = Integer.parseInt(failCount);
I think it may help full...
Setting value is session:
request.getSession.setAttribute("count",String.valueOf(rsp.getCount()));
Reading value from session:
String failCount = (String)request.getSession().getAttribute("failCount");
While setting the value in session, you are calling it count and while reading the value from JSP, you are calling it failCount.
I think failCount is null that why
int failCountint = Integer.parseInt(failCount);
So please use
System.out.println(failCount);
And also use try catch block around error line.

Error when trying to search similar images using JSP

I am building a web application for feature extraction and comparing the feature of images, using JSP, Java, and PostgreSQL.
My feature extraction is extracting some features from images, so that then I can compare them (some features are about color, some on the histogram of the image and so. I have special methods that extract them using specific libraries (jars that I add into lib) as you can see in the following example!
Those features are then successfully being added into my PostgreSQL database.
public void GetImageProperties(String targetPath, ImageProperties imagesProperties) throws Exception
{
// load image
FileInputStream imageStream;
imageStream = new FileInputStream(targetPath);
BufferedImage bimg = ImageIO.read(imageStream);
// get properties
imagesProperties.cl = new ColorLayoutImpl(bimg);
imagesProperties.eh = new EdgeHistogramImplementation(bimg);
imagesProperties.sc = new ScalableColorImpl(bimg);
}
Then I add them into a postgresql database(only the features, not the images)
String query = "CREATE TABLE Images (" +
" imageid SERIAL PRIMARY KEY," +
" fname VARCHAR(128)," +
" colorlayout VARCHAR(512), " +
" edgehist VARCHAR(512), " +
" scalablecolor VARCHAR(512) " +
")";
I get this error every time I had loaded an image and want to compare it with all the other images in a directory.
HTTP Status 500 -
type Exception report
message:
description The server encountered an internal error () that prevented it from fulfilling this request.
exception:
org.apache.jasper.JasperException: An exception occurred processing JSP page /query.jsp at line 124
121: if (bSearch) {
122: // get form params
123: query.setTopK(new Integer(request.getParameter("frm_topk")));
124: query.setColorHistogramWeight(new Integer(request.getParameter("frm_weight_c1")));
125: query.setColorDistributionWeight(new Integer(request.getParameter("frm_weight_c2")));
126: query.setTextureWeight(new Integer(request.getParameter("frm_weight_c3")));
127: }
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
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:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause:
java.lang.NumberFormatException: For input string: "1.0"
java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
java.lang.Integer.parseInt(Integer.java:492) java.lang.Integer.<init>
(Integer.java:677) org.apache.jsp.query_jsp._jspService(query_jsp.java:256)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
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:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.27 logs.
Your problem is here
query.setTopK(new Integer(request.getParameter("frm_topk")));
should be
String parFrm_topk = request.getParameter("frm_topk");
Integer frm_topk = null;
if (parFrm_topk != null && parFrm_topk.length() > 0 && !parFrm_topk.equals("null"))
try {
frm_topk = Integer.valueOf(parFrm_topk);
} catch (NumberFormatException nfe){
throw nfe;
}
if (frm_topk ! = null) {
query.setTopK(frm_topk);
this code is trying to check the parameter that could be empty, why it is empty depends on how flow the app and how parameters are passed through url.

Categories

Resources