jsp / servlets从数组填充下拉框 [英] jsp/servlets filling a drop down box from an array

查看:117
本文介绍了jsp / servlets从数组填充下拉框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi我正在尝试创建一个表单,允许您为主题创建实验室。它有一个下拉框,您可以在其中选择与该用户相关的主题。然而,当我去加载页面,我得到这个错误 g.apache.jasper.JasperException:java.lang.NullPointerException ,与我正在使用的当前用户,他们应该有2个结果

hi all I'm trying to create a form that allows you to create a lab for a subject. It has a drop down box where you can select the subjects that are related to that user. However when I go to load the page i get this error g.apache.jasper.JasperException: java.lang.NullPointerException, with the current user that I'm using, they should have 2 results

这里是我的servlet完整

here is my servlet in full

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页



here is my jsp page

<%@ 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>


推荐答案

此代码有严重的安全漏洞。您正在接受用户的输入并将其传递到数据库查询中:

This code has a serious security flaw in it. You're taking input from the user and passing it into database queries unvetted:

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注入攻击。

使用预编译语句更加安全(更简洁):

It is much safer (and neater) to use prepared statements:

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 list1 list2 之前,你的try块,然后setAttribute与他们后捕捉。这样,当尝试中出现问题时,您将至少得到一个表单的空列表。

To avoid your NullPointerException, you could initialize list1 and list2 before your try block then setAttribute with them after the catch. This way you'll at least get an empty list for your form when something goes wrong in the try.

这篇关于jsp / servlets从数组填充下拉框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