如何创建自己创建的构造函数的对象

时间:2015-04-28 15:54:09

标签: java list jsp object constructor

我想使用我创建的对象

1.我从MySQL检索数据并将其放入我的班级类型的链表中 2.我创建了我的类,声明了对象并创建了构造函数 3.现在我想从变量中获得价值

这是我正在尝试的代码

String query = "SELECT * FROM request";
    try (
        Statement st = connection.createStatement();
        ResultSet rs = st.executeQuery(query);)
    {
        while (rs.next())
        {
            /*String f_name = rs.getString("f_name");
            String l_name = rs.getString("l_name");
            String email = rs.getString("email");
            String contact = rs.getString("contact");
            result += (f_name+",.,"+l_name+",.,"+email+",.,"+contact); */
            List<Request> get_request= new ArrayList<Request>();
            get_request.add(new Request(rs));
        }
    }

我想要存储的课程

package com.Utility.umair;
import java.sql.ResultSet;
public class Request {
String f_name;
String l_name;
String email;
String contact;
String Organization;
public Request(ResultSet rs)
    {
        try
        {
            f_name = rs.getString("f_name");
            l_name = rs.getString("l_name");
            email = rs.getString("email");
            contact = rs.getString("contact");
            Organization = rs.getString("organization");
        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

我想要检索我的数据

<%@page import="com.Utility.umair.Request"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" 
    import = "com.request_handling.umair.DbLayer.RequestHandlingDb" 
    import = "java.io.IOException"
    import = "java.sql.SQLException" %>
   <%
   List<Request> string  = RequestHandlingDb.ViewRole();
   System.out.println(string);
   %>
<!DOCTYPE html>
<html>

我不知道如何在jsp或我的错误方式中获取数据

1 个答案:

答案 0 :(得分:1)

你做错了。

  1. 您不能将对象添加到空对象。

    列表get_request = null;                     get_request.add(new Request(rs));

  2. 创建新对象。在您不分配之前,新对象永远不会给您任何价值。

    请求re = new Request();    的System.out.println(re.f_name);

  3. 理想情况下应该是

    public class Whatever{
    
    public static List<Request> getResults(){
    String query = "SELECT * FROM request";
    List<Request> get_request= new ArrtList<Request>;
            try {
                Statement st = connection.createStatement();
                ResultSet rs = st.executeQuery(query);
                while (rs.next())
                {
                    /*String f_name = rs.getString("f_name");
                    String l_name = rs.getString("l_name");
                    String email = rs.getString("email");
                    String contact = rs.getString("contact");
                    result += (f_name+",.,"+l_name+",.,"+email+",.,"+contact); */
    
                    get_request.add(new Request(rs));
                }
            }
            catch(Exception e){}
            return get_request;
    
    }
    

    在你的jsp中按如下方式获取

    Whatever.getResults()