實踐:
結合前端界面,響應簡單的登陸請求。
效果圖:
登陸成功:
登陸失敗:
代碼示例:
後端代碼:
@WebServlet("/welcome")
public class LogIn extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user");
String passWd = request.getParameter("passWd");
PrintWriter p = response.getWriter();
if(user.equals("login") && passWd.equals("123456"))
p.println("<h1>successful</h1>");
else
p.println("<h1>failed</h1>");
}
}
前端代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>歡迎登陸</title>
<style type="text/css">
div#log{
position: relative;
width: 400px;
height: 480px;
top: 80px;
left: 1000px;
border: 1px solid lightgrey;
}
div#user{
position: absolute;
top: 260px;
left: 1100px;
}
img{
float: left;
padding-top: 80px;
padding-left: 200px;
}
</style>
</head>
<body>
<h3 style="padding-left: 200px; padding-top: 20px;">Servlet自主學習登陸平臺</h3>
<img src="E:\Eclipse\Web開發\Demo_3\WebContent\WEB-INF/log.jpg">
<div id="log">
</div>
<div id="user">
<p style="text-align: center; font-size: 20px">歡迎登陸</p>
<form action="welcome" method="post">
賬戶:<input name="user"><br>
密碼:<input type="password" name="passWd" style="margin-top: 5px"><br>
<p style="text-align: right; font-size: 14px;">忘記密碼?</p>
<button style="width: 210px; margin-top: 10px;">登陸</button>
</form>
</div>
</body>
</html>
實現分析:
先看下項目文件分配圖:
理清前後端關係:
項目初啓,首先顯示界面的url爲:
http://localhost:8080/Demo_3/test.html
而響應界面爲:
http://localhost:8080/Demo_3/welcome
因此不難理解這其間的關係,如上述圖片所示。