I have a general question about using Servlet and JDBC.
For instance, I have a class called MyDatabaseManager, which provides functions
public boolean updateUser(User user) {...}
public boolean deleteUser(User user) {...}
public boolean inserUser(User user){...}
, these functions will access and manipulate the Database.
My question is on the Servlet implementation. I am using three Servlets (UpdateUserServlet,InsertUserServlet and DeleteUserServlet) at the moment and each Servlet calls the MyDatabaseManager instance (only one instance here, using Singleton pattern) function. (For example, UpdateUserServlet calls MyDatabaseManager.updateUser ...).
I think this is the most straightforward way of using Servlet and Database. But I am not sure if this is the correct way of doing it. For example, how is this implemented in the industry world.
People don't really use servlets directly nowadays, they use frameworks that allow you to simplify your work, but if you really want to use servlets, you can make all actions in a single one, using the other methods, doPut, doDelete and even creating your own methods. Here's a sample of how you would do it:
public abstract class BaseServlet extends HttpServlet {
#Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String method = request.getParameter("_method");
if ("form".equals(method)) {
this.doForm(request, response);
} else {
if ("delete".equals(method)) {
this.doDelete(request, response);
} else {
super.service(request, response);
}
}
}
protected void doForm(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
throw new UnsupportedOperationException();
}
}
As you can see, this Servlet uses a special field _method on forms to decide what special method to call, if the _method is not available it's going to use the usual service method and is going to call doGet or doPost.
And here's how an implementation for this servlet would look like:
public class UsersServlet extends BaseServlet {
private UsersRepository cadastro = new UsersRepository();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setAttribute("usuarios", cadastro.list());
req.getRequestDispatcher("/usuarios/listar.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
User usuario = this.getUser(req);
usuario.setNome(req.getParameter("nome"));
usuario.setEmail(req.getParameter("email"));
usuario.setSenha(req.getParameter("senha"));
this.cadastro.persist(usuario);
resp.sendRedirect(req.getContextPath() + "/usuarios");
}
protected User getUser(HttpServletRequest req) {
User usuario;
if (req.getParameter("id") == null) {
usuario = new Usuario();
} else {
Long id = new Long(req.getParameter("id"));
usuario = this.cadastro.search(id);
}
return usuario;
}
#Override
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
User usuario = this.getUser(req);
this.cadastro.remover(usuario);
resp.sendRedirect(req.getContextPath() + "/usuarios");
}
#Override
protected void doForm(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
User usuario = this.getUser(request);
request.setAttribute("usuario", usuario);
request.getRequestDispatcher("/usuarios/form.jsp").forward(request,
response);
}
}
This way you can make it all in a single servlet.
Difficult to answer because there are hundreds of design patterns out there! I know a good one about Database management is called DAO (data access objects). I use this one a lot. I advice you to take a look.
Don't get me wrong, a Singleton to hold your Manager is a good idea. Pretty much that's what I usually do too. However, usually I have a DAOFactorySingleton which pretty much have the responsibility to generate all classes DAO in my app and this factory is good because I can have some DataSource rules that this factory just poll from somewhere and inject in my DAO! So, pretty much, each DAO doesn't have to care about things like JDBC connection!
Follow 2 links to explain more about DAO!
http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
http://community.jboss.org/wiki/GenericDataAccessObjects
The second one is to use with hibernate! you can read it and is not mandatory using just with hibernate. I really like that second one, more complex though.
This is surely a matter of design choice, you can adopt a framework like Spring, Struts etc.. which make this much easier. Alternatively if you want to use the classic servlet request/response pattern, I will suggest creating a parent servlet which intercepts request and passes it on to the right method to perform the request.
Additionally you have a choice to various ORM solutions like Hibernate, JPA etc.. which you can use to handle your database access operations. Yet if you choose to stick to the classic JDBC calls, you can use Filters and Handlers to decide which calls to provide wrap database connection and operation against.
Singleton on the Database class sounds good, especially as it seems to contain update/delete/insert code.
If you're using Connection Pools, make sure you Singleton the DataSourceFactory.
Many in the industry use ORM + Dependency Injection framework + transaction manager + database pooling libraries, for example Hibernate (ORM) + Spring DI (Dependency Injection) + Spring transaction manager (transaction manager) + Apache DBCP (DB connection pooling).
Sometimes when the use of ORM cannot be justified (e.g. very simple DB schema, ORM performance overhead is prohibitive due to the nature of the app. etc.), developers might use raw JDBC. Many would still use dependency injection and DB connection pooling.
It is very rare that the use of dependency injection or DB connection pooling cannot be justified. I.e., unless it is a very rare, special app., developers in the industry do use dependency injection framework and DB connection pooling.
In this case the state that needs to be managed is managed by the DB connection pooling framework, so you should not have to worry about state management or thread safety (as long as you don't share anything between different threads yourself and follow the API of the DB connection pool framework). I.e., you won't need a singleton. If you implement your own DB connection pool, then using a singleton would make sense.
If a developer doesn't want to use any framework (e.g. creating a very simple tool), then many would just open a connection every time (for each thread). In this case, you again don't need to manage any state so you won't need a singleton.
In the industry world, we are all for simplicity. For example, for user interaction from browser, to server, to a persistence storage (database), we follow these approaches.
An MVC pattern, first and foremost. This would allow us to totally not write a Servlet for each user interaction from browser to server. What this allows us to do is to do the following:
Allow the controller to handle user request and link it to our user action (our model). This model allows us to write business logic to respond to user data.
In today's Java World, Frameworks exists that meets our MVC requirements. The one that comes out the Java box is JSF (JavaServer Faces).
For backend, we definitely use databases, but we are clever too and use ORM (Object Relational Mapping) to model our real-world problem into an Object model and how to best persist (store) these object models. Some usesERM (Entity-Relational Modelling) to design a semantic data model.
In the middle, the business logic, we add a service (as the business logic layer) doesn't want to care about where to read/write data, as long as they can see the data it wants. For this, a Service layer is added that facilitates this. In essence we have this effect.
public class ActionServlet extends HttpServlet {
//Action registration
public void init() {
ActionMapping mapping = .....; //some instatiation
mapping.setAction("/userRegistration", UserRegistrationAction.class);
//Save it in Application Scope
getServletContext().setAttribute("actionConfig", mapping);
}
private void doAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
String path = request.getPathInfo();
Action action = ((ActionMapping)getServletContext().getAttribute("actionConfig")).getAction(path);
if (action == null) {
throw new Exception("No action of '" + path + "' found.");
}
action.execute(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
doAction(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
doAction(request, response);
}
}
public abstract class Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
protected void dispatch(HttpServletRequest request, String path) {
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
}
}
public class UserRegistrationAction extends Action {
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//Business Logic goes here...
//Call DAO,
UserRegistrationDAO dao = ; //Some DAO instantation
User user = createUserFromForm(request);
dao.save(user);
dispatch(request, "success");
}
}
As for persistence, Java 5 & higher comes with JPA. You can use any form of ORM that you want, depending on your project scope. There's Hibernate (which also supports JPA) or if you want to, write your own DAO.
One more thing, all these processes are tedious to glue together. Fortunately, we have frameworks that helps us make our beautiful example above much easier. Frameworks like JBoss Seam does this and it fully uses Java specifications. For now, go for the simple design models and MVC (for learning purposes). As you get accustomed to the architecture, use frameworks.
Related
I'm super new to java web application development. Working on basic Todos app. So far app is working fine. I wish to add dynamic url routes like updateTodos, deleteTodos to existing path.
Expected behavior as shown below
/todos
*render todos list*
/todos/update
*render updateTodos.jsp*
/todos/delete
*render deleteTodos.jsp*
Below is my code
#WebServlet(urlPatterns = "/todos")
public class UserTodos extends HttpServlet {
private TodoService todoService = new TodoService();
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
if(request.isRequestedSessionIdValid()){
request.setAttribute("userName", request.getParameter("userName"));
request.setAttribute("allTodos", todoService.retrieveTodos());
request.getRequestDispatcher("WEB-INF/views/todos.jsp").forward(request, response);
}else{
response.sendRedirect("/login");
}
}
}
My understanding is so far that the annotation #WebServlet triggers the class file based on route defined. Can I achieve the above with a single class file?
Something like being done in JS web-framework Express-JS
If I sum-up my whole query is - Is it possible to multiple doGet and doPost methods in a single class file which will be executed based on user's URL accessed?
Update
I was able to achieve this, not sure whether this is correct implementation or not :/
I read about ControllerServlet usage in affablebean tutorial for Java EE 6, by Oracle.
It ends up with a servlet handling a lot of different URL requests, like this:
#WebServlet(name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/category",
"/addToCart",
"/viewCart",
"/updateCart",
"/checkout",
"/purchase",
"/chooseLanguage"})
public class ControllerServlet extends HttpServlet {
#EJB
private CategoryFacade categoryFacade;
#EJB
private OrderManager orderManager;
#Override
public void init() throws ServletException {
// store category list in servlet context
getServletContext().setAttribute("categories", categoryFacade.findAll());
}
/**
* Handles the HTTP <code>GET</code> method.
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/category")) {
// get categoryId from request
String categoryId = request.getQueryString();
if (categoryId != null) {
// get selected category
Category selectedCategory = categoryFacade.find(Short.parseShort(categoryId));
// place selected category in request scope
request.setAttribute("selectedCategory", selectedCategory);
// get all products for selected category
Collection<Product> categoryProducts = selectedCategory.getProductCollection();
// place category products in request scope
request.setAttribute("categoryProducts", categoryProducts);
}
// if cart page is requested
} else if (userPath.equals("/viewCart")) {
// TODO: Implement cart page request
userPath = "/cart";
// if checkout page is requested
} else if (userPath.equals("/checkout")) {
// TODO: Implement checkout page request
// if user switches language
} else if (userPath.equals("/chooseLanguage")) {
// TODO: Implement language request
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
System.out.println("Redirecting to : "+url);
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
I wonder if it is good practice for a Java EE project? I'm thinking about adopting Java EE as the framework for a project, which involves a small team of programmers. I think this ControllerServlet is encouraging them to put a lot of business logic inside. The class is expected to grow terribly long with a lot of if/else if... in future.
So what would be your recommendation about such a ControllerServlet to work in a big project?
You are correct in thinking that the controller servlet will quickly grow to be unmanageable if you are handling many different actions. You'll wind up with a huge set of if or case statements following the naive approach you sketched out.
A typical solution would be a front controller pattern that dispatches url mappings to other code that actually handles the requests. There are many relatively straight forward solutions to do this (someone mentioned the command pattern) and it's a key part of most web frameworks. I would probably not write my own front controller in 2016. What with the ease of standing up annotation based servlets, I would consider structuring a very simple application (like a microservice) around a single action per servlet; handling as many of the http methods as necessary: DELETE, PUT, GET...
However, you are also probably going to need additional features such as templating, reusable UI components, fancy url parameter handling, object to json mapping (and the reverse), sub resource mapping, content negotiation, authorization, etc. To the extent that you do, consider one of the numerous java EE technologies that you can apply to the problem (JAX-RS, JSF, JSR 371) and even more numerous implementations of each.
If you exposing an api I'd look at a JAX-RS implementation like jersey For a certain kind of application that might suffice: perhaps a single page web application communicating with the back end via ajax calls.You could serve your static content with nginx for apache. For full-blown frameworks you can choose a component based approach that implements the JSF standard or an action based one that implements the mvc1 (JSR 371) spec. You can read about the differences here: https://blogs.oracle.com/theaquarium/entry/why_another_mvc_framework_in
You mentioned choosing between JSF and spring mvc, The former is component based, the latter is action based. There is currently only one implementation of JSR 371, Ozark, the reference. If this distinction is important for your choice then you might be hampered by the lack of JSR 371 implementations. But it really does seem to me that the action based approach is the future.
I'm trying to share a session between a liferay portlet and a servlet, running in the same WAR.
I'm setting the attribute like this in the LoginPostAction (Hook):
#Override
public void run(HttpServletRequest request, HttpServletResponse response) throws ActionException {
Gebruiker g = new Gebruiker();
request.getSession().setAttribute("gebruiker", gebruiker);
}
Trying to get this Gebruiker object in my servlet, through an AJAX-request:
#RequestMapping(value="/haalContactGegevens", method = RequestMethod.POST)
public #ResponseBody ContactGegevensMessage getContactGegevens(HttpServletRequest request, HttpServletResponse response) {
Gebruiker gebruiker = (Gebruiker)request.getSession(true).getAttribute("gebruiker");
}
But here my 'Gebruiker-object' stays null.
What am I doing wrong?
thx
Easy: The LoginPostAction is handled by Liferay (even though technically implemented in your webapp's context/classloader. However, if you look at the httpServletRequest's context path, it's Liferay's.
When you implement a servlet in your own webapp, it will have its own session, unrelated to Liferay's.
You should rather implement a portlet and utilize its serveResource lifecycle method to handle the Ajax request - this will make you part of the whole portal environment. However, you should also minimize use of the Http-level session: It's prone to become a source for memory leaks sooner or later.
Note: While implementing a portlet will give you access to the HttpServletRequest (through PortalUtil), this is discouraged for the reasons given above. But as I don't know what you're trying to achieve, this would be part of the quickfix for the code that you give in your question.
Hello i am trying to develop a rest api .it have no need for performance issue or such complex design just two api . how can i develop it with out jersy using jetty server ??
Isn't there any way we can make a RESTful web service without using jersey or for that matter any other light weight libs ?
is there any Reasons for not directly write Servlets for creating a REST API ??
Here is the code for skeleton servlet. If you have issues making it run, let me know and I'll post complete sample project.
public class TestServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
String query = request.getQueryString();
writer.print("Hello. You said: " + query);
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
doGet(req, res);
}
}
REST is basically a concept over applied the HTTP protocol. You can implement it with Servlets and JSP, even thought it will be much harder to understand in a more complex scenario, when a base resource invokes sub-resource, building a chain call.
I would recommend that you stick to the JAX-RS specification for java REST services. It is very lightweight and easy to understand.
I have got a website, with really badly implemented Vanity URL module and really high loads at certain periods of time. Due to some bugs in the url module, the system needs to be restarted every so often. So, I want to rewrite a bloody module to make it nice and less buggy...
Is there are a good pattern to implementing Vanity URL system ?
What is the best approach when dealing with Vanity URL's for high performance ?
What is the best library to look at the sources ?
Cheers.
Ako
I'm not sure about the specific implementation details of your application, but as a general sketch I would write a Filter mapped to the space of URL of interest (perhaps /*).
Such Filter would check if the URL is a fancy one, and in that case would forward the request to the appropiate resource (either a URL dispatcher or a named one). You will need to save the filterConfig.getServletContext() passed in init(FilterConfig) in order to create the request dispatchers. If the URL is not fancy, the filter would invoke chain.doFilter(req, resp), then serving a non-mapped resource.
public class ExceptionFilter implements Filter {
private ServletContext servletContext;
public void destroy() {}
public void doFilter(ServletRequest req,
ServletResponse resp,
FilterChain chain)
throws IOException, ServletException {
String mapping = getMappingFor((HttpServletRequest)req);
if(mapping!=null) servletContext.getRequestDispatcher(mapping).forward(req,resp);
else chain.doFilter(req, resp);
}
public void init(FilterConfig filterConfig) throws ServletException {
this.servletContext = filterConfig.getServletContext();
}
private String getMappingFor(HttpServletRequest req) {...}
How getMappingFor is implemented, depends on the application, but it would probably open a connection to a database and ask whether URL /foo/bar is mapped, returning the mapped URL or nullif there is no mapping. If the mappings are known not to change, you may cache those mappings already retrieved.
You may go with more detailed implementations, such as setting some request attributes depending on the given URL or information from the database, and then forwarding the request to some servlet that knows what to do.