使用jsp从数据库中获取数据 [英] fetching the data from data base by using jsp
问题描述
如何通过使用jsp作为下拉框从mssql服务器数据库中的状态表中获取状态
how to fetch the states from the the states table in mssql server db by using jsp as a drop down box
推荐答案
首先,创建一个用代码和名称(基本上与数据库表中的数据相同)表示状态的javabean.然后创建一个执行数据库交互任务的DAO类.然后创建一个Servlet类,该类从DAO检索列表,将其放入请求范围,并将请求转发到JSP.最后,使用 JSTL 的 c:forEach
To start, create a javabean representing a state with code and name (basically the same data as you have in the DB table). Then create a DAO class which does the database interaction task. Then create a Servlet class which retrieves the list from the DAO, puts it in the request scope and forwards the request to the JSP. Finally create a JSP file which displays the list using JSTL's c:forEach
.
状态Bean的基本示例:
Basic example of the state bean:
public class State {
private String code;
private String name;
// Add (generate) public getters and setters.
}
DAO类的基本示例:
Basic example of the DAO class:
public List<State> list() {
List<State> states = new ArrayList<State>();
// Do your JDBC thing here.
return states;
}
Servlet类的基本示例:
Basic example of the Servlet class:
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
List<State> states = stateDAO.list();
request.setAttribute("states", states);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
JSP文件的基本示例:
Basic example of JSP file:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<select name="state">
<c:forEach items="${states}" var="state">
<option value="${state.code}">${state.name}</option>
</c:forEach>
</select>
将url-pattern
上的servlet映射到您在web.xml
中的口味,然后通过浏览器调用该servlet.
Map the servlet on the url-pattern
to your taste in web.xml
and invoke this servlet by your browser.
To get more insights and ideas around the DAO pattern, you may find this article useful as well.
这篇关于使用jsp从数据库中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!