Java:如何将值从类/bean传递给servlet
Posted
技术标签:
【中文标题】Java:如何将值从类/bean传递给servlet【英文标题】:Java:how to pass value from class/bean to servlet 【发布时间】:2011-03-21 11:19:39 【问题描述】:我是 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);
我不知道我的代码是否正确,请告诉我。非常感谢^^
【问题讨论】:
您将数组存储在请求中,在 servletdoGet()
或 doPost()
中执行该方法后,请求被清除。为什么不将其保存在 Session 中? (request.getSession().setAttribute(....)
.
【参考方案1】:
您不会将某些内容传递给 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
,这里放了所有的 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;
最后,在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 映射到 web.xml
中的 /areas
的 url-pattern
上,以便您可以通过 http://example.com/contextname/areas 调用它
/WEB-INF/areas.jsp
可能看起来像这样,假设您想在表格中显示区域:
<table>
<c:forEach items="$areas" var="area">
<tr>
<td>$area.location</td>
<td>$area.timezone</td>
</tr>
</c:forEach>
</table>
另见:
Beginning and intermediate JSP/Servlet tutorials Advanced JSP/Servlet tutorials DAO tutorial(包含更高级/灵活的 DAO 示例) Hidden features of JSP/Servlet【讨论】:
很好的答案!您的代码清楚地揭示了 MVC 模式。感谢您为初学者发布如此出色的答案【参考方案2】:您似乎正在尝试将数据从数据库加载到您的 servlet 中的 fypjdbList ArrayList 中。
它不起作用,因为您的 servlet 没有调用数据库代码。您的数据库代码在 fypjdbClass 的main
方法中; main
方法通常由 Java 控制台或桌面应用程序使用,但在 Java servlet 应用程序中不使用。
从数据库中检索数据的更好方法是创建数据访问对象 (DAO)。这是一个仅包含访问数据库的代码的 Java 类。 DAO 为您检索数据,但不存储数据本身(它不会包含timezone
或location
)。 DAO 的概念在http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
Google 会为您找到许多关于 DAO 的教程(我无法在此处发布链接,因为作为 Stack Overflow 的新成员,我只能发布一个链接!)
在学习 Java 时编写 servlet 很有用,但如果您想构建一个完整的网站,您可能会发现使用像 Spring MVC(Spring 框架的一部分)这样的框架会更容易。 Spring MVC 提供了一个全面的分步教程,如果您是 Java Web 开发新手,这将非常有用。
【讨论】:
【参考方案3】:为什么要让不同模式的新手混淆! @OP - 更改您的 main() 方法以返回数据而不是 void 并在 servlet 中为该类创建一个实例。
【讨论】:
以上是关于Java:如何将值从类/bean传递给servlet的主要内容,如果未能解决你的问题,请参考以下文章