简体   繁体   English

jsp中的java.lang.NullPointerException

[英]java.lang.NullPointerException in jsp

Hi all I am a fresher in java and jsp and honestly I dont have knowledge of json. 大家好我是java和jsp更新鲜,说实话,我没有json的知识。 but I have some requirement that I have to pull the data from database and display on jsp page. 但我有一些要求,我必须从数据库中提取数据并在jsp页面上显示。 but the criteria is that I have to use Bootstrap Data Table why I am using this because it provide lot of flexibility like Pagination Filtering Sorting Multi-column sorting Individual column filter. 但标准是我必须使用Bootstrap数据表为什么我使用它,因为它提供了很多灵活性,如分页过滤排序多列排序单个列过滤器。 I am getting a java.lang.NullPointerException in my jsp can any body tell me why am I getting this error. 我在我的jsp得到一个java.lang.NullPointerException ,任何正文告诉我为什么会出现这个错误。 This is my jsp page 这是我的jsp页面

dataTable.jsp

<%@page import="org.codehaus.jettison.json.JSONObject"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
   <%@ page import ="java.util.*" %>
  <%--  <%@ page import="com.varun.DataBase"%> --%>
   <%@ page import="java.sql.*" %>
<%--    <%@ page import="org.json.*"%> --%>
   <%@ page import ="net.sf.json.JSONArray" %>


 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DataTable</title>
</head>
<body>
<h1>Lets display the data from database using dataTabel</h1>

<%

String[] cols = { "id","engine", "browser", "platform", "version", "grade" };
String table = "ajax";

JSONObject result = new JSONObject();
JSONArray arr = new JSONArray();


int amount = 10;
int start = 0;
int echo = 0;
int col = 0;

int  id=0;
String engine = "";
String browser = "";
String platform = "";
String version = "";
String grade = "";



String dir = "asc";
String sStart = request.getParameter("iDisplayStart");
String sAmount = request.getParameter("iDisplayLength");
String sEcho = request.getParameter("sEcho");
String sCol = request.getParameter("iSortCol_0");
String sdir = request.getParameter("sSortDir_0");

engine = request.getParameter("sSearch_0");
browser = request.getParameter("sSearch_1");
platform = request.getParameter("sSearch_2");
version = request.getParameter("sSearch_3");
grade = request.getParameter("sSearch_4");


List<String> sArray = new ArrayList<String>();
if (!engine.equals("")) {
    String sEngine = " engine like '%" + engine + "%'";
    sArray.add(sEngine);
    //or combine the above two steps as:
    //sArray.add(" engine like '%" + engine + "%'");
    //the same as followings
}

if (!browser.equals("")) {
    String sBrowser = " browser like '%" + browser + "%'";
    sArray.add(sBrowser);
}
if (!platform.equals("")) {
    String sPlatform = " platform like '%" + platform + "%'";
    sArray.add(sPlatform);
}
if (!version.equals("")) {
    String sVersion = " version like '%" + version + "%'";
    sArray.add(sVersion);
}
if (!grade.equals("")) {
    String sGrade = " grade like '%" + grade + "%'";
    sArray.add(sGrade);
}

String individualSearch = "";
if(sArray.size()==1){
    individualSearch = sArray.get(0);
}else if(sArray.size()>1){
    for(int i=0;i<sArray.size()-1;i++){
        individualSearch += sArray.get(i)+ " and ";
    }
    individualSearch += sArray.get(sArray.size()-1);
}


if (sStart != null) {
    start = Integer.parseInt(sStart);
    if (start < 0)
        start = 0;
}
if (sAmount != null) {
    amount = Integer.parseInt(sAmount);
    if (amount < 10 || amount > 100)
        amount = 10;
}
if (sEcho != null) {
    echo = Integer.parseInt(sEcho);
}
if (sCol != null) {
    col = Integer.parseInt(sCol);
    if (col < 0 || col > 5)
        col = 0;
}
if (sdir != null) {
    if (!sdir.equals("asc"))
        dir = "desc";
}


