サーブレットで認証するコードの紹介です。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<FORM method="POST" action="CertServlet">
UserName : <INPUT type="text" name="username"><br><br>
Password : <INPUT type="text" name="password"><br><br>
<INPUT type="submit" value="SEND">
<INPUT type="reset" value="RESET">
</FORM>
</body>
</html>
<FORM method="POST" action="CertServlet">
POSTメソッドのHTMLフォームを用意します。Action先はサーブレットにします。
HTMLフォーム内にはユーザー名を入力するテキストボックス、パスワードを入力するテキストボックス、リセットボタン、サブミットボタンを配置します。
package webApplication8;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CertServlet extends HttpServlet {
/** Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletConfig config = getServletConfig();
// Servlet 初期化パラメータ情報
String un = config.getInitParameter("username");
String pw = config.getInitParameter("password");
response.setContentType("text/html; charset=shift-jis");
PrintWriter out = response.getWriter();
if (un.equals(request.getParameter("username")) == true
&& pw.equals(request.getParameter("password")) == true) {
out.println("OK 認証に成功しました");
} else {
out.println("NG パスワードまたはユーザー名が違います");
}
out.close();
}
/** Returns a short description of the servlet. */
public String getServletInfo() {
return "Short description";
}
}
doPost()メソッドを実装します。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation
="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>CertServlet</servlet-name>
<servlet-class>webApplication8.CertServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>administrator</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>administrator</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>CertServlet</servlet-name>
<url-pattern>/CertServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>