開發環境myeclipse+tomcat5 先建立web project,項目名為test, 在webroot 目錄下建立login.jsp檔案 login.jsp <body> <form action="login"> username:<input type="text" name="username"><br> password:<input type="password" name="pwd"><br> <input type="submit"> </form> </body> 在scr目錄下的com.ht.servlet 編寫AcountBean.java檔案 package com.ht.servlet; public class AcountBean { private String username=""; private String password=""; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } } 編寫servlet類CheckAccount.java檔案 package com.ht.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.*; public class CheckAccount extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); AcountBean account = new AcountBean(); String username = request.getParameter("username"); String pwd = request.getParameter("pwd"); account.setUsername(username); account.setPassword(pwd); if ((username != null) && (username.trim().equals("jsp"))) {
if ((pwd != null) && (pwd.trim().equals("1"))) {
System.out.println("session");
session.setAttribute("account", account); String logon_suc = "session.jsp"; response.sendRedirect(logon_suc); return; } } String logon_fail = "fail.jsp"; response.sendRedirect(logon_fail); return; } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } 在webroot目錄下 編寫session.jsp檔案 成功後跳轉 <body> <%
com.ht.servlet.AcountBean account=(com.ht.servlet.AcountBean)session.getAttribute("account");
%> username: <%=account.getUsername() %> <br> password:<%=account.getPassword() %> </body> 編寫fail.jsp檔案 失敗後跳轉 <body> Logon Failed <br> </body> 下面是web.xml檔案 <?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"> <welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>CheckAccount</servlet-name> <servlet-class>com.ht.servlet.CheckAccount</servlet-class> </servlet> <servlet-mapping> <servlet-name>CheckAccount</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app> 通過myeclipse運行 配置tomcat 這裡省略。。。 http://127.0.0.1:8080/tset/ 驗證察看結果 |