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

时间:2010-07-27 07:40:45

标签: java servlets jdbc

我是java新手,我遇到的问题是将类/ bean(存储在arraylist中)传递给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);
}

}

我不知道我的代码是否正确,请告诉我。谢谢很多^^

3 个答案:

答案 0 :(得分:6)

您不会将某些内容传递给servlet。你只需让servlet访问一些东西。

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

模型类,Area(无论你想要什么名称,只要它有意义),它应该只代表一个实体:

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; }
}

基本连接管理器类Database,这里只加载一次驱动程序并为连接提供一个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,这里放置了所有数据库交互方法:

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;
    }
}

最后,在servlet中初始化DAO一次并获取HTTP方法中的列表:

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);
        }
    }
}

将此servlet映射到url-pattern/areas的{​​{1}},以便您可以http://example.com/contextname/areas

调用它

假设您要在表格中显示区域,web.xml可能看起来像这样:

/WEB-INF/areas.jsp

另见:

答案 1 :(得分:1)

为什么要让不同模式的新手混淆! @OP - 更改main()方法以返回数据而不是void,并在servlet中为该类创建一个实例。

答案 2 :(得分:0)

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

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

从数据库检索数据的更好方法是创建数据访问对象(DAO)。这是一个仅包含访问数据库的代码的Java类。 DAO会为您检索数据,但不会自行存储数据(它不包含timezonelocation)。 DAO的概念在http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

解释

谷歌会在DAO上找到一些教程(我不能在这里发布链接,因为作为Stack Overflow的新成员我只能发布一个链接!)

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