在Struts 2中插入更新删除但显示NullPointerException

时间:2014-05-08 05:37:19

标签: java jsp servlets jdbc struts2

这里我提出了像更新,删除和查看这样的操作的问题,所以现在插入工作正常,但其他操作如updatedeleteview显示错误,如。有人可以指导正确的方向吗?这就是我到现在为止所做的一切

错误:

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

javax.servlet.ServletException: java.lang.NullPointerException
    org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
    org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause

java.lang.NullPointerException
    Action.Testiue.view(Testiue.java:115)
    sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    java.lang.reflect.Method.invoke(Method.java:606)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
    com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
    com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
    com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
    com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
    com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
    com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
    com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
    com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
    org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)

struts.xml中:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <include file="struts-default.xml" />
    <package name="a" extends="struts-default">
        <action name="adduser" class="Action.Testiue" method="add">
            <result name="success">/insert.jsp</result>
            <result name="success">/ssuccess.jsp</result>
        </action>

        <action name="viewuser" class="Action.Testiue" method="view">
            <result name="success">/view.jsp</result>
            <result name="error">/error.jsp</result>

        </action>


        <action name="updateuser" class="Action.Testiue" method="update">
            <result name="success">/edit.jsp</result>
            <result name="error">/error.jsp</result>
        </action>

        <action name="deleteuser" class="Action.Testiue" method="delete">
            <result name="success">/dsuccess.jsp</result>
            <result name="error">/error.jsp</result>
        </action>

    </package>

</struts>

Web.xml中

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

TestIUE.java

package Action;

import com.opensymphony.xwork2.ActionSupport;

import dao.UserDao;
import dbBean.UseBean;

public class Testiue 
{

    private String Name;
    private String Password;
    private String EmailID;
    private String Phoneo;
    private int ID;

   public String getName()
    {
        return Name;
    }
    public void setName(String name)
    {
        Name = name;
    }
    public String getPassword()
    {
        return Password;
    }
    public void setPassword(String password)
    {
        Password = password;
    }
    public String getEmailID()
    {
        return EmailID;
    }
    public void setEmailID(String emailID)
    {
        EmailID = emailID;
    }
    public String getPhoneo()
    {
        return Phoneo;
    }
    public void setPhoneo(String phoneo)
    {
        Phoneo = phoneo;
    }
    public int getID()
    {
        return ID;
    }
    public void setID(int i)
    {
        ID = i;
    }
    @Override
    public String toString()
    {
        return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
    }  

    private UserDao dao;
    private UseBean bean;

    public String add()
    {
        dao=new UserDao();
       bean=new UseBean();
        System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
        bean.setID(ID);
        bean.setName(Name);
        bean.setPassword(Password);
        bean.setPhoneo(Phoneo);
        bean.setEmailID(EmailID);
        dao.addUser(bean);
        return ActionSupport.SUCCESS;

    }

    public String update()
    {

        dao=new UserDao();
        bean=new UseBean();
        //System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
        bean.setID(ID);
        bean.setName(Name);
        bean.setPassword(Password);
        bean.setPhoneo(Phoneo);
        bean.setEmailID(EmailID);
        dao.updateUser(bean);
        return ActionSupport.SUCCESS;

    }


    public String delete()
    {

        int userId =0;
        dao.deleteUser(userId);
        return ActionSupport.SUCCESS;
   }
    public String edit()
    {

        int userId =0;
        bean = dao.getUserById(userId);
        return ActionSupport.SUCCESS;
    }
    public String view()
    {

        dao.getAllUsers();
        return ActionSupport.SUCCESS;

    }

}

的index.jsp

<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">

view.jsp的;

<%@ taglib prefix="s" uri="/struts-tags"%>
<%@page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>

<a href="<s:url action="adduser.action"/>">Insert</a>

<table border=1>
    <thead>
        <tr>
        <th>Id</th>
        <th>Name</th>
        <th>password</th>
        <th>phoneno</th>
        <th>emailid</th>
        <th colspan=2>Action</th>
        </tr>
    </thead>
        <jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
        <% for(int i = 0; i < users.size(); i+=1) 
        { 
            UseBean user = (UseBean)users.get(i);
        %>
        <tbody>
        <tr>
            <td><%= user.getID() %></td>
            <td><%= user.getName() %></td>
            <td><%= user.getPassword() %></td>
            <td><%= user.getEmailID() %></td>
            <td><%= user.getPhoneo() %></td>
            <td><a href="<s:url action="updateuser.action"/>">Update</a></td>
            <td><a href="<s:url action="delete.action"/>">Delete</a></td>

            </tr>

<%      
}
%>
</tbody>
 </table>

