jsp会话隐式对象在从servlet调用它时抛出空指针异常

时间:2015-06-24 13:35:22

标签: jsp servlets

我正在使用jsp和servlet开发一个应用程序,我在jsp中使用session隐式对象时遇到了问题。 我正在做的是我在servlet中的会话对象中设置某些属性,然后我将响应转发到jsp页面。现在我想在我的jsp页面中访问这些会话属性,但是这样做会引发空指针异常。 这是我的代码: -

这是我的servlet,

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter pw=response.getWriter();
    con=Connector.myCon();
    u=request.getParameter("userName");
    p=request.getParameter("password");
    HttpSession session=request.getSession();
    session.setAttribute("userName",u); 
    session.setAttribute("userType",userType);
    RequestDispatcher rd=request.getRequestDispatcher("Home.jsp");
    rd.forward(request, response);
    }

这是我的jsp

<%
    session=request.getSession();
    String s = (String) application.getAttribute("name");
    System.out.println(s);
    String userName = (String)session.getAttribute("userName");
    if (userName == null) {
        //request.setAttribute("Error", "Session has ended.  Please logenter code herein.");
        RequestDispatcher rd = request
                .getRequestDispatcher("index.hmtl");
        rd.include(request, response);
        out.println("Session has ended.  Please login.");
    } 
    else 
    {
        String userType = (String)session.getAttribute("userType");
        System.out.println(userType);
        if(userType.equals("student")) 
        {}
    }%> 

我在使用它时遇到空指针异常。 帮助我。

1 个答案:

答案 0 :(得分:0)

像这样改变,

<%
String s = (String) application.getAttribute("name");
System.out.println(s);
String userName = (String)session.getAttribute("userName");
if (userName == null) {
    //request.setAttribute("Error", "Session has ended.  Please logenter code herein.");
    RequestDispatcher rd = request
            .getRequestDispatcher("index.hmtl");
    rd.include(request, response);
    out.println("Session has ended.  Please login.");
} 
else 
{
    String userType = (String)session.getAttribute("userType");
    System.out.println(userType);
    if(userType.equals("student")) 
    {}
}%>