页面显示:
失败:
成功
视图层(view)
login.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action='/day04/LoginServlet' method='post'>
<table border="1" align="center">
<caption>用户登陆【mvc】</caption>
<tr>
<th>用户</th>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
</body>
</html>
fail.hmtl
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
登陆失败
</body>
</html>
cuccess.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陆</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
登陆成功
</body>
</html>
控制层(controller)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 取得提交的参数
String username = request.getParameter("username");
// 调用模型层对象
LoginBean lgin = new LoginBean();
boolean flag = lgin.validate(username);
// 根据还回值转发到不同页面;
if (flag) {
// 也可以使用这个
// this.getServletContext().getRequestDispatcher("/success.html").forward(request, response);
//获取提交值
ServletContext context = this.getServletContext();
// 定位需要转发的路径
RequestDispatcher rd = context
.getRequestDispatcher("/success.html");
// 真正转向页面
rd.forward(request, response);
} else {
//this.getServletContext().getRequestDispatcher("/fail.html").forward(request, response);
//获取提交值
ServletContext context = this.getServletContext();
// 定位需要转发的路径
RequestDispatcher rd = context
.getRequestDispatcher("/fail.html");
// 真正转向页面
rd.forward(request, response);
}
}
}
模型(model)
public class LoginBean {
public boolean validate(String username)
{
boolean flag = false;
//去掉空格
if(username.trim() != null && "liwen".equals(username.trim()))
{
flag = true;
}
return flag;
}
}