查看: 826|回复: 0

[DIV/CSS] 编写Servlet,验证用户登录,如果用户名与密码都为“admin”则验证通过,跳转欢迎页面,否则弹出提示信息“用户名或密码错误,请重新输入!”,点击“确定”后

发表于 2017-9-24 08:00:05
尚学堂AD

java代码:(Test1)

  1. package com.test;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.annotation.WebServlet;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. @WebServlet(urlPatterns={"/Test1"})
  10. public class test1 extends HttpServlet {
  11. @Override
  12. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  13. throws ServletException, IOException {
  14. // TODO 自动生成的方法存根
  15. req.setCharacterEncoding("gbk");
  16. resp.setContentType("text/html;charset=utf-8");
  17. PrintWriter out = resp.getWriter();
  18. String user=req.getParameter("user");
  19. String pass = req.getParameter("pwd");
  20. if(user.equals("admin")&&pass.equals("admin")){
  21. out.println("欢迎登陆");
  22. }else{
  23. out.println("<script language='javascript'>alert('用户名或密码错误,请重新输入!')</script>");
  24. out.println("<script language='javascript'>window.location.href='/Servlet_work/Html1.html'</script>");
  25. }
  26. }
  27. @Override
  28. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  29. throws ServletException, IOException {
  30. // TODO 自动生成的方法存根
  31. doGet(req, resp);
  32. }
  33. }
复制代码

html代码:(html1)

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Html1.html</title>
  5. <meta name="keywords" content="keyword1,keyword2,keyword3">
  6. <meta name="description" content="this is my page">
  7. <meta name="content-type" content="text/html; charset=utf-8">
  8. <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
  9. <style>
  10. #home {
  11. width: 300px;
  12. height: 300px;
  13. margin: auto;
  14. }
  15. .dl1{
  16. clear: both;
  17. }
  18. .dl1 dt{
  19. float: left;
  20. }
  21. .dd1 dd{
  22. float: left;
  23. }
  24. h1{
  25. text-align: center;
  26. }
  27. #foot{
  28. text-align: center;
  29. }
  30. </style>
  31. </head>
  32. <body>
  33. <div id="home">
  34. <h1>用户登陆</h1>
  35. <form action="Test1" method="post">
  36. <dl class="dl1">
  37. <dt>用户账号:</dt>
  38. <dd><input type="text" name="user" /></dd>
  39. </dl>
  40. <dl class="dl1">
  41. <dt>用户密码:</dt>
  42. <dd><input type="passWord" name="pwd" /></dd>
  43. </dl>
  44. <div id="foot">
  45. <input type="submit" value="登陆"/>
  46. </div>
  47. </form>
  48. </div>
  49. </body>
  50. </html>
复制代码

运行截图:

备注:

在Servlet中实现页面中弹窗:

  1. PrintWriter out = resp.getWriter();
复制代码
  1. out.println("<script language='javascript'>alert('用户名或密码错误,请重新输入!')</script>");
复制代码

在Servlet中实现页面的跳转:

  1. out.println("<script language='javascript'>window.location.href='/Servlet_work/Html1.html'</script>");
复制代码



回复

使用道具 举报