1.创建web project,项目名为test,
2.在webroot 目录下创建login.jsp文件
login.jsp的body部分描述如下:
<body>
<form action="login">
username:<input type="text" name="username"><br>
password:<input type="password" name="pwd"><br>
<input type="submit">
</form>
</body>
3.在scr目录下创建servlet文件,packege为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;
}
}
4.编写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("chen"))) {
if ((pwd != null) && (pwd.trim().equals("123"))) {
System.out.println("success");
session.setAttribute("account", account);
String logon_suc = "success.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);
}
}
5.在webroot目录下
编写success.jsp文件 成功后跳转
<body>
<%
com.ht.servlet.AcountBean account=(com.ht.servlet.AcountBean)session.getAttribute("account");
%>
username: <%=account.getUsername() %>
<br>
password:<%=account.getPassword() %>
</body>
6.编写fail.jsp文件 失败后跳转
<body>
Logon Failed <br>
</body>
7.下面是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>
8.通过myeclipse运行 配置tomcat