用戶場景:在網頁裏輸入:http://localhost:8080/Demo04/login_success.html ,出現登錄界面(login.html),輸入正確帳戶密碼後,點擊提交後便跳轉到另外一個 html 頁面。html
作法:java
login.html瀏覽器
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="LoginServlet" method="get"> <h2>請輸入如下內容,完成登錄</h2> 帳號:<input type="text" name="username"/><br> 密碼:<input type="text" name="password"/><br> <input type="submit" value="登錄"> </form> </body> </html>
登錄成功頁面 login_success.html測試
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h2>登錄成功了</h2> <a href="">獲取網站登錄總數</a> </body> </html>
測試類網站
package com.itheima.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { //response 響應數據給瀏覽器,就靠這個對象 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.獲取數據 String userName = request.getParameter("username"); String password = request.getParameter("password"); System.out.println("userName="+userName+"password"+password); //2.校驗數據 PrintWriter pw = response.getWriter(); if("admin".equals(userName) && "123".equals(password)){ // System.out.println("登錄成功"); pw.write("login success...."); //設置狀態碼,從新定位狀態碼 response.setStatus(302); //成功就會跳轉到 login.html網頁 response.setHeader("Location", "login_success.html"); }else{ // System.out.println("登錄失敗"); pw.write("login faild..."); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }