Reputation: 2467
I'm learning how to write websites in Java and my question is what is the proper way of connecting to database?
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.
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.
Upvotes: 0
Views: 1423
Reputation: 648
Whatever thesaurier_rex said is right.
But I'm just giving some more layers
UI(your jsp/html)
you can get More information here
Upvotes: 0
Reputation: 1526
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:
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.
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)
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.
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.
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.
Upvotes: 1