开发者

Proper Model 2 Design

I understand there are a variety of ways to design web applications using java-ee, but the method that seems to make the most sense to me is model 2 or mvc where we separate the code and design into servlets and jsp pages.

Based on the research I have done, the proper method is to access a page through a servlet and then points the user in the proper direction, but i'm having a hard time wrapping my brain around this idea so please tell me if this real world example makes practical model 2 sense.

Say I have a website and the home page is a login. So here the user would go to something like www.mysite.com/Login (where Login is the name of the servlet). This servlet might look something like this:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession session = request.getSession();

    if(request.getParameter("username") != null && request.getParameter("password") != null){

        User user = new User();
        user.setUsername(request.getParameter("username"));

        try {
            user.setPassword(com.portraitcreationsnc.services.EncryptionService.getInstance().encrypt(request.getParameter("password")));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            if(!user.userExist(user)){ //No Match.
                String errMessage = "You have entered an invalid Username/Password combination."; //Error Message
                request.setAttribute("message", errMessage);
                request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
                System.out.println("Login Error");
            } else {
                //Match found.
                session.setAttribute("user", user);

          开发者_开发技巧      System.out.println("User Login Successful");
                pageForward(request, response);
            }
        } catch (SQLException e) {
            throw new ServletException("DB error ", e);
        }

    }else{
        if(session.getAttribute("user") == null){
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
        }else{
            //User already logged in. Send to home.
            response.sendRedirect("Welcome");
        }
    }
}

private void pageForward(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    response.sendRedirect("Welcome");
}

The main idea here is that the servlet loads initially and checks whether or not it has requestParameters. If it does not, it redirects to login.jsp which might look something like:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org      /TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<h3>Simple Login</h3>
<form action="LoginAuth" method="post">
Username <input type="text" name="username"> 
Password <input type="password" name="password">
<button type="submit">Login</button>
</form>
<%
Object errMessage = request.getAttribute("message");
if(errMessage != null){
out.println(request.getAttribute("message"));
out.println("<br>");
}
%>

<br>
If you do not have a username, <a href="register.html">click here to register.</a>
</body>
</html>

Which in turn will call the servlet again when the form is submitted and the servlet will recognize the request data, and proceed with checking the user against a database etc etc.

It seems somewhat backwards to not just load the jsp first, but in other situations it makes far more sense to load the servlet first. The research I have done concludes that with model 2 you should almost exclusively never call a jsp page, but instead direct all links to servlets who pass the user onto jsp's. Is my design the proper way to accomplish this?


You got it right. Note that you could initially point to another servlet (let's call it LoginDisplay), which would just dispatch to the login JSP. The JSP would submit to the LoginAuth servlet, which expects all the required parameters to be there.

If you want to use such a model, don't reinvent the wheel, though. There are lots of frameworks implementing this model already and providing other useful services : Stripes, Spring MVC, Struts just to name a few.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