Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

java - Why isn't this JSP - Servlet code work?

I've a package named classes which includes x.java and y.java. x.java:

public class x{
private int a;
private int b;
private String c;
private String d;
private String e;
private String f;
//And the fields are encapsulated.
}

y.java:

public class y{
private List<x> xs;
private int k1;
private int k2;
private String k3;
private String k4;
//And the fields are encapsulated.
}

z.JSP:

<%
usecase y = new y();
request.getSession().setAttribute("yy", y);
%>
<form action="aaa?id=1" method="POST">
            <td>
            <input type="text" name="bbb"/>
            </td>
            <td>
            <input type="text" name="ccc"/>
            </td>
            <td>
            <input type="submit" name="ddd"/>
            </td>
        </form>

aaa.java (Servlet - inside the processRequest):

PrintWriter out = response.getWriter();
    try {
        y yy = (y) request.getSession().getAttribute("yy");
        String id = request.getParameter("id");
        x s = new x();
        s.setC(request.getParameter("bbb"));
        b.setD(request.getParameter("ccc"));

        if ("1".equals(id)) {
            s.setE("l");
        } else if ("2".equals(id)) {
            s.setE("k");
        }

        yy.getXs().add(s);
        response.sendRedirect("z.jsp");
    } finally {
        out.close();
    }

Here's the code. when I watch it with a breakpoint everything goes well, variables get their values. But in this line: yy.getXs().add(s); there's an error and it doesn't redirect. Would you please help me?

SOLUTION: replace private List<x> xs; with List<X> xs = new ArrayList<X>();. Thanks a lot.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A NullPointerException, most of the time, means that you're dereferencing a null variable. I assume the line causing the exception (line 97 in z.java, as the stack trace indicates) is the following line:

yy.getXs().add(s);

Then it can mean two things:

  1. yy is null
  2. The list returned by yy.getXs() is null.

Use a debugger to identify the problem, or add logging traces in your code.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...