0

こんにちは、フォームを含むサーブレットを実行して送信をクリックすると、次のエラーが表示されます。コードでエラーが見つかりませんが、送信をクリックしても次のエラーが表示されない場合は明らかにエラーがあります。

'lab' を作成できる user_id が存在する場合、SQL を実行する必要があります。

The server encountered an internal error () that prevented it from fulfilling this request.

exception 

java.lang.NumberFormatException: null
    java.lang.Integer.parseInt(Unknown Source)
    java.lang.Integer.parseInt(Unknown Source)
    CreateLab.doPost(CreateLab.java:72)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

import java.io.IOException;


import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CreateLab
 */
@WebServlet("/CreateLab")
public class CreateLab extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateLab() {
        super();
        // TODO Auto-generated constructor stub
    }
     int id;
     int capacity; 
     String day = ""; 
     String time = ""; 
     String room = ""; 
     int subject_id;
     int user_id;

    public void init() {
      try {
          Class.forName("com.mysql.jdbc.Driver");
          Connection con =
            DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
        System.out.println("JDBC driver loaded"); 
      } 
      catch (ClassNotFoundException e) {
        System.out.println(e.toString()); 
      } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    } 

    /**Process the HTTP Get request*/ 
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws 
  ServletException,IOException {  
      sendPageHeader(response); 
      sendRegistrationForm(request, response, false); 
      sendPageFooter(response); 
    } 

    /**Process the HTTP Post request*/ 
    public void doPost(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException {
      sendPageHeader(response); 

      capacity = Integer.parseInt(request.getParameter("capacity"));
      id = Integer.parseInt(request.getParameter("id")); 
      day = request.getParameter("day"); 
      time = request.getParameter("time"); 
      room = request.getParameter("room"); 
      user_id = Integer.parseInt(request.getParameter("user_id")); 
      subject_id = Integer.parseInt(request.getParameter("subject_id")); 


      boolean error = false; 
      String message = null; 
      try {
          Class.forName("com.mysql.jdbc.Driver");
          Connection con = 
            DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
        System.out.println("got connection"); 
        System.out.println(id);
        Statement s = con.createStatement(); 

        String sql = "SELECT id FROM user" + 
                " WHERE id='" + user_id + "'";  
        ResultSet rs = s.executeQuery(sql); 
        if (rs.next()) {
          rs.close(); 
           sql = "INSERT INTO lab" + 
                  " (capacity, day, time, room, subject_id, user_id)" + 
                  " VALUES" + 
                  " (" +  capacity + "','" + 
                     " '"  +  day + "'," + 
                     " '"  +  time + "'," + 
                     " '"  + room + "','" + subject_id + "','" + user_id + "')"; 

          System.out.println(sql);
          int i = s.executeUpdate(sql); 
          if (i==1) {
            message = "Successfully a new lab class."; 
          } 
        } 
          s.close(); 
          con.close(); 
        } 
        catch (SQLException e) {
          message = "Error." + e.toString(); 
          error = true; 
        } 
        catch (Exception e) {
          message = "Error." + e.toString(); 
          error = true; 
        } 
        if (message!=null) {
          PrintWriter out = response.getWriter(); 
          out.println("<B>" + message + "</B><BR>"); 
          out.println("<HR><BR>"); 
        } 
        if (error==true) 
          sendRegistrationForm(request, response, true); 
        else 
          sendRegistrationForm(request, response, false); 
        sendPageFooter(response); 
      } 

      /** 
       * Send the HTML page header, including the title 
       * and the <BODY> tag 
       */ 
      private void sendPageHeader(HttpServletResponse response) 
        throws ServletException, IOException {
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
        out.println("<HTML>"); 
        out.println("<HEAD>"); 
        out.println("<TITLE>Create Lab Page</TITLE>"); 
        out.println("</HEAD>"); 
        out.println("<BODY>"); 
        out.println("<CENTER>"); 
      } 

      /** 
       * Send the HTML page footer, i.e. the </BODY> 
       * and the </HTML> 
       */ 
      private void sendPageFooter(HttpServletResponse response) 
        throws ServletException, IOException {
        PrintWriter out = response.getWriter(); 
        out.println("</CENTER>"); 
        out.println("</BODY>"); 
        out.println("</HTML>"); 
      }   
      /**Send the form where the user can type in 
       * the details for a new user 
       */ 
      private void sendRegistrationForm(HttpServletRequest request, 
        HttpServletResponse response, boolean displayPreviousValues) 
        throws ServletException, IOException {

        PrintWriter out = response.getWriter(); 
        out.println("<BR><H2>Create A Lab</H2>"); 
        out.println("<BR>Please enter the lab details."); 
        out.println("<BR>"); 
        out.println("<BR><FORM METHOD=POST>"); 
        out.println("<TABLE>"); 
        out.println("<TR>"); 
        out.println("<TD>Class Capacity</TD>"); 
        out.print("<TD><INPUT TYPE=TEXT Name=capacity"); 

        if (displayPreviousValues) 
          out.print(" VALUE=\"" + capacity + "\""); 

        out.println("></TD>"); 
        out.println("</TR>"); 
        out.println("<TR>"); 
        out.println("<TD>Day</TD>"); 
        out.print("<TD><INPUT TYPE=TEXT Name=day"); 

        if (displayPreviousValues) 
          out.print(" VALUE=\"" + day + "\""); 

        out.println("></TD>"); 
        out.println("</TR>"); 
        out.println("<TR>"); 
        out.println("<TD>Time</TD>"); 
        out.print("<TD><INPUT TYPE=TEXT Name=time"); 

        if (displayPreviousValues) 
          out.print(" VALUE=\"" + time + "\""); 

        out.println("></TD>"); 
        out.println("</TR>"); 
        out.println("<TR>"); 
        out.println("<TD>Room</TD>"); 
        out.print("<TD><INPUT TYPE=TEXT Name=room");
        if (displayPreviousValues) 
            out.print(" VALUE=\"" + room + "\"");
        out.println("></TD>");
        out.println("</TR>");
        out.println("<TR>");
        out.println("<TD>subject_id</TD>");
        out.print("<TD><INPUT TYPE=TEXT Name=subject_id");
        if (displayPreviousValues) 
            out.print(" VALUE=\"" + subject_id + "\"");
        out.println("></TD>");
        out.println("</TR>");
        out.println("<TR>");
        out.println("<TD>user_id</TD>");
        out.print("<TD><INPUT TYPE=TEXT Name=user_id");
        out.println("></TD>");
        out.println("</TR>");

        if (displayPreviousValues) 
        out.print(" VALUE=\"" + user_id + "\""); 
        out.println("</TD>"); 
        out.println("</TR>");

        out.println("<TR>"); 
        out.println("<TD><INPUT TYPE=RESET></TD>"); 
        out.println("<TD><INPUT TYPE=SUBMIT></TD>"); 
        out.println("</TR>"); 
        out.println("</TABLE>"); 
        out.println("</FORM>"); 
        out.println("<BR>"); 
        out.println("<BR>"); 
      }
      }