String colName = cols[col];
int total = 0;
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","admin");
try {
    String sql = "SELECT count(*) FROM "+table;
    PreparedStatement ps = conn.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    if(rs.next()){
        total = rs.getInt("count(*)");
    }
}catch(Exception e){

}
int totalAfterFilter = total;
//result.put("sEcho",echo);

try {
    String searchSQL = "";
    String sql = "SELECT * FROM "+table;
    String searchTerm = request.getParameter("sSearch");
    String globeSearch =  " where (engine like '%"+searchTerm+"%'"
                            + " or browser like '%"+searchTerm+"%'"
                            + " or platform like '%"+searchTerm+"%'"
                            + " or version like '%"+searchTerm+"%'"
                            + " or grade like '%"+searchTerm+"%')";
    if(searchTerm!=""&&individualSearch!=""){
        searchSQL = globeSearch + " and " + individualSearch;
    }
    else if(individualSearch!=""){
        searchSQL = " where " + individualSearch;
    }else if(searchTerm!=""){
        searchSQL=globeSearch;
    }
    sql += searchSQL;
    sql += " order by " + colName + " " + dir;
    sql += " limit " + start + ", " + amount;

    PreparedStatement ps = conn.prepareStatement(sql);
    ResultSet rs = ps.executeQuery();
    while (rs.next()) {
       // JSONArray ja = new JSONArray();
        net.sf.json.JSONArray ja = new net.sf.json.JSONArray(); 

        ja.add(rs.getInt("id"));
        ja.add(rs.getString("engine"));
        ja.add(rs.getString("browser"));
        ja.add(rs.getString("platform"));
        ja.add(rs.getString("version"));
        ja.add(rs.getString("grade"));
        arr.add(ja); 
    } 
    String sql2 = "SELECT count(*) FROM "+table;
    if (searchTerm != "") {
        sql2 += searchSQL;
        PreparedStatement ps2 = conn.prepareStatement(sql2);
        ResultSet rs2 = ps2.executeQuery();
        if (rs2.next()) {
            totalAfterFilter = rs2.getInt("count(*)");
        }
    }
    result.put("iTotalRecords", total);
    result.put("iTotalDisplayRecords", totalAfterFilter);
    result.put("aaData", arr);
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "no-store");
    out.print(result);
    conn.close();
} catch (Exception e) {

}

%>

</body>
</html>

Stack Trace 堆栈跟踪

11:26:50,224 ERROR [[jsp]] Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.jsp.dataTable_jsp._jspService(dataTable_jsp.java:114)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:369)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:322)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:249)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:235)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:190)
    at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:92)
    at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.process(SecurityContextEstablishmentValve.java:126)
    at org.jboss.web.tomcat.security.SecurityContextEstablishmentValve.invoke(SecurityContextEstablishmentValve.java:70)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:158)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:330)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:829)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:598)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
    at java.lang.Thread.run(Unknown Source)

If the answer of Ajil Mohan prevent the error to appear, it means that you have no value in your ParametersMap. 如果Ajil Mohan的答案阻止出现错误,则意味着您的ParametersMap中没有值。

engine = request.getParameter("sSearch_0");
browser = request.getParameter("sSearch_1");
platform = request.getParameter("sSearch_2");
version = request.getParameter("sSearch_3");
grade = request.getParameter("sSearch_4");

These lines just get the data in the Parameter map of your request. 这些行只是获取请求的参数映射中的数据。 If the given is not in the map it returns null ( https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29 ). 如果给定的不在map中,则返回null( https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29 )。 This map is created when you send the POST request on the previous page with the data contained in your form. 当您在上一页上发送包含表单中包含的数据的POST请求时,将创建此映射。 Your input field has to be set with the name you give to the getParameter method. 您的输入字段必须使用您为getParameter方法指定的名称进行设置。

If you don't have previous page with a form then you may want to send data from server to JSP. 如果您没有带有表单的上一页,那么您可能希望将数据从服务器发送到JSP。 If you use Servlet then you should use the request AttributeMap. 如果您使用Servlet,那么您应该使用请求AttributeMap。

