IT兄弟連 Java Web教程 經典案例2

  • 2019 年 10 月 5 日
  • 筆記

版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

本文鏈接:https://blog.csdn.net/ITXDL123/article/details/90051798

案例需求:寫一個用戶登錄的html頁面有帳號和密碼,並在登錄的Servlet中獲取登錄的帳號和密碼,如果帳號是abc密碼是123則向瀏覽器輸出登錄成功,否則向瀏覽器輸出登錄失敗。

案例實現:

● html 頁面

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>

<body>

<form id="login_form" action="login.do" method="get" >

帳號:<input type="text" name="acc_no" ><br>

密碼:<input type="password" name="acc_password"><br>

<input type="submit" value="登錄" />

</form>

</body>

</html>

● servlet類

package com.xdl.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 XdlLoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override

protected void service(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");

// 獲取頁面請求參數

String acc_no = request.getParameter("acc_no");

String acc_password = request.getParameter("acc_password");

PrintWriter pw = response.getWriter();

if("abc".equals(acc_no) && "123".equals(acc_password)){

pw.write("登錄成功");

}else{

pw.write("登錄失敗");

}

pw.close();

}

}

● web.xml配置

<servlet>

<servlet-name>LoginServlet</servlet-name>

<servlet-class>com.xdl.servlet.XdlLoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>LoginServlet</servlet-name>

<url-pattern>/login.do</url-pattern>

</servlet-mapping>