edit.jsp文件:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="updateuser">

        id:<input type="text" name="ID" ><br/>
        Name:<input type="text" name="Name" ><br/>
        Password:<input type="text" name="password" ><br/>
        phoneno:<input type="text" name="Phoneo" ><br/>
        Emailid:<input type="text" name="Emailid" >  <br/> 

         <input type="submit" value="Submit" />
    </form>     
</body>
</html>

UserDao.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import dbBean.UseBean;
import Dbconnect.*;

public class UserDao
{

    private Connection conn;

    public UserDao()
    {
        conn=Dbconnect.getConnection();
    }
    public void addUser(UseBean bean)
    {
        try
        {
            String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
            PreparedStatement ps=conn.prepareStatement(sql);    
            ps.setString(1,bean.getName());
            ps.setString(2,bean.getPassword());
            ps.setString(3,bean.getPhoneo());
            ps.setString(4,bean.getEmailID());
            ps.executeUpdate();

        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
    }
    public void deleteUser(int userId)
    {
        try
        {
            PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
            // Parameters start with 1
            ps.setInt(1, userId);
            ps.executeUpdate();

        } catch (SQLException e)
        {
            e.printStackTrace();
        }
    }

    public void updateUser(UseBean bean)
    {
        try
        {
            PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
            // Parameters start with 1
            preparedStatement.setString(1, bean.getName());
            preparedStatement.setString(2, bean.getPassword());
            preparedStatement.setString(3, bean.getPhoneo());
            preparedStatement.setString(4, bean.getEmailID());
            preparedStatement.setInt(5, bean.getID());
            preparedStatement.executeUpdate();

        } 
        catch (SQLException e)
        {
            e.printStackTrace();
        }
    }



    public List<UseBean> getAllUsers()
    {
        List<UseBean> users = new ArrayList<UseBean>();
        try
        {
            Statement statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("select * from senthil");
            while (rs.next())
            {
                UseBean user = new UseBean();
                user.setID(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("pass"));
                user.setPhoneo(rs.getString("phoneno"));
                user.setEmailID(rs.getString("emailid"));
                users.add(user);
            }
        } 
        catch (SQLException e)
        {
            e.printStackTrace();
        }

        return users;
    }


    public UseBean getUserById(int userId)
    {
        UseBean user = new UseBean();
        try
        {
            PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
            preparedStatement.setInt(1, userId);
            ResultSet rs = preparedStatement.executeQuery();

            if (rs.next())
            {
                user.setID(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPassword(rs.getString("pass"));
                user.setPhoneo(rs.getString("phoneno"));
                user.setEmailID(rs.getString("emailid"));
            }
        } catch (SQLException e)
        {
            e.printStackTrace();
        }

        return user;
    }       
}

2 个答案:

答案 0 :(得分:0)

在内部视图方法中,您尚未初始化dao对象(即引用为null),请添加以下代码:

在TestIUE.java中再添加一个成员变量:

  List<UseBean> users = new ArrayList<UseBean>();

还添加Accessor方法:

  public List<UseBean> getUsers()
  {
     return users;
  }

现在修改您的视图方法,如下所示:

  public String view()
  {
    dao = new UseDao();
    users = dao.getAllUsers();
    return ActionSupport.SUCCESS;

  }

答案 1 :(得分:0)

在JSP中,users应该可用于请求范围。

public String view() {
  UserDao userDao = new UserDao();
  List<UseBean> users = userDao.getAllUsers();
  ServletActionContext.getRequest().setAttribute("users", users);
  return Action.SUCCESS;
}

public String update() {
  UserDao dao = new UserDao();
  UseBean bean=new UseBean();
  HttpServletRequest request ServletActionContext.getRequest();
  bean.setID(request.getParameter("ID");
  bean.setName(request.getParameter("Name");
  bean.setPassword(request.getParameter("Password");
  bean.setPhoneo(request.getParameter("Phoneo");
  bean.setEmailID(request.getParameter("EmailID");
  //System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
  dao.updateUser(bean);
  return Action.SUCCESS;

}

public String delete() {
  HttpServletRequest request ServletActionContext.getRequest();
  int userId = request.getParameter("ID");
  dao.deleteUser(userId);
  return Action.SUCCESS;
}

删除操作

<a href="<s:url action="delete"><s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete</a>