1、创建用户登录提交界面
2、创建处理用户登录请求servlet组件Main
3、创建代表登录成功响应的servlet的组件LoginSuccess
4、创建代表登录失败响应的servlet组件LoginFail
【1代码login.html】
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>
</head>
<body bgcolor="#FFFFFF">
<center>欢迎登录系统</center>
<form action="Main" method="post">
<label>用户名:</label>
<input type="text" value="">
<label>密码:</label>
<input type="password" value="">
<input type="submit" value="提交"></input>
<input type="reset"></input>
</form>
</body>
</html>
【2程序Main.Java】
package example.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Main
*/
@WebServlet("/Main")
public class Main extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uerID=request.getParameter("userID");
if (uerID==null) uerID="";
String password=request.getParameter("password");
if(password==null) password="";
if(uerID.equals("guest")&&password.equals("guest")){
RequestDispatcher dispatcher=request.getRequestDispatcher("LoginSuccess");
dispatcher.forward(request, response);
}else {
RequestDispatcher dispatcher=request.getRequestDispatcher("LoginFail");
dispatcher.forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request,response);
}
public String getServletinfo(){
return "short description";
}
}
【3程序LoginSuccess.java】
package example.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/LoginSuccess")
public class LoginSuccess extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out=response.getWriter();
String name=request.getParameter("userID");
out.println("<html>");
out.println("<head>");
out.println("<title>登录成功</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>欢迎"+name+"您已成功登录系统</h1>");
out.println("</body>");
out.println("</html>");
}