public class BasicTotoServlet extends HttpServlet {
 /**
  * Manage GET HTTP Request
  */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        String data = getData();
        request.setAttibute("sSearch_0", data)
    }
}

Then in your JSP : 然后在你的JSP中:

engine = request.getAttribute("sSearch_0");

I hope I was clear enough. 我希望我很清楚。 Ask for precision if needed 如果需要,要求精确度

EDIT : Here is what I understand. 编辑:这是我的理解。

You arrive on your JSP and you get several Parameter from the previous page's form. 您到达JSP并从前一页的表单中获得了几个参数。 This form may not give to you all the information, that is why you get a NPE on this 此表格可能不会向您提供所有信息,这就是您获得NPE的原因

engine = request.getParameter("sSearch_0");
engine.equals("")

To solve this as told you Ajil Mohan, just turn the equals the other way round, so that if engine is NULL you have no problem 要解决这个问题,就像Ajil Mohan告诉你的那样,只需转动等于其他方式,这样如果引擎为NULL则没有问题

"".equals(engine);

As "" is never null you'll never get NPE. 由于“”永远不会为空,你永远不会得到NPE。

Now you don't have any data in you table. 现在您表中没有任何数据。 Why? 为什么? If I'm correct you create a SQL Query by concatenating several data. 如果我是正确的,您可以通过连接多个数据来创建SQL查询。 searchSQL = globeSearch + " and " + individualSearch;

individualSearch is the result of concatenating your Parameters but what if they're null? individualSearch是连接参数的结果,但如果它们为空则会怎样?

if (!"".equals(browser)) {
    String sBrowser = " browser like '%" + browser + "%'";
    sArray.add(sBrowser);
}

In this code, if browser is null (as we saw earlier it can be), you will add the String " browser like '%null%'" to you query with the and key word. 在这段代码中,如果浏览器为null(正如我们之前看到的那样),您将使用和关键字添加字符串" browser like '%null%'" I'm not sure there will be any browser with "null" in its name. 我不确定其名称中是否会有任何名为“null”的浏览器。

You better put this test : 你最好把这个测试:

if (!"".equals(browser) && browser != null) {
    String sBrowser = " browser like '%" + browser + "%'";
    sArray.add(sBrowser);
}

Since it is a jsp file its very difficult to debug. 由于它是一个jsp文件,因此很难调试。 Here you are getting a NullPointerExceotion . 在这里你得到一个NullPointerExceotion。 From your code we can see that some places where NullPointerException would occur. 从您的代码中我们可以看到一些会发生NullPointerException的地方。

For Eg:- You are getting parameter from "sSearch_0". 例如: - 您从“sSearch_0”获取参数。 engine = request.getParameter("sSearch_0"); engine = request.getParameter(“sSearch_0”);

Just imagine, if its a null value. 试想一下,如果它是一个空值。

Then following code will produce a nullpointer exception. 然后下面的代码将产生一个nullpointer异常。

if (!engine.equals("")) if(!engine.equals(“”))

So it is always safe to check as follows, if(!" ".equals(engine)) ... 因此,如果(!“”。equals(engine)),检查如下是安全的...

In this way you wont get null pointer exception even if engine has a null value. 这样,即使引擎具有空值,也不会获得空指针异常。

This may not be the issue, but I wish to mention it. 这可能不是问题,但我想提一下。

Have you considered using something like Google gson in your controller to automatically produce json from a model class? 您是否考虑在控制器中使用Google gson之类的东西从模型类中自动生成json? It could reduce the string manipulation inside your jsp. 它可以减少jsp中的字符串操作。

A more common pattern would be to expose this information from a restful api which is consumed by an ajax call on the front end. 更常见的模式是从前端的ajax调用所消耗的restful api中公开此信息。

Java Jersey in combination with gson or Jackson could achieve a lot of this functionality for you Java Jersey与gson或Jackson相结合可以为您实现许多此功能

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM