mysql java.lang.NumberFormatException:空的java.lang.Integer.parseInt(未知的来源)

waxmsbnn  于 2022-11-28  发布在  Mysql
关注(0)|答案(1)|浏览(188)

我正在尝试从jsp页面获取值,并希望使用java将这些值存储在mysql(xampp)数据库中。连接已建立并成功登录,但当我尝试获取值时,出现空指针异常
MainController.java

package classes;

import java.io.IOException;

import java.sql.Connection;

import java.sql.Date;

import java.sql.DriverManager;

//import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.sql.Time;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

/**

 * Servlet implementation class MainController

 */

@WebServlet("/MainController")

public class MainController extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**

     * @see HttpServlet#HttpServlet()

     */
    public MainController() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {



    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    }
    //@SuppressWarnings("null")
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String url= "jdbc:mysql://localhost/meeting_planner";
        System.out.println("start");
        // boolean stfound = false;

        try {
            System.out.println("reached controller");
            Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection(url, "admin", "admin");

        Statement stmt = con.createStatement();
        //System.out.println("connection");
        String button=request.getParameter("button");
        System.out.println(button +  request.getParameter("AId"));



        if(button.equals("login"))
        {

            System.out.println("inside if");

            String  AdminId= request.getParameter("AId");
            String password= request.getParameter("Password");

            System.out.println(AdminId+"  sadia   "+password);

            if(!(AdminId=="" || password==""))
            {

                boolean stfound = false;

                System.out.println(AdminId+"  sadia   "+password);

                String query = "SELECT AId,Password FROM administrator";

                ResultSet rs = stmt.executeQuery(query);
                System.out.println(query);

                while(rs.next())
                {

                    String dbadminid = rs.getString(1);
                    String dbadminpwd = rs.getString(2);

                    if(AdminId.equals(dbadminid) && password.equals(dbadminpwd))
                    {
                        HttpSession session = request.getSession(true);
                        session.setAttribute("userid",dbadminid);
                        stfound = true;
                        break;
                    }
                }



        if(stfound){
             RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( "/meeting_Id.jsp" ) ;

             dispatcher.forward ( request, response ) ;

            }
        }
            else{
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( "/index.jsp" ) ;

                dispatcher.forward ( request, response ) ;

            }
            }
        if(button.equals("Next"))
    {

        HttpSession session = request.getSession(true);
        String AID =(String) session.getAttribute("aid");

        int meetingid = Integer.parseInt(request.getParameter("meeting_id"));
        /*String CNM= request.getParameter("CNM");
        int CCD = Integer.parseInt(request.getParameter("CCD"));
        int  CCDD= Integer.parseInt(request.getParameter("CCDD"));
        int PID= Integer.parseInt(request.getParameter("PID"));
        int STFID=Integer.parseInt(AID);*/

        meeting obj=new meeting();
        obj.addmeeting(meetingid);

        System.out.print("Sadia");

        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( "/creat_date.jsp" ) ;

        dispatcher.forward ( request, response ) ;
    }
    }catch (ClassNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SQLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    }
}

而Meeting.java是

package classes;

import java.sql.Connection;

import java.sql.Date;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Time;

import java.sql.Statement;

public class meeting {

    private int meeting_id;
    Connection con=null;
    Statement smt = null;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }
    public meeting()throws ClassNotFoundException//construtor
        , SQLException{
            //  try{
            String url = "jdbc:mysql://localhost/meeting_planner";
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(url, "admin", "admin");

            smt = con.createStatement();

            //}catch(ClassNotFoundException e1){
            //e1.printStackTrace();
        }
        public void addmeeting(int meeting_id1)throws ClassNotFoundException  // from attribute web.xml
            , SQLException{
                System.out.println("------TRY INSERTION------"); 

                String query = "SELECT meeting_Id FROM meeting";
                ResultSet rs = smt.executeQuery(query);
                int numCols = rs.getMetaData().getColumnCount()+1;
                //  STAFF_ID=numCols+1;

                String query1 = "INSERT INTO Meeting VALUE ( "+meeting_id+")";
                System.out.println(query1); 
                smt.executeUpdate(query1);

            }
        }

Next按钮的名称为“next”,当我在System.out.println("next"+next);这一行中打印next的值时,它为next参数打印null

编辑:已解决NullPointerException的问题,但现在掷回NumberFormatException

