一、环境
- Eclipse Java EE IDE for Web Developers.
Version: Neon.1a Release (4.6.1)
- Apache Tomcat version: 8.0.39
二、作业内容:
利用三个servlet,实现表单页面的输出,表单提交的信息的验证以及验证信息后的跳转页面。
三、开始
我们一共需要建立三个servlet类,他们分别是:Login.java,LoginContral.java和Welcome.java,他们的具体代码如下所示:
1.Login()类代码如下:
@WebServlet("/Login") public class Login extends HttpServlet { private static final long serialVersionUID = 1L;
public Login() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<head><title>登陆页面</title></head>"); out.println("<body>"); out.println("<h1>登陆页面</h1>"); out.println("<form action='LoginControl'>"); out.println("用户名:<input type='text' name='username' /><br>"); out.println("密码:<input type='password' name='password' /><br>"); out.println("<input type='hidden' name='sex' value='man' />"); out.println("<input type='submit' value='登陆'>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); } catch (Exception e) { e.printStackTrace(); } } }
|
2.LoginControl()类代码如下:
@WebServlet("/LoginControl") public class LoginControl extends HttpServlet { private static final long serialVersionUID = 1L;
public LoginControl() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("UTF-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String sex = req.getParameter("sex"); try { if (username.equals("admin") && password.equals("123")) {
HttpSession hs = req.getSession(); hs.setMaxInactiveInterval(30); hs.setAttribute("username", username); hs.setAttribute("password", password); resp.sendRedirect("Welcome?username=" + username + "&password=" + password + "&sex=" + sex); } else { resp.sendRedirect("Login"); } } catch (Exception e) { e.printStackTrace(); } } }
|
3.LoginControl()类代码如下:
@WebServlet("/Welcome") public class Welcome extends HttpServlet { private static final long serialVersionUID = 1L;
public Welcome() { super(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter();
HttpSession hs = req.getSession(); String usernameSession = (String) hs.getAttribute("username"); String passwordSession = (String) hs.getAttribute("password"); if (usernameSession != null) { out.println("欢迎登陆我们的网站!用户名:" + usernameSession + " 密码:"+ passwordSession); } else { } } catch (Exception e) { e.printStackTrace(); } } }
|