製作login.jsp頁面,要求實現提供使用者登陸的介面, 使用者通過該介面輸入使用者名稱(控制元件名userName)和密碼(控制元件名password), 然後點選“登入”按鈕實現登陸操作.
阿新 • • 發佈:2019-02-09
例題:
1.製作login.jsp頁面,要求實現提供使用者登陸的介面,
使用者通過該介面輸入使用者名稱(控制元件名userName)和密碼(控制元件名password),
然後點選“登入”按鈕實現登陸操作.
2.製作welcome.jsp頁面,要求在該頁面中顯示合法使用者成功登陸的提示資訊,
資訊格式如下:“使用者,密碼為,歡迎您於*時間訪問本頁面。”
3.設計並實現LoginServlet類,通過該類獲取login.jsp中提交的登陸資訊。
合法使用者登陸時要求獲取使用者登陸的時間,並通過RequestDispatcher物件將成功登陸的提示資訊轉發到welcome.jsp頁面,
非法使用者登陸時重定向到login.jsp頁面,讓使用者重新登入。
4.合法使用者只有一名,使用者名稱為“TOM”,密碼為“123456”。
這裡我用到的開發工具是Intellij idea 2017.3建立專案如圖
建立login.jsp
<%--
Created by IntelliJ IDEA.
User: SugarMan
Date: 2017/12/18
Time: 上午10:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>登入</title>
</head>
<body>
${requestScope.info}
<form action="first" method="post">
姓名:<input type="text" name="userName"><br>
密碼:<input type="password" name="password"><br>
<input type="submit" value="登入">
</form>
</body>
</html>
first.java程式碼
package Servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
public class first extends HttpServlet {
protected void doPost(HttpServletRequest request,
ServletException, IOException {
request.setCharacterEncoding("utf-8");
String name = request.getParameter("userName");
String password =
request.getParameter("password");
String info = "";
request.setAttribute("userName",name);
request.setAttribute("password",password);
if (name.equals("TOM") && password.equals("123456")) {
info = name + "使用者,密碼為:" + password +
",歡迎您於" + new Date() + "時間訪問本頁面";
request.setAttribute("info",info);
//此方法重新定向的地址為web.xml裡servlet的地址
request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request,response);
} else {
info = "使用者密碼輸入錯誤";
request.setAttribute("info",info);//向req儲存info資訊
RequestDispatcher dispatcher =
request.getRequestDispatcher("login.jsp");
dispatcher.forward(request,response);//重定向轉發
}
}
}
PS:這裡為什麼我沒有用LoginServlet來命名呢,因為我試過用這個名稱命名,卻發現在form表單裡找不到它,重啟伺服器,清除idea快取都不行,無奈只好用其他名稱命名了,如果有小夥伴解決了這個問題可以告訴我哦!
welcome.jsp程式碼
<%--
Created by IntelliJ IDEA.
User: SugarMan
Date: 2017/12/18
Time: 上午10:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>歡迎</title>
</head>
<body>
${requestScope.info}
</body>
</html>
PS:這個EL表示式真心方便