如何在Servlet的单独类中实现MVC的业务逻辑?

时间:2016-03-19 15:21:07

标签: servlets

我已经尝试将类放在servlets控制器中但是我在构造函数和设置方法访问方面遇到了麻烦。我阅读它提高效率以使业务逻辑分离,我甚至尝试将其放在JavaBean中,但我还不知道如何从控制器向它发送参数。我仍然需要学习很多东西,只是在做一个项目。

1 个答案:

答案 0 :(得分:0)

您可以使用EJB将业务逻辑与表示层分开,即JavaEE平台中的(Servlet和JSP)。如果您的项目没有太多业务逻辑代码,那么只需使用Java POJO类。 This example gives very raw idea. you can use web frameworks which have built in MVC design.

<强> Controller: 使用Servlet来控制导航或针对HTTP请求执行其他任务。

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    public LoginServlet() {
        super();
    }



    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        LoginManager loginManager=new LoginManager();
        if(loginManager.isValidUser("getUserID from request Params","password from request params")){
            //initialize user session and redirect to dashboard
            //response.sendRedirect("/userhome.jsp");
        }else{
            //display failure messages. etc...
            //response.sendRedirect("/login.jsp");
        }
    }

}

<强> Model : POJO,包含一组用于登录相关操作的方法。

 public class LoginManager {

    private Connection con;

    public LoginManager() {

    }

    private void initConnection(){
        //register driver class and create a new connection
        //you can create separate DBUtils class to get new connections
        //to prevent boilerplate code.

        //make new connection to database
//      con=..
    }

    private void closeConnection() throws SQLException{
        con.close();
    }

    public boolean isValidUser(String user,String password) throws SQLException{
        initConnection();
        PreparedStatement pstm=con.prepareStatement("select 1 from users where userID = ? and password=?");

//设置用户ID和密码参数             ResultSet rs = pstm.executeQuery();

        if (rs.next()){
            if(checkpassword.....)
            return true;
        }
        closeConnection();
        return false;
    }
}

<强> View

login.jspuserhome.jsp页这样的页面是视图;