- 论坛徽章:
- 0
|
What way is right to invok ResultSet form JavaBean in Servle
[这个贴子最后由cinc在 2002/10/30 00:16am 编辑]
You can use DAO Pattern and MVC Framework:
Servlet, JSP ->; JavaBean and DAO ->; Database
Servlet or JSP is the View layer of MVC Framework.
It must not contain any codes that directly access database.
JavaBean and DAO is the Model layer of MVC Framework.
JavaBeans is the representation of table in database
You can place business code in DAO Object, including code communicating with database.
For example:
If you have a table in database called : article
create table article(
id integer,
title char(10),
content char(30)
)
1.Model layer : JavaBean and DAO Object
You can create a JavaBean to represent an article in database
public class Article{
int id;
String title;
String content;
public void set...(){
}
public ... get...(){
}
...
}
we ususally use DAO Object to access database, for article, we create:
public class ArticleDAO{
/**
* find one article, return an article
*/
public Article findById(int id){
// execute SQL : select title, content from article where id = 10;
Article article = new Article();
article.setId(id);
article.setTitle(title);
article.setContent(content);
return article;
}
/**
* find all the articles which contains the keyword, return a vector
* containing these articles
*/
public Vector findByKeyword(String keyword){
Vector resultVector = new Vector();
// execute SQL : select title, content from article where content like "%keyword%";
while (resultset.next){
Article article = new Article();
article.setId(id);
article.setTitle(title);
article.setContent(content);
resultVector.add (article);
}
return resultVector;
}
}
2.View Layer : servlet or jsp
/**
* user want to find all the article that contain the keyword
*/
public void doGet(...){
String keyword = getParameter("keyword";
ArticleDAO articleDAO = new ArticleDAO();
Vector resultVector = articleDAO.findByKeyword(keyword);
// display each article in resultVector
}
DAO Pattern is a widely used pattern in web development of servlet and jsp
more detail:
http://java.sun.com/blueprints/patterns/DAO.html
Other consideration about design pattern:
use Factory to Create DAO Object
public class DAOFactory{
public ArticleDAO getArticleDAO(){
...
}
...
}
Factory is an Singleton
:) |
|