Java:如何将值从类/bean 传递给 servlet
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3341563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java:how to pass value from class/bean to servlet
提问by lemin
i am new to java, i'm having problem passing value from a class/bean (which are stored in arraylist) to servlet. any idea how can i achieve that? below is my code.
我是 Java 新手,我在将值从类/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);
}
}
}
And this is the Servlet
这是 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);
}
}
i dont know if my code is right, pls advise me. thanks lot ^^
我不知道我的代码是否正确,请给我建议。非常感谢^^
回答by BalusC
You don't pass something into a servlet. You just let the servlet access something.
您不会将某些内容传递给 servlet。您只需让 servlet 访问某些内容即可。
You should get rid of that main()method and move the database interaction code into a DAO class. I'd also give the model class (with timezone and location) a more sensitive name starting with an uppercase. So all with all, you should update the code so that it look something like the following:
您应该摆脱该main()方法并将数据库交互代码移动到 DAO 类中。我还会为模型类(带有时区和位置)提供一个以大写开头的更敏感的名称。总之,您应该更新代码,使其看起来类似于以下内容:
Model class, the Area(name it whatever you want, as long as it makes sense), it should just represent a single entity:
模型类,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; }
}
Basic connection manager class, the Database, here you load the driver just once and provide a getter for the connection:
基本的连接管理器类,在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 class, the AreaDAO, here you put all DB interaction methods:
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;
}
}
Finally, in the servlet initialize the DAO once and obtain the list in the HTTP method:
最后,在 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);
}
}
}
Map this servlet on an url-patternof /areasin web.xmlso that you can invoke it by http://example.com/contextname/areas
将此 servlet 映射url-pattern到/areasin 上,web.xml以便您可以通过http://example.com/contextname/areas调用它
The /WEB-INF/areas.jspcan look like something this, assuming that you want to display the areas in a table:
该/WEB-INF/areas.jsp可以像这样的东西,假设你想在表格中显示的区域:
<table>
<c:forEach items="${areas}" var="area">
<tr>
<td>${area.location}</td>
<td>${area.timezone}</td>
</tr>
</c:forEach>
</table>
See also:
也可以看看:
- Beginning and intermediate JSP/Servlet tutorials
- Advanced JSP/Servlet tutorials
- DAO tutorial(contains more advanced/flexible DAO examples)
- Hidden features of JSP/Servlet
- 初级和中级 JSP/Servlet 教程
- 高级 JSP/Servlet 教程
- DAO 教程(包含更高级/灵活的 DAO 示例)
- JSP/Servlet 的隐藏特性
回答by gekrish
Why to confuse a newbie with different patterns! @OP - Change your main() method to return data instead of void and create an instance for that class in the servlet.
为什么要用不同的模式混淆新手!@OP - 更改您的 main() 方法以返回数据而不是 void 并在 servlet 中为该类创建一个实例。
回答by gutch
It looks like you are trying to load data from a database into the fypjdbListArrayList in your servlet.
看起来您正在尝试将数据库中的数据加载到servlet 中的fypjdbListArrayList 中。
It isn't working because your servlet is not calling the database code. Your database code is in the mainmethod of fypjdbClass; the mainmethod is generally used by Java console or desktop applications but not in a Java servlet application.
它不起作用,因为您的 servlet 没有调用数据库代码。你的数据库代码在mainfypjdbClass的方法中;该main方法通常由 Java 控制台或桌面应用程序使用,但不在 Java servlet 应用程序中使用。
A better way to retrieve data from the database is to create a Data Access Object (DAO). This is a Java class that contains only code to access the database. The DAO retrieves data for you, but does not store data itself (it would not contain timezoneor location). The concept of a DAO is explained at http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
从数据库中检索数据的更好方法是创建数据访问对象 (DAO)。这是一个 Java 类,只包含访问数据库的代码。DAO 为您检索数据,但不存储数据本身(它不会包含timezone或location)。在http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html解释了 DAO 的概念
Google will find you a number of tutorial on DAOs (I can't post the links here because as a new member of Stack Overflow I can only post one link!)
Google 会为您找到许多有关 DAO 的教程(我无法在此处发布链接,因为作为 Stack Overflow 的新成员,我只能发布一个链接!)
Writing servlets is useful when learning Java, but if you want to build a full website you will probably find it easier to use a framework like the Spring MVC (part of the Spring Framework). Spring MVC has a comprehensive step-by-step tutorial available which is very useful if you're new to Java web development.
在学习 Java 时编写 servlet 很有用,但是如果您想构建一个完整的网站,您可能会发现使用 Spring MVC(Spring 框架的一部分)之类的框架更容易。Spring MVC 有一个全面的分步教程,如果您不熟悉 Java Web 开发,这将非常有用。

