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

我是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 fypjdbList = new ArrayList(); 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 fypjdbList = new ArrayList(); //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 fypjdbList = new ArrayList(); /** * @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 fypjdbList = new ArrayList();// 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。 你只需让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 list() throws SQLException { Connection connection = null; PreparedStatement statement = null; ResultSet resultSet = null; List areas = new ArrayList(); 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 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映射到web.xml/areasurl-pattern ,以便您可以通过http://example.com/contextname/areas调用它

/WEB-INF/areas.jsp看起来像这样,假设您要显示表中的区域:

  
${area.location} ${area.timezone}

也可以看看:

  • 初级和中级JSP / Servlet教程
  • 高级JSP / Servlet教程
  • DAO教程 (包含更高级/灵活的DAO示例)
  • JSP / Servlet的隐藏function

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

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

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

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

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

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