iT邦幫忙

0

【左京淳的JAVA WEB學習筆記】第三章 登入頁面

首先先做個測試用的基本頁面,裡面放個表單

"<%@ page language=""java"" contentType=""text/html; charset=utf-8""
    pageEncoding=""utf-8""%>
<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + ""://"" + request.getServerName()  
  + "":"" + request.getServerPort() + path + ""/"";
%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
  <%=path %>
  <br>
  <%=basePath %>
  <br>
  <form action=""<%=basePath%>LoginSvl"" method= ""post"">
    <table align = ""center"">
      <tr><td height = 200></td></tr>
      <tr><td>用戶名:</td><td><input type = ""text"" name = ""uname""></td></tr>
      <tr><td>密碼:</td><td><input type = ""password"" name = ""pwd""></td></tr>
      <tr>
        <td colspan = ""2"" align = ""center"">
          <input type = ""submit"" value = ""提交""/>${msg}
        </td>
      </tr>
    </table>
  </form>"

這邊pageEncoding設為utf-8是為了能顯示中文。

訪問登入頁面的網址時,默認會觸發Servlet的doGet()方法。
然而在同樣的頁面送出表單時,會啟動一樣的Servlet,但觸發doPost()方法。
具體設定由頁面上的標籤進行設定如下:

<form action="<%=basePath%>LoginSvl" method= "post">

可以設定表單的資料要送往哪個Servlet,以及觸發的方法。
不過在登入頁面通常就送往同一個Servlet,以POST方式送件。

為了得到Servlet的路徑,使用以下的request方法先得到網站的路徑。

"request.getScheme() + ""://"" + request.getServerName()  
  + "":"" + request.getServerPort() + request.getContextPath() + ""/"";"

以上路徑再加上Servlet名稱,即是完整路徑。

新增LoginSvl
在com.aaa.action包下新增LoginSvl。
改寫doGet()和doPost()方法如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  request.getRequestDispatcher("/main/login.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String uname = request.getParameter("uname");
  String pwd = request.getParameter("pwd");
  request.setAttribute("uname", uname);
  request.getRequestDispatcher("/main/hello.jsp").forward(request, response);
}

可以看出使用者進入登入頁面時,觸發doGet(),被轉發至login.jsp填表單。
填完之後送出表單,會觸發同一個Servlet的doPost(),把表單的參數都存進變數後,設置到request的屬性裡面。然後把使用者轉發到歡迎頁面去。

歡迎頁面可以新增或直接使用上一章寫的hello.jsp,
只要把顯示內容改為Hello,${uname}即可。
這邊就可以看出,用request即可攜帶資料在輸入頁面、後台以及輸出頁面之間趴趴造。
不過,由於Servlet預設以"ISO-8859-1"去解讀資料,因此若你在登入頁面輸入了中文名字,應該會在輸出頁面看到亂碼。
要修正此情形,需在servlet裡面加入以下代碼:

request.setCharacterEncoding("UTF-8");

註:在開發過程中,有時候會手殘刪錯檔案(就是在下),照以下步驟可以救回來:

  1. 選擇誤刪除檔所在包(資料夾)
  2. 在包上按一下右鍵。
  3. 選擇restore from local history...
  4. 在彈出的對話方塊中選擇需要恢復的檔

以上 就是這次的筆記內容


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言