JSP Exception error while converting from String to Int - java

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.

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

FreeMarker template error: The following has evaluated to null or missing | BUT NOT TRUE

The error I'm facing is so weird. Everything looks fine, but I get this error when the browser sends the GET request to the server. What I'm trying to do is actually catching the HTTP parameters, save them in an object saved in an ArrayList sending to a Freemarker template.
Could you please help me? Thanks a lot.
The error:
freemarker.log._JULLoggerFactory$JULLogger error SEVERE: Error
executing FreeMarker template FreeMarker template error: The following
has evaluated to null or missing:
==> item.lat1 [in template "view/result.ftl" at line 18, column 15]
freemarker.core.InvalidReferenceException: [... Exception message was
already printed; see it above ...] at
freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:131)
at freemarker.core.EvalUtil.coerceModelToString(EvalUtil.java:355)
at
freemarker.core.Expression.evalAndCoerceToString(Expression.java:82)
at freemarker.core.DollarVariable.accept(DollarVariable.java:41) at
freemarker.core.Environment.visit(Environment.java:324) at
freemarker.core.MixedContent.accept(MixedContent.java:54) at
freemarker.core.Environment.visitByHiddingParent(Environment.java:345)
at
freemarker.core.IteratorBlock$IterationContext.executeNestedBlockInner(IteratorBlock.java:268)
at
freemarker.core.IteratorBlock$IterationContext.executeNestedBlock(IteratorBlock.java:220)
at
freemarker.core.IteratorBlock$IterationContext.accept(IteratorBlock.java:194)
at
freemarker.core.Environment.visitIteratorBlock(Environment.java:572)
at
freemarker.core.IteratorBlock.acceptWithResult(IteratorBlock.java:78)
at freemarker.core.IteratorBlock.accept(IteratorBlock.java:64) at
freemarker.core.Environment.visit(Environment.java:324) at
freemarker.core.MixedContent.accept(MixedContent.java:54) at
freemarker.core.Environment.visit(Environment.java:324) at
freemarker.core.Environment.process(Environment.java:302) at
freemarker.template.Template.process(Template.java:325) at
spark.template.freemarker.FreeMarkerEngine.render(FreeMarkerEngine.java:71)
at controller.App.lambda$main$1(App.java:57) at
spark.RouteImpl$1.handle(RouteImpl.java:58) at
spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:162) at
spark.webserver.JettyHandler.doHandle(JettyHandler.java:61) at
org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
at
org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at
org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
at org.eclipse.jetty.server.Server.handle(Server.java:517) at
org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:302) at
org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
at
org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:245)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at
org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
at
org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
at
org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Thread.java:745)
[qtp285763673-17] ERROR spark.webserver.MatcherFilter -
java.lang.IllegalArgumentException:
freemarker.core.InvalidReferenceException: The following has evaluated
to null or missing:
==> item.lat1 [in template "view/result.ftl" at line 18, column 15]
.. But true, because I do print the Array and it works fine!
final FreeMarkerEngine freeMarkerEngine = new FreeMarkerEngine();
final Configuration freeMarkerConfiguration = new Configuration();
freeMarkerConfiguration.setTemplateLoader(new ClassTemplateLoader(App.class, "/"));
freeMarkerEngine.setConfiguration(freeMarkerConfiguration);
get("/rest", (request, response) -> {
Double lat1 = Double.parseDouble(request.queryParams("lat1") != null ? request.queryParams("lat1") : "anonymous");
Double lon1 = Double.parseDouble(request.queryParams("lon1") != null ? request.queryParams("lon1") : "anonymous");
Double lat2 = Double.parseDouble(request.queryParams("lat2") != null ? request.queryParams("lat2") : "anonymous");
Double lon2 = Double.parseDouble(request.queryParams("lon2") != null ? request.queryParams("lon2") : "anonymous");
if (shouldReturnHtml(request)) {
response.status(200);
response.type("text/html");
Map<String, Object> attributes = new HashMap<>();
attributes.put("list",loadTheList(lat1,lon1,lat2,lon2));
return freeMarkerEngine.render(new ModelAndView(attributes, "/view/result.ftl"));
}
else {
response.status(200);
response.type("application/json");
return null;
}
});
}
private static boolean shouldReturnHtml(Request request) {
String accept = request.headers("Accept");
return accept != null && accept.contains("text/html");
}
public static ArrayList<Bereken> loadTheList(double lat1, double lon1, double lat2, double lon2) {
ArrayList<Bereken> list = new ArrayList<>();
list.add(new Bereken(lat1,lon1,lat2,lon2));
return list;
}
And result.ftl:
<#list list as item>
<h2>${item.lat1}</h2>
<h2>${item.lon1}</h2>
<h2>${item.lat2}</h2>
<h2>${item.lon2}</h2>
</#list>
I know this is an old question, but I just bumped into this. Freemarker will also complain that the value "is null or missing" if you pass it an instance of a private class (which I just tried). If you pass in a Java Bean class, it needs to be public. The error message is very misleading in this case.
You are adding 1 instance of the Bereken class to the "list".
So i would assume the Bereken class does not provide public properties lat1, lat2, lon1, lon2 or coresponding getter methods.
I just ran across this yesterday. I was working through a tutorial and one of the steps did not include the code for a getter method in a class that created an object. I guess the author just assumed the reader knew that should have happened already.
So, wherever this 'Bereken' thing is (I just learned it is a JavaBean class), be sure to add the setter and getter methods for the properties associated with each element in the 'list'.

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

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)) {

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.

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