Database Design Servlets

I have a general question about using Servlet and JDBC.

For example, I have a class MyDatabaseManager that provides functions

public boolean updateUser (User user) {...}
public boolean deleteUser (User user) {...}
public boolean inserUser (User user) {...}

these functions will access and manage the Database.

My question is how to implement a servlet. I currently use three servlets (UpdateUserServlet, InsertUserServlet and DeleteUserServlet), and each servlet invokes an instance of MyDatabaseManager (only one instance here using the Singleton pattern). (For example, UpdateUserServlet calls MyDatabaseManager.updateUser ...).

I think this is the easiest way to use Servlet and Database. But I'm not sure if this is the right way to do this. For example, how it is implemented in the industrial world.

+5
source share
6 answers

People don’t actually use servlets right now, they use frameworks that simplify your work, but if you really want to use servlets, you can do all the actions in one using other methods, doPut, doDelete and even creating your own methods. Here is an example of how you will do this:

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();
   }

}

, _method , , , _method , doGet doPost.

:

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);
}

}

, .

+5

, ! , DAO ( ). . .

, , - . , . , , DAOFactorySingleton, DAO , factory , DataSource, factory DAO! , DAO , JDBC!

2 , DAO! http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

http://community.jboss.org/wiki/GenericDataAccessObjects

- ! . , , .

+2

, , , Spring, Struts .., . , / , , .

, ORM, Hibernate, JPA .., . , JDBC, " " , , .

+1

Singleton Database , , //.

, , Singleton DataSourceFactory.

0

ORM + Dependency Injection framework + + , Hibernate (ORM) + Spring DI (Dependency Injection) + Spring ( ) + Apache DBCP ( ).

, ORM (, , ORM - ..), raw JDBC. - .

. I.e., , .

, ( API- DB). ., . , .

- (, ), ( ). - , .

0

. , , ( ) .

MVC, . . :

  • ( ). - .

Java , MVC. , Java, JSF (JavaServer Faces).

, ORM (Object Relational Mapping) () . ERM (Entity-Relational Modeling) .

-, ( -), , / , . , . .

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");
    }
}

, Java 5 JPA. ORM, , . Hibernate ( JPA), , DAO.

One more thing, all these processes are tedious for gluing. Fortunately, we have a framework that helps us make our beautiful example a lot easier. Structures like JBoss Seam do this and make full use of the Java specifications. At the moment, for simple design models and MVC (for training). When you are used to architecture, use frameworks.

0
source

All Articles