今天在編寫網頁計算器時總是出現一個莫名其妙的錯誤java
個人代碼是這樣的apache
<%! String filename=this.getServletContext().getRealPath("/"); %>
結果報錯:app
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
後來經過查找解決,應該是<%!%>使用來定義全局變量,函數,類的jsp
這裏的filename不是常量,定之後須要計算才能得出,因此會出問題,改成《%%》函數
或者將filename改成一個常量的字符串便不會出現問題了。this
若是仍是須要用到filename的全局變量;spa
能夠先在定義一個全局的null值的變量,而後寫一個函數進行賦值操做便可。code
jsp老是會有一些莫名其妙的錯誤,並且不告訴你在多少行,真是煩。server