通过HttpServlet来开发servlet:
version 1.0 包含的功能:
1、进行简单的用户验证
知识点:
1、如何使用servlet开发动态网页
2、如何从一个页面跳转到另一个页面
response.sendRedirect(String)
代码:
/**
* @(#)Login.java
*
*
* @author
* @version 1.00 2008/7/20
*/
package com.keer2345;
import javax.servlet.http.*;
import java.io.*;
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<body>");
pw.println("<form action=loginCheck method=post>");
pw.println("用户名:<input type=text name=username><br>");
pw.println("密 码:<input type=password name=password><br>");
pw.println("<input type=submit value=Login>");
pw.println("</form>");
pw.println("</body>");
pw.println("</html>");
}
catch(Exception ex){
ex.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
this.doGet(request,response);
}
}
/**
* @(#)LoginCheck.java
*
*
* @author
* @version 1.00 2008/7/20
*/
package com.keer2345;
import javax.servlet.http.*;
import java.io.*;
public class LoginCheck extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
if (username.equals("keer2345") && password.equals("keer2345")) {
pw.println("<h1><center>Welcome!</center></h1>");
pw.println("<center><a href=login>Try again!</a></center>");
} else {
response.sendRedirect("login");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
this.doGet(request,response);
}
}
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.keer2345.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>com.keer2345.LoginCheck</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/loginCheck</url-pattern>
</servlet-mapping>
</web-app>