控制台是这样的

start

reached controller

inside if

111  sadia   sadia

111  sadia   sadia

SELECT AId,Password FROM administrator

start

reached controller

Oct 29, 2014 6:44:57 PM org.apache.catalina.core.StandardWrapperValve invoke

SEVERE: Servlet.service() for servlet [classes.MainController] in context with path [/Meeting1] threw 

exception

java.lang.NumberFormatException: null

    at java.lang.Integer.parseInt(Unknown Source)

    at java.lang.Integer.parseInt(Unknown Source)

    at classes.MainController.doPost(MainController.java:141)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)

    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

    at 

org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)

    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)

    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)

    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)

    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)

    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)

    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)

    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)

    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)

    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)

    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)

    at 

org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)

    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)

    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)

    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

    at java.lang.Thread.run(Unknown Source)

index.jsp是

<form method = "post" name="create" action="MainController">

                                    <label for="author">Enter id: </label> <input type="text"
                                        id="AId" name="AId" required="required" />
                                    <div class="cleaner_h10"></div>
                                    <label for="author">Enter_password: </label><input
                                        type="password" name="Password" required="required" />
                                    <div class="cleaner_h10"></div>
                                    <br>  <input type="submit"
                                            name="button" " value="login"
                                            style="height: 30px; width: 70px"></a>
                                             </input>

                                </form>

会议ID. jsp为

<form method="post" name="create" action="MainController">

                    <label for="author">Enter Meeting Id:</label> <input type="text" id="meeting_id" name="mid" required="required" />
                    <div class="cleaner_h10"></div>

                    <div class="cleaner_h10"></div><br>

            <input type="submit" name="cancelbutton" value="Cancel" style="height:30px; width:70px">
            </input>
            <input type="submit" name="button" value="Next" style="height:30px; width:70px">
            </input>
                </form>
0x6upsns

0x6upsns1#

原始NullPointerException问题的解决方案

问题就在这里:

//System.out.println("connection");
    String button=request.getParameter("button");
    System.out.println(button +  request.getParameter("AId"));



    if(button.equals("login"))

正如您从自己的调试打印中看到的,您打印的button和参数AId都为空。
因此,当你试图调用button.equals("login")时,你会得到一个NullPointerException,这是因为你不能在null上调用一个方法。
在使用参数之前,你应该检查参数是否为null,即使你认为它们不应该是null--因为黑客可能试图在没有表单控制的情况下向servlet发送内容。
下面是一步一步发生的事情。
1.显示index.jsp。单击按钮。

  1. MainController运行。因为有一个来自index.jspbutton参数,所以一切正常,它到达最后的代码,将其转发到meeting_Id.jsp,现在显示在浏览器上。
    1.现在单击该按钮,将meeting_Id.jsp中的表单发送回MainController
    1.现在,在这个调用中,没有参数button。因此,您会得到NullPointerException。
    您正在MVC环境中工作。每个表单都被发送到同一个控制器MainContoller,并且MainController应该足够智能,能够知道哪个表单向它发送了请求,并相应地处理它。但是您的环境假设只有index.jsp在调用它。但是它不是这样工作的。当您单击meeting_Id.jspa上的next按钮时,您正在创建一个新请求,该请求转到同一个MainController servlet,并导致错误。
    你应该确保你的表单发送某种ID,告诉MainController哪个表单正在使用它,然后控制器可以发送请求给适当的模型处理。你使用它的输入应该有相同的名称,并且应该存在于你发送的所有表单中。

NumberFormatException的解决方案

现在,您有一个类似的问题,但原因不同。在此行中:

int meetingid = Integer.parseInt(request.getParameter("meeting_id"));

您正在尝试解析一个名为meeting_id的参数。问题是,同样,您没有检查空值。您实际上没有这样的参数。
为什么?因为这是你的HTML(meeting_Id.jsp)所表达的内容:

<input type="text" id="meeting_id" name="mid" required="required" />

正如您所看到的,“meeting_id”是它的id,而不是它的name,并且getParameter()总是与输入的name一起工作。
除此之外,在修复此问题之后,必须确保(使用正则表达式)参数中只有数字,或者必须在parseInt行周围使用try-catch块捕获NumberFormatException
始终检查从用户处获取的参数。切勿假设它们存在、不为空或具有预期的值。

相关问题