4

4 に答える 4

1

NumberFormatExceptionNULL または空の文字列を渡すとスローされますInteger.parseInt()

capacityフォーム データでパラメーターを渡しているかどうかを確認します。

変化する

capacity = Integer.parseInt(request.getParameter("capacity"));

id = Integer.parseInt(request.getParameter("id"));

String str = request.getParameter("capacity");
if(str!=null && str.length > 0){
   capacity = Integer.parseInt(str);
}
str = request.getParameter("id");
if(str!=null && str.length > 0){
   id = Integer.parseInt(str);
}
str = request.getParameter("user_id");
if(str!=null && str.length > 0){
   user_id = Integer.parseInt(str);
}
str = request.getParameter("subject_id");
if(str!=null && str.length > 0){
   subject_id = Integer.parseInt(str);
}

毎回のチェックを避けたい場合。データがない場合に -1 または 0 を返すメソッドを作成できます。

public int getIntParameter(String strParamval){
    int nRetVal=0;
    try{
            nRetVal=Integer.parseInt(strParamVal);
        }catch(NumberFormatException nfe){
            return 0;
        }
        return nRetVal;
}
于 2012-10-03T05:05:22.040 に答える
0

文字列を int に解析するたびに、この関数を使用します。getIntParameter は、パラメーターに文字または null が含まれている場合は 0 を返し、それ以外の場合は int 値を返します。

public int getIntParameter(String strParamval){

        int nRetVal=0;
        if((strParamval != null) && (!strParamval.matches("\\d*")))
            return nRetVal;
        try{
            nRetVal = Integer.parseInt(strParamval);
        }catch(NumberFormatException nfe){
        }
        return nRetVal;
    }

doPost関数では、

capacity = getIntParameter(request.getParameter("capacity"));
id = getIntParameter(request.getParameter("id")); 
user_id = getIntParameter(request.getParameter("user_id")); 
subject_id = getIntParameter(request.getParameter("subject_id")); 

それ以外の

capacity = Integer.parseInt(request.getParameter("capacity"));
id = Integer.parseInt(request.getParameter("id")); 
user_id = Integer.parseInt(request.getParameter("user_id")); 
subject_id = Integer.parseInt(request.getParameter("subject_id")); 
于 2012-10-03T05:34:29.303 に答える
0

に渡す引数の 1 つがparseInt()有効な数値ではありません。したがって、例外です。初期化していないidcapacityuserid有効な int を使用していないと思います。解析する前に確認してString.isEmpty()ください。

     String id =request.getParameter("id");
       try {
    if(!id.isEmpty()) {
      Integer.parseInt(id);
     }
         }
       catch(NFE ex) {
         ex.printStrackTrace();
      } 

また、String オブジェクトを返すことを覚えておいてrequest.getParameter("")ください。与えられたパラメーターが見つからない場合は、文字列のデフォルト値である null を返します。

     String id= request.getParameter("id")
    try {
    if(!id.isEmpty() && id!=null) {
      Integer.parseInt();
     }
         }
       catch(NFE ex) {
         ex.printStrackTrace();
      } 
于 2012-10-03T05:06:00.877 に答える
0

を使用して「user_id」を解析しているためですInteger.parseInt。その中にString値が必要ですが、null.

しかし、あなたがそれを試しているとき

user_id = Integer.parseInt(request.getParameter("user_id"));

それを確認してください

request.getParameter("user_id")

返っておりません null。が返されたnull場合、オブジェクトは Web ページのフォームから空白で送信されたためuser_id、オブジェクトで使用できないはずです。フォームの送信中に が空でないrequestことを確認してください。user_id

于 2012-10-03T05:07:37.107 に答える