这个Servlet的任务是用户登录
条件:
如果登陆账户名为“admin”,密码为“123456”,则判断登陆成功,跳转到“success.html”页面,展示内容为:“登陆成功!”。
反之,登陆账户和命名的账号密码不一致则跳转“error.html”页面,展示内容为“登陆失败”。项目要求
首先展示一段错误代码示例:
Login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="LoginServlet" method="post"> 用户名:<input type="text" name="username"><br> 密码:<input type="password" name="password"><br> 性别:<input type="radio" name="sex" value="男"> 男 <input type="radio" name="sex" value="女"> 女<br> 爱好:<input type="checkbox" name="hobby" value="看书">看书 <input type="checkbox" name="hobby" value="画画">画画 <input type="checkbox" name="hobby" value="听歌">听歌<br> <input type="submit" value="登录"> </form> </body> </html>
LoginServlet
import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=utf-8"); request.setCharacterEncoding("utf-8"); // ServletContext context= this.getServletContext(); PrintWriter out = response.getWriter(); String name = request.getParameter("username"); String password =request.getParameter("password"); String sex =request.getParameter("sex"); out.println("用户名:" + name+"<br>"); out.println("密码:" + password+"<br>" ); out.println("性别:" + sex+"<br>"); String [] hobbys = request.getParameterValues("hobby"); out.println("爱好:"); for (int i =0; i<hobbys.length;i++) { out.println(hobbys[i]+" "); } if (name.equals("admin") && password.equals("123456")){ request.getRequestDispatcher("/success.html").forward(request,response); }else { out.println("用户名或密码输入有误...3秒后将自动跳转 <br>"); response.setHeader("Refresh","3;URL=/error.html"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
success.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Successful</title> </head> <body> 登录成功 </body> </html>
error.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Error</title> </head> <body> 登录失败 </body> </html>
项目打包下载
这样看的代码好似没什么问题(~ ̄▽ ̄)~
but!为什么错误跳转出来是乱码?!!!Admin