【有道云笔记】十七 4.3 转发、重定向、Get、POST、乱码
https://note.youdao.com/s/GD5TRksQ
一、转发
转发:一般查询了数据之后,转发到一个jsp页面进行展示
req.setAttribute("list", list);
req.getRequestDispatcher("student_list.jsp").forward(req, resp);
二、重定向
重定向:一般添加、删除、修改之后重定向到查找所有
resp.sendRedirect("/student");
重定向的状态码是302,重定向的地址最终是由浏览器发送这个请求
给超链接添加点击事件并触发:
<a href="javascript:void(0)" οnclick="method()"></a> <a href="javascript:;" οnclick="method()"></a> <a href="javascript:method();">xxx</a>
三、Get
- 采用URL请求路径传输参数,参数拼接在URL后面
- 参数传输过程中隐私性较差,直接在URL后面
- 路径可以容纳的数据有限,只能传递少量参数
- form表单请求默认就是get
http://localhost:8080/student?method=deleteById&id=23
http://localhost:8080/student?name=zhangsan&age=12&gender=男
Get方式传参,不是非得在form表单里面,可以手动写,在超链接的href里面直接在地址后面加?id=2
四、POST
- 采用实体内容传参数
- 参数在传输过程中不可见,隐私性好
- 实体内容专门用来传输数据,大小没有限制
- 使用:在form上加method="post"
不管是Get方式还是POST方式传参数,后台代码获取参数的方式都是一样的。
req.getParameter("name");
五、乱码问题总结
1、数据库创建时候选择utf-8编码
连接数据库url:
jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8
2、解决post请求乱码问题 method="post"
req.setCharacterEncoding("UTF-8");
3、服务器响应浏览器的乱码问题:
resp.setContentType("text/html;charset=utf-8");
六、前台往后台发请求方式
- form表单
- 超链接删除
- location.href
- ajax
跳转到一个jsp页面的方式:
- 直接访问这个jsp页面 http://localhost:8080/student_update.jsp
- 访问servlet转发到这个页面
七、增删改查代码
//http://localhost:8080/index.jsp //http://localhost:8080/student @WebServlet("/student") public class StudentServlet extends HttpServlet { //默认访问service @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //System.out.println("StudentServlet.service"); //解决post请求乱码问题 req.setCharacterEncoding("UTF-8"); // http://localhost:8080/student?method=selectAll // http://localhost:8080/student?method=deleteById&id=23 String method = req.getParameter("method"); if (method == null || method.equals("")) { method = "selectAll"; } switch (method) { case "selectAll": selectAll(req, resp); break; case "deleteById": deleteById(req, resp); break; case "add": add(req, resp); break; case "toUpdate": toUpdate(req, resp); break; case "update": update(req, resp); break; } } private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println("StudentServlet.update"); String id = req.getParameter("id"); String name = req.getParameter("name"); String age = req.getParameter("age"); String gender = req.getParameter("gender"); Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCUtil.getConnection(); String sql = "update student set name=?,age=?,gender=? where id=?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); preparedStatement.setInt(2, Integer.parseInt(age)); preparedStatement.setString(3, gender); preparedStatement.setInt(4, Integer.parseInt(id)); System.out.println(preparedStatement); int count = preparedStatement.executeUpdate(); System.out.println("count: " + count); } catch (SQLException throwables) { throwables.printStackTrace(); } resp.sendRedirect("/student"); } private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("StudentServlet.toUpdate"); String id = req.getParameter("id"); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; Student student = null; try { connection = JDBCUtil.getConnection(); String sql = "SELECT id,name,age,gender FROM student where id=?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, Integer.parseInt(id)); System.out.println(preparedStatement); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) {//判断下一个有没有,如果返回true而且指向下一个,没有返回false //int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); student = new Student(Integer.parseInt(id), name, age, gender); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, resultSet); } //把list数据放到req里面 req.setAttribute("student", student); //转发到student_list.jsp页面进行展示 req.getRequestDispatcher("student_update.jsp").forward(req, resp); } private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException { System.out.println("StudentServlet.add"); String name = req.getParameter("name"); String age = req.getParameter("age"); String gender = req.getParameter("gender"); Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCUtil.getConnection(); String sql = "insert into student(name,age,gender) values(?,?,?)"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, name); preparedStatement.setInt(2, Integer.parseInt(age)); preparedStatement.setString(3, gender); System.out.println(preparedStatement); int count = preparedStatement.executeUpdate(); System.out.println("count: " + count); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, null); } resp.sendRedirect("/student?method=selectAll"); } private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException { String id = req.getParameter("id"); Connection connection = null; PreparedStatement preparedStatement = null; try { connection = JDBCUtil.getConnection(); String sql = "delete from student where id=?"; preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, Integer.parseInt(id)); System.out.println(preparedStatement); int count = preparedStatement.executeUpdate(); System.out.println("count: " + count); } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, null); } // /student 302 // 重定向 resp.sendRedirect("/student?method=selectAll"); } private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; List<Student> list = new ArrayList<>(); try { connection = JDBCUtil.getConnection(); String sql = "SELECT id,name,age,gender FROM student"; //预编译 preparedStatement = connection.prepareStatement(sql); System.out.println(preparedStatement); resultSet = preparedStatement.executeQuery(); while (resultSet.next()) {//判断下一个有没有,如果返回true而且指向下一个,没有返回false int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); String gender = resultSet.getString("gender"); Student student = new Student(id, name, age, gender); list.add(student); } for (Student student : list) { System.out.println(student); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JDBCUtil.close(connection, preparedStatement, resultSet); } //把list数据放到req里面 req.setAttribute("list", list); //转发到student_list.jsp页面进行展示 req.getRequestDispatcher("student_list.jsp").forward(req, resp); } }
student_list.jsp
<%@ page import="com.situ.web.pojo.Student" %> <%@ page import="java.util.List" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <link rel="stylesheet" href="static/bootstrap-3.4.1-dist/css/bootstrap.css"> </head> <body> <% //JSP页面中可以嵌套Java代码 //JSP脚本:在这里可以写任意的Java代码 //request、response:JSP页面的内置对象 List<Student> list = (List<Student>) request.getAttribute("list"); %> <a class="btn btn-primary" href="/student_add.jsp">添加</a> <table class="table table-striped table-bordered table-hover table-condensed"> <tr> <td>ID</td> <td>名字</td> <td>年龄</td> <td>性别</td> <td>编辑</td> <td>删除</td> </tr> <% for (Student student : list) { %> <tr> <td><%=student.getId()%></td> <td><%=student.getName()%></td> <td><%=student.getAge()%></td> <td><%=student.getGender()%></td> <td><a href="/student?method=toUpdate&id=<%=student.getId()%>">编辑</a></td> <%--/deleteStudent?id=12 --%> <%--<td><a href="/deleteStudent?id=<%=student.getId()%>">删除</a></td>--%> <%--<td><a href="/student?method=deleteById&id=<%=student.getId()%>">删除</a></td>--%> <td><a href="javascript:deleteById(<%=student.getId()%>)">删除</a></td> </tr> <% } %> </table> <script> function deleteById(id) { var isDelete = confirm('您确认要删除?'); if (isDelete) { location.href = '/student?method=deleteById&id=' + id; } } </script> </body> </html>
student_add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/student?method=add" method="post"> 用户名:<input type="text" name="name"/><br/> 年龄:<input type="text" name="age"/><br/> 性别:<input type="text" name="gender"/><br/> <input type="submit" value="添加"/> </form> </body> </html>
student_update.jsp
<%@ page import="com.situ.web.pojo.Student" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% Student student = (Student) request.getAttribute("student"); %> <form action="/student?method=update" method="post"> <input type="hidden" name="id" value="<%=student.getId()%>"/> 用户名:<input type="text" name="name" value="<%=student.getName()%>"/><br/> 年龄:<input type="text" name="age" value="<%=student.getAge()%>"/><br/> 性别:<input type="text" name="gender" value="<%=student.getGender()%>"/><br/> <input type="submit" value="修改"/> </form> </body> </html>