案例需求:写一个用户登录的html页面有账号和密码,并在登录的Servlet中获取登录的账号和密码,如果账号是abc密码是123则重定向到main.html,否则重定向到login.html。
案例实现:
● login.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form id="login_form" action="login.do" method="get" >
账号:<input type="text" name="acc_no" ><br>
密码:<input type="password" name="acc_password"><br>
<input type="submit" value="登录" />
</form>
</body>
</html>
● main.html页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> 恭喜你登录成功</h1>
</body>
</html>
● servlet类
package com.xdl.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class XdlLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
// 获取页面请求参数
String acc_no = request.getParameter("acc_no");
String acc_password = request.getParameter("acc_password");
if("abc".equals(acc_no) && "123".equals(acc_password)){
response.sendRedirect("main.html");
}else{
request.getRequestDispacher("login.html").forward(request,response);
}
}
}
● web.xml配置
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.xdl.servlet.XdlLoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>