Servlet request请求转发-登录案例 作者:马育民 • 2022-02-09 13:35 • 阅读:10015 # 案例 登录成功后,**转发** 到 首页,如下图: [![](http://65242847.gitee.io/pic/jsp/11370083-f279314aef6741db324234.jpg)](http://65242847.gitee.io/pic/jsp/11370083-f279314aef6741db324234.jpg) # 实现 ### search.jsp ``` 用户名: 密码: ``` ### LoginServlet2 ``` package com.zrgj.servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.List; 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 com.zrgj.util.DbUtils; /** * * 该登录类,登录成功后,实现跳转 * * @author 马育民 * */ @WebServlet( urlPatterns="/login2") public class LoginServlet2 extends HttpServlet{ /** * HttpServletRequest req:封装请求信息(数据),如:封装提交来的用户名、密码 */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html; charset=UTF-8"); //获取提交来的数据 String uname=req.getParameter("username"); String pass=req.getParameter("password"); DbUtils s=new DbUtils(); try { //try代码块,写可能抛异常的代码 s.connect("com.mysql.jdbc.Driver" , "jdbc:mysql://127.0.0.1:3308/scott?useSSL=false&useUnicode=true&characterEncoding=utf-8" ,"root" ,""); } catch (ClassNotFoundException e) {//e就是抛出异常的对象(将报错的信息封装到给对象中) // TODO Auto-generated catch block e.printStackTrace();//将异常的详细信息打印到控制台 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //登录的sql String sql="SELECT uid,username,password FROM user WHERE username=? AND PASSWORD=? "; //创建参数的数组,将sql语句需要的参数,放入到该数组中 Object[] paras=new Object[2]; paras[0] = uname;//因为sql语句中第一个? 是用户名 paras[1] = pass; try { List list=s.query(sql, paras);//可能会抛出异常,因为可能写错sql语句 //如何处理,才能知道登录成功???? // TODO 待完成 if(list!=null && list.size()>0){ //说明登录成功! System.out.println("登录成功!");//其实没必要显示在控制台中 // out.write("登录成功!"); //登录成功后,跳转到首页 //叫:转发,也叫forward req.getRequestDispatcher("/index.html").forward(req, resp); }else{ //在forward转发时,不要执行该行代码,否则乱码 // PrintWriter out=resp.getWriter(); // 该对象的作用是:向浏览器输出文字 // //说明登录失败! // System.out.println("登录失败!"); // out.write("登录失败!"); // req.getRequestDispatcher("/loginFail.html").forward(req, resp); req.getRequestDispatcher("/WEB-INF/test.html").forward(req, resp); } System.out.println();//此无效代码的作用,是为了 debug时,能够停在该行,方便查看list元素 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace();//一定要打印异常,否则一旦报错,你不知道哪里报的错误 } try { s.close();//数据库资源非常宝贵,用完之后,要及时关闭掉。否则,长时间连接数据库不断开,会导致数据库无响应,再也连不上 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("接收到登录请求!用户名:"+uname+",密码:"+pass); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("调用doPost()"); doGet(req, resp); } } ``` ### loginFail.html 登录失败页面 ``` 登录失败! ``` 原文出处:http://malaoshi.top/show_1IX2kMSru0xE.html