Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:如何将值从类/bean传递到servlet_Java_Servlets_Jdbc - Fatal编程技术网

Java:如何将值从类/bean传递到servlet

Java:如何将值从类/bean传递到servlet,java,servlets,jdbc,Java,Servlets,Jdbc,我是java新手,在将存储在arraylist中的类/bean的值传递到servlet时遇到问题。你知道我怎样才能做到吗?下面是我的代码 package myarraylist; public class fypjdbClass { String timezone; String location; public String getTimezone() { return timezone; } public void setTimezone(String timezone) {

我是java新手,在将存储在arraylist中的类/bean的值传递到servlet时遇到问题。你知道我怎样才能做到吗?下面是我的代码

package myarraylist;

public class fypjdbClass {

String timezone;
String location;

public String getTimezone() {
    return timezone;
}
public void setTimezone(String timezone) {
    this.timezone = timezone;
}
public String getLocation() {
    return location;
}


public void setLocation(String location) {
    this.location = location;
}

public fypjdbClass() {
    super();
    ArrayList<fypjdbClass> fypjdbList = new ArrayList<fypjdbClass>();
    this.timezone = timezone;
    this.location = location;
}

public static void main(String[] args) {


    //Establish connection to MySQL database
    String connectionURL = "jdbc:mysql://localhost/fypjdb";
    Connection connection=null;
    ResultSet rs;

    try {
         // Load the database driver
        Class.forName("com.mysql.jdbc.Driver");

        // Get a Connection to the database
        connection = DriverManager.getConnection(connectionURL, "root", ""); 
        ArrayList<fypjdbClass> fypjdbList = new ArrayList<fypjdbClass>();
        //Select the data from the database
           String sql = "SELECT location,timezone FROM userclient";
        Statement s = connection.createStatement();
        //Create a PreparedStatement
        PreparedStatement stm = connection.prepareStatement(sql);
        rs = stm.executeQuery();
        //rs = s.getResultSet();
        while(rs.next()){

            fypjdbClass f = new fypjdbClass(); 

            f.setTimezone(rs.getString("timezone"));
            f.setLocation(rs.getString("location"));

            fypjdbList.add( f);

        }



        for (int j = 0; j < fypjdbList.size(); j++) {
            System.out.println(fypjdbList.get(j));

          }
        //To display the number of record in arraylist
        System.out.println("ArrayList contains " + fypjdbList.size() + " key value pair.");


        rs.close ();
        s.close ();
        }catch(Exception e){
        System.out.println("Exception is ;"+e);
        }

}
}
这就是Servlet

package myarraylist;

public class arraylistforfypjServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public arraylistforfypjServlet() {
    super();
}

public static ArrayList<fypjdbClass> fypjdbList = new ArrayList<fypjdbClass>();

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */

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

    RequestDispatcher rd = request.getRequestDispatcher("/DataPage.jsp"); //You could give a relative URL, I'm just using absolute for a clear example.
    ArrayList<fypjdbClass> fypjdbList = new ArrayList<fypjdbClass>();// You can use any type of object you like here, Strings, Custom objects, in fact any object.
    request.setAttribute("fypjdbList", fypjdbList);
    rd.forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
    //processRequest(request, response);
    doGet(request,response);
}

}

我不知道我的代码是否正确,请告诉我。非常感谢^^

看起来您正试图将数据从数据库加载到servlet中的fypjdbList ArrayList中

它不起作用,因为servlet没有调用数据库代码。您的数据库代码位于fypjdbClass的主方法中;main方法通常由Java控制台或桌面应用程序使用,但不在javaservlet应用程序中使用

从数据库检索数据的更好方法是创建数据访问对象DAO。这是一个Java类,只包含访问数据库的代码。DAO为您检索数据,但不存储数据本身,因为它不包含时区或位置。DAO的概念解释如下:

谷歌会给你找到一些关于DAOs的教程,我不能在这里发布链接,因为作为Stack Overflow的新成员,我只能发布一个链接


编写servlet在学习Java时很有用,但是如果您想构建一个完整的网站,您可能会发现使用Spring框架的SpringMVC部分这样的框架更容易。Spring MVC提供了一个全面的分步教程,如果您是Java web开发新手,该教程非常有用。

您不需要将某些内容传递到servlet中。您只需让servlet访问某些内容

您应该去掉该主方法,并将数据库交互代码移动到DAO类中。我还为带有时区和位置的模型类提供了一个更敏感的名称,以大写字母开头。总之,您应该更新代码,使其看起来如下所示:

模型类,区域名称,只要有意义,它应该只表示单个实体:

public class Area {
    private String location;
    private String timezone;

    public String getLocation() { return location; }
    public String getTimezone() { return timezone; }

    public void setLocation(String location) { this.location = location; }
    public void setTimezone(String timezone) { this.timezone = timezone; }
}
基本连接管理器类,即数据库,在这里您只需加载一次驱动程序,并为连接提供一个getter:

public class Database {
    private String url;
    private String username;
    private String password;

    public Database(String driver, String url, String username, String password) {
        try { 
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Driver class is missing in classpath", e);
        }
        this.url = url;
        this.username = username;
        this.password = password;
    }

    public Connection getConnection() {
        return DriverManager.getConnection(url, username, password);
    }
}
DAO类,AreaDAO,这里您放置了所有DB交互方法:

public class AreaDAO {
    private Database database;

    public AreaDAO(Database database) {
        this.database = database;
    }

    public List<Area> list() throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Area> areas = new ArrayList<Area>();

        try {
            connection = database.getConnection();
            statement = connection.prepareStatement("SELECT location, timezone FROM userclient");
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Area area = new Area();
                area.setLocation(resultSet.getString("location"));
                area.setTimezone(resultSet.getString("timezone"));
                areas.add(area);
            }
        } finally {
            if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
            if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
            if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
        }

        return areas;
    }
}
另见: 包含更多高级/灵活的DAO示例
为什么要用不同的模式来混淆新手呢!
@OP-更改main方法以返回数据,而不是void,并在servlet中为该类创建实例。

将数组存储在请求中,在servlet doGet或doPost中执行该方法后,请求被清除。为什么不在会话中保存它?request.getSession.setAttribute…回答得很好!您的代码清楚地揭示了MVC模式。感谢您为初学者提供如此优秀的答案
public class AreaServlet extends HttpServlet {
    private AreaDAO areaDAO;

    public void init() throws ServletException {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/dbname";
        String username = "user";
        String password = "pass";
        Database database = new Database(driver, url, username, password);
        this.areaDAO = new AreaDAO(database);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        try {
            List<Area> areas = areaDAO.list();
            request.setAttribute("areas", areas);
            request.getRequestDispatcher("/WEB-INF/areas.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException("Cannot retrieve areas", e);
        }
    }
}
<table>
    <c:forEach items="${areas}" var="area">
        <tr>
            <td>${area.location}</td>
            <td>${area.timezone}</td>
        </tr>
    </c:forEach>
</table>