java - jsp/servlets 从数组中填充下拉框

标签 java database forms jsp servlets

大家好,我正在尝试创建一个允许您为某个主题创建实验室的表单。它有一个下拉框,您可以在其中选择与该用户相关的主题。但是,当我加载页面时出现此错误 g.apache.jasper.JasperException: java.lang.NullPointerException,对于我正在使用的当前用户,他们应该有 2 个结果

这是完整的 servlet

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 java.util.ArrayList;

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 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 {  


    HttpSession session = request.getSession(true);

    String sql = "SELECT id,name" +
              " FROM subject " +
            " WHERE user_id="+(Integer)session.getAttribute("id");

    try{
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
        System.out.println("connected");

        Statement stmt = con.createStatement();
          ResultSet res = stmt.executeQuery(sql);
          System.out.println(res);
          ArrayList<String> list1 = new ArrayList<String>();
          ArrayList<String> list2 = new ArrayList<String>();
          if (res.next()){
              do{
                   list1.add(res.getString(1));
                   list2.add(res.getString(2));
                   System.out.print(list1.add(res.getString(1)));
                   System.out.print(list2.add(res.getString(2)));

              }while(res.next());
          System.out.println("Outside");
          String[] arr1 = list1.toArray(new String[list1.size()]);
          String[] arr2 = list2.toArray(new String[list2.size()]);
          System.out.println(list1);
          request.setAttribute("res1", arr1);
          request.setAttribute("res2", arr2);
          request.setAttribute("user_id", user_id);

          }

    }catch (SQLException e) {
    } 
    catch (Exception e) {
    } 

      sendRegistrationForm(request, response, false); 
      sendPageHeader(response);
    } 

    /**Process the HTTP Post request*/ 
    public void doPost(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException {
      sendPageHeader(response); 
      HttpSession session = request.getSession(true);
      capacity = Integer.parseInt(request.getParameter("capacity"));

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

      System.out.print(user_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."; 
            response.sendRedirect("Lecturer_labs.jsp");
          } 
        } 
          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); 
      } 

      }

这是我的jsp页面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
    <title>Mars University Lab System</title>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen">
</head>

<body>
<jsp:include page="headerLecturer.jsp"/>


<tr>
<td>
</td>
</tr>

<tr>
<td>
<div id = "centrecontent">
<br>
<h3>Create Labs</h3>

<%
    String[] list1 = (String[])request.getAttribute("res1");
    String[] list2 = (String[])request.getAttribute("res2"); %>

        <form name ="createLabs" ACTION="CreateLab" method="post">
        Capacity: <input type="text" name="capacity"/><br />
        Day: <input type="text" name="day"/><br />
        Time: <input type="text" name="time"/><br />
        Room: <input type="text" name="room"/><br />
        <select name="subject_id">
        <%
        for(int i=0; i<list1.length; i++)  
        { 
        out.println("<option value="+list1[0]+"> "+list2[i]+" </option>");

        } 
        %>


        </select>
        <input type=SUBMIT value="Submit" name="Submit" />

    </form>
</div>

<jsp:include page="footer.jsp"/>


</body>

</html>

最佳答案

此代码中存在严重的安全漏洞。您正在从用户那里获取输入并将其传递到未经审查的数据库查询中:

day = request.getParameter("day"); 
time = request.getParameter("time"); 
room = request.getParameter("room"); 

sql = "INSERT INTO lab" + 
              " (capacity, day, time, room, subject_id, user_id)" + 
              " VALUES" + 
              " ('" +  capacity + "'," + 
                 " '"  +  day + "'," + 
                 " '"  +  time + "'," + 
                 " '"  + room + "','" + subject_id + "','" + user_id + "')"; 
int i = s.executeUpdate(sql);

这可以利用 SQL Injection攻击。攻击者可能会通过向您的表单传递意想不到的内容来破坏您的数据库。

使用准备好的语句更安全(也更整洁):

sql = "INSERT INTO lab" + 
              " (capacity, day, time, room, subject_id, user_id)" + 
              " VALUES (?, ?, ?, ?, ?, ?)"; 
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setInt(1,   capacity );
// set the rest.
int i = stmt.executeUpdate(sql);

为了避免 NullPointerException,您可以在 try block 之前初始化 list1list2,然后在 catch 之后用它们设置属性。这样,当尝试出现问题时,您至少会得到一个空列表。

关于java - jsp/servlets 从数组中填充下拉框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12767069/

相关文章:

javascript - 我应该在前端还是后端处理 html 表单验证?

java - 在 scriptlet 中访问 struts bean 属性

Java Google Cloud Endpoints API UTF-8 Unicode 中文字符生成 Android 客户端?

ASP.NET - app_data 文件夹中 SQL Server 数据库的性能影响

c# - 不使用类 System.Windows.Forms.Form 创建一个窗口?

javascript - 多部分 jQuery 验证

java - 如何将网页中的小程序包含在不同的目录中?

java - 如何为JavaFX异常对话框的按钮设置操作事件

c# - SQLite 数据源路径奇怪的问题?

mysql - 将图像从数据库添加到谷歌地图信息窗口