JSP-连接到数据库 [英] JSP - connecting to a database

查看:68
本文介绍了JSP-连接到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习如何用Java编写网站,我的问题是连接数据库的正确方法是什么?

I'm learning how to write websites in Java and my question is what is the proper way of connecting to database?

在我看来,从JSP级别连接到数据库(网络上的许多教程都建议)是一个非常糟糕的主意,因为JSP应该仅用于视图,而不用于逻辑.

Connecting to database from JSP level (as many tutorials around the web suggest) is in my opinion a very bad idea as JSP should be only used for a view, not for logic.

我应该创建一个用于从数据库获取数据的类吗?并以某种方式使用"useBean"标签对其进行初始化?如果数据库连接失败,应该如何处理异常?我非常了解Java SE,但是在Java EE中我是一个完整的初学者,因此任何建议和示例代码都将非常有帮助.

Should I create a class for obtaining data from database? And initialize it somehow using "useBean" tag? How should I handle exception in case of database connection fail? I know Java SE well but in Java EE I'm a complete beginner so any advice and sample code would be very helpful.

推荐答案

您的直觉是正确的.即使可能,也不应将JSP直接连接到数据库.大多数程序由几层组成.例如:

Your intuition is right. You should not connect from the JSP directly to the database, if that is even possible. Most programs consist of several layers. For example:

您拥有DAO(数据访问对象),它的职责之一是:从数据库中获取数据.它不在乎该数据会发生什么,但会检索它.

You have the DAO (Data Access Object) which has one responsibility: getting data from the database. It does not care what happens with that data, but it retrieves it.

然后,您将拥有执行业务逻辑,计算等的服务层.它不在乎数据来自何处,它只是假设数据在那儿(但它是从dao来的)

Then you have the service layer which does business logic, calculations, etc. It does not care where the data comes from, it just assumes the data is there (but it is from the dao)

然后,您将拥有一个用户界面层,该层准备要在JSP中使用的信息,执行JSP无法完成的转​​换,过滤掉不需要的信息,等等.而且,它又一无所知.数据来自,只是从服务层获取.

Then you have the user interface layer which prepares the information to be used in JSP's, does transformations that the JSP cannot do, filter out information that is not required, etc. And once again, it does not know anything about where the data comes from, it just gets it from the service layer.

我建议您像这样构建您的应用程序.这也使测试变得更加容易,因为您只需要测试数据库而不关心UI,或者只测试UI而不关心DB.大多数严肃的应用程序都是这样构成的,尽管通常涉及的层甚至更多.

I would suggest that you build your application like this. It makes it also easier to test, because you only have to test the DB and not care about the UI, or only test the UI and not care about the DB. Most serious applications are structured like this, although there are often even more layers involved.

请注意,实际上并不需要构建DAO层,像JPA或Hibernate或Spring Data这样的系统可以生成其中的大部分.

Note that it is not required to actually build the DAO layer, systems like JPA or Hibernate or Spring Data can generate most of it.

这篇关于JSP-连接到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