模拟MVC的简单入门程序,附源代码 – 恵玩科技

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>LoginServlet</title>
</head>
<body>
<form action="/LoginServlet" method="post">
    姓名: <input type="text" name="username" value="username">
    <input type="submit" value="提交">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>success</title>
</head>
<body>
成功了,噢耶
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>fail</title>
</head>
<body>
登录失败了
</body>
</html>
package com.lxgyx.web.servlet;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "LoginServlet",urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //取得表单提交的参数
        String username=request.getParameter("username");

        //调用模型层对象
        LoginBean loginBean=new LoginBean();
        boolean flag=loginBean.validate(username);

        //根据返回值,转发到不同的页面
        if(flag){
            ServletContext context=this.getServletContext();
            //定位需要转发的路径
            RequestDispatcher requestDispatcher=context.getRequestDispatcher("/success.html");

            //真正的转向页面
            requestDispatcher.forward(request,response);
        }else {
            ServletContext context=this.getServletContext();
            RequestDispatcher rd=context.getRequestDispatcher("/fail.html");
            rd.forward(request,response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
package com.lxgyx.web.servlet;

public class LoginBean {
    //验证用户名的方法
    public boolean validate(String username){
        boolean flag=false;
        if (username!=null&&"zhangdapeng".equals(username)){
            flag=true;
        }
        return flag;
    }
}

 

打赏作者