今天在编写网页计算器时老是出现一个莫名其妙的错误
我的代码是这样的
<%! String filename=this.getServletContext().getRealPath("/"); %>
结果报错:
HTTP Status 500 - java.lang.NullPointerException -------------------------------------------------------------------------------- type Exception report message java.lang.NullPointerException description The server encountered an internal error that prevented it from fulfilling this request. exception org.apache.jasper.JasperException: java.lang.NullPointerException org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:177) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) 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 javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125) org.apache.jsp.count_jsp.<init>(count_jsp.java:24) sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) java.lang.reflect.Constructor.newInstance(Unknown Source) java.lang.Class.newInstance0(Unknown Source) java.lang.Class.newInstance(Unknown Source) org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:172) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369) 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) note The full stack trace of the root cause is available in the Apache Tomcat/7.0.42 logs. -------------------------------------------------------------------------------- Apache Tomcat/7.0.42
后来通过查找解决,应该是<%!%>使用来定义全局变量,函数,类的
这里的filename不是常量,定以后需要计算才能得出,所以会出问题,改为《%%》
或者将filename改为一个常量的字符串便不会出现问题了。
如果还是需要用到filename的全局变量;
可以先在定义一个全局的null值的变量,然后写一个函数进行赋值操作即可。
jsp总是会有一些莫名其妙的错误,而且不告诉你在多少行,真是烦。