lem*_*min 3 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这就是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);
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道我的代码是否正确,请告诉我.谢谢很多^^
您没有将某些内容传递给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; }
}
Run Code Online (Sandbox Code Playgroud)
基本连接管理器类,在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);
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
最后,在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
将此servlet映射url-pattern到/areasin,web.xml以便您可以通过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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16812 次 |
| 最近记录: |