》》sendRedirect和getRequestDispatcher区别
》sendRedirect
地址栏:http://localhost:8096//JSP-07/success.jsp 不共享一个request
代码:response.sendRedirect("../success.jsp");
页面的路径是相对路径。sendRedirect可以将页面跳转到任何页面,不一定局限于本web应用中。
会重新创建request
这种方式要传值出去的话,只能在url中带parameter或者放在session中,无法使用request.setAttribute来传递。
》getRequestDispatcher
代码(写在servlet/myServlet里):request.getRequestDispatcher("/success.jsp").forward(request, response);
地址栏:http://localhost:8096//JSP-07/servlet/myServlet?action=quer
跳转后浏览器地址栏不会变化
这个时候如果success.jsp里有超链接的话就会发现如果直接写<a href="index.jsp">返回</a>是会找不到页面的
必须写成<a href="../index.jsp">返回</a>
这是因为它是内部跳转,虽然页面改变了,地址仍然是servlet里,所有后面写分页拼接网址的时候会用到这点知识。
这种重定向方式是利用服务器端的缓冲区机制,在把缓冲区的数据发送到客户端之前,原来的数据不发送,将执行转向重定向页面,发送重定向页面的数据,重定向调用页的数据将被清除。
》》实例
src结构
表:
emmmmmm....导出不大成功
/*
Navicat MySQL Data Transfer
Source Server : Tiffany
Source Server Version : 50716
Source Host : localhost:3306
Source Database : yiki
Target Server Type : MYSQL
Target Server Version : 50716
File Encoding : 65001
Date: 2017-12-25 18:40:08
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=gb2312;
-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('4', '鐐瑰鐐�', '4');
INSERT INTO `student` VALUES ('5', 'ddf', '4');
INSERT INTO `student` VALUES ('6', '鏉庝紛鐞�', '18');
INSERT INTO `student` VALUES ('7', 'ddf', '18');
INSERT INTO `student` VALUES ('8', 'ttt', '1');
INSERT INTO `student` VALUES ('9', '鏉庝紛鐞�', '4');
INSERT INTO `student` VALUES ('10', 'ddf', '18');
INSERT INTO `student` VALUES ('11', 'ddf', '18');
INSERT INTO `student` VALUES ('12', 'ddf', '18');
INSERT INTO `student` VALUES ('13', 'ddf', '18');
INSERT INTO `student` VALUES ('14', 'hhhh', '4');
INSERT INTO `student` VALUES ('15', 'hhhh', '4');
DButil
package com.yiki.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DButil {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
driver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://localhost:3306/yiki?useUnicode=true&characterEncoding=gb2312";
username = "root";
password = "*******";
}
public static Connection open() {
try {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
System.out.println("连接错误");
}
return null;
}
public static void close(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
javabean
package com.yiki.dbutil;
public class Student {
int id;
String name;
int age;
public static final int PAGE_SIZE=4;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
连接池
package com.yiki.dbutil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class StudentImpl {
public void add(Student s) {
String sql = "insert into student(name,age)value(?,?)";
Connection con = DButil.open();
try {
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setString(1, s.getName());
pstm.setInt(2, s.getAge());
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DButil.close(con);
}
}
public void delete(int id) {
String sql = "delete from student where id = ?";
Connection con = DButil.open();
try {
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setInt(1, id);
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DButil.close(con);
}
}
public Student getSbyID(int id) {
String sql = "select * from student where id=?";
Connection con = DButil.open();
Student s = new Student();
try {
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setInt(1, id);
ResultSet rs = pstm.executeQuery();
if (rs.next()) {
String name = rs.getString(2);
int age = rs.getInt(3);
s.setId(id);
s.setName(name);
s.setAge(age);
}
return s;
} catch (Exception e) {
e.printStackTrace();
} finally {
DButil.close(con);
}
return null;
}
public List<Student> query() {
String sql = "select * from student";
Connection con = DButil.open();
try {
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery(sql);
List<Student> list = new ArrayList<Student>();
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
Student s = new Student();
s.setId(id);
s.setName(name);
s.setAge(age);
list.add(s);
}
return list;
} catch (Exception e) {
e.printStackTrace();
} finally {
DButil.close(con);
}
return null;
}
public void Update(Student s) {
String sql = "Update student set name=?,age=? where id=?";
Connection con = DButil.open();
try {
PreparedStatement pstm = con.prepareStatement(sql);
pstm.setString(1, s.getName());
pstm.setInt(2, s.getAge());
pstm.setInt(3, s.getId());
pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
DButil.close(con);
}
}
public int findCount() {
int count = 0;
Connection conn = DButil.open();
String sql = "select count(*) from student";
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
count = rs.getInt(1);
}
rs.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return count; // 返回总记录数
}
public List<Student> find(int page) {
List<Student> list = new ArrayList<Student>();
Connection con = DButil.open();
String sql = "select* from student order by id desc limit ?,?";
try {
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, (page - 1) * Student.PAGE_SIZE);
ps.setInt(2, Student.PAGE_SIZE);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Student p = new Student();
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setAge(rs.getInt("age"));
list.add(p);
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
DButil.close(con);
}
return list;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>myServlet</servlet-name>
<servlet-class>com.yiki.Servlet.myServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>findServler</servlet-name>
<servlet-class>com.yiki.Servlet.findServler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/servlet/myServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>findServler</servlet-name>
<url-pattern>/servlet/findServler</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
增删查改servlet
package com.yiki.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yiki.dbutil.Student;
import com.yiki.dbutil.StudentImpl;
public class myServlet extends HttpServlet {
StudentImpl dao = new StudentImpl();
Student student = new Student();
ArrayList<Student> list = new ArrayList<Student>();
private String action;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
action = request.getParameter("action");
System.out.print(action);
if(action!=null){
this.action=request.getParameter("action");
if(action.equals("insert")){//插入
try {
String name = request.getParameter("name");
byte[] n = name.getBytes("ISO-8859-1");
int age = Integer.parseInt(request.getParameter("age"));
student.setName(name);
student.setAge(age);
dao.add(student);
request.getRequestDispatcher("/success.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
else if(action.equals("look")){//查看总表
try {
int count = dao.findCount();
List<Student> list = dao.query();
request.setAttribute("list", list);
request.setAttribute("count", count);
request.getRequestDispatcher("/look.jsp").forward(request, response);
}
catch (Exception e) {
e.printStackTrace();
}
}
else if(action.equals("delete")){
int id = Integer.parseInt(request.getParameter("ids"));
student.setId(id);
dao.delete(id);
}
else if(action.equals("update")){
String name = request.getParameter("name");
byte[] n = name.getBytes("ISO-8859-1");
int id = Integer.parseInt(request.getParameter("ids"));
int age = Integer.parseInt(request.getParameter("age"));
student.setName(name);
student.setAge(age);
student.setId(id);
dao.Update(student);
request.getRequestDispatcher("/success.jsp").forward(request, response);
//http://localhost:8096//JSP-07/success.jsp 不共享一个request
//response.sendRedirect("../success.jsp");
}
else if(action.equals("quer")){
try {
int id = Integer.parseInt(request.getParameter("ids"));
Student s = dao.getSbyID(id);
request.setAttribute("quer", s);
request.getRequestDispatcher("/querbyid.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
分页servlet
package com.yiki.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.yiki.dbutil.Student;
import com.yiki.dbutil.StudentImpl;
public class findServler extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int currPage=1;
if(request.getParameter("page")!=null){
currPage=Integer.parseInt(request.getParameter("page"));
}
StudentImpl dao = new StudentImpl();
List<Student> list = dao.find(currPage);
request.setAttribute("list", list);
int pages; //总页数
int count=dao.findCount(); //查询总记录数
if(count%Student.PAGE_SIZE==0){
pages=count/Student.PAGE_SIZE;
}else{
pages=count/Student.PAGE_SIZE+1;
}
StringBuffer sb = new StringBuffer();
//通过循环构建分页条
for(int i=1;i<=pages;i++){
if(i==currPage){ //判断是否为当前页
sb.append("『"+i+"』"); //构建分页条
}else{
sb.append("<a href='findServler?page="+i+"'>"+i+"</a>"); //构建分页条 !!!!注意路径!
}
sb.append(" ");
}
request.setAttribute("bar", sb.toString());
request.getRequestDispatcher("../product.jsp").forward(request, response);//注意这里的路径!
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
JSP结构
首页:注意看路径
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"
contentType="text/html; charset=gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<h1 align="center">Welcome</h1>
<body>
<table align="center">
<tr>
<td><a href="servlet/myServlet?action=look">查看总表</a></td>
<td><a href="delete.jsp">删除数据</a></td>
<td><a href="insert.jsp">插入数据</a></td>
<td><a href="update.jsp">更新数据</a></td>
<td><a href="querbyform.jsp">查询数据</a></td>
<td><a href="servlet/findServler">分页显示</a></td>
</table>
</body>
</html>
查看总表
<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<table align="center" border="1">
<tr>
<td>id</td>
<td>name</td>
<td>age</td>
</tr>
<%
String name = null;
int id = 0;
int age = 0;
List<Student> list=(List<Student>)request.getAttribute("list");
for (int i = 0; i < list.size(); i++) {
Student s = (Student) list.get(i);
name = s.getName();
id = s.getId();
age = s.getAge();
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=age %></td>
</tr>
<%
}
%>
</table>
一共<%=request.getAttribute("count")%>条记录
<a href="../index.jsp">返回</a>
</body>
</html>
插入
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<form action="servlet/myServlet?action=insert" method="POST">
名字:<input type="text" name="name">
年龄:<input type="text" name="age">
<input type="submit" value="提交">
</form>
</body>
</html>
删除
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<h1 align="center">输入要删除的id</h1>
<form action="servlet/myServlet?action=delete" method="POST" >
id:<input type="text" name="ids">
<input type="submit" value="提交">
</form>
</body>
</html>
更新
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<h1>更新数据</h1>
<body>
<form action="servlet/myServlet?action=update" method="POST">
id:<input type="text" name="ids">
名字:<input type="text" name="name">
年龄:<input type="text" name="age">
<input type="submit" value="更新">
</form>
</body>
</html>
查询
<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<h1>输入要查询的id</h1>
<body>
<form action="servlet/myServlet?action=quer" method="POST">
id:<input type="text" name="ids">
<input type="submit" value="提交">
</form>
</body>
</html>
<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<h1>查询成功</h1>
<table align="center" border="1">
<tr>
<td>id</td>
<td>name</td>
<td>age</td>
</tr>
<%
Student s = (Student)request.getAttribute("quer");
String name = s.getName();
int ids = s.getId();
int age = s.getAge();
%>
<tr>
<td><%=ids%></td>
<td><%=name%></td>
<td><%=age%></td>
</tr>
</table>
<a href="../index.jsp">返回</a>
</body>
</html>
分页显示
<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<h1>查询成功</h1>
<table align="center" border="1">
<tr>
<td>id</td>
<td>name</td>
<td>age</td>
</tr>
<%
Student s = (Student)request.getAttribute("quer");
String name = s.getName();
int ids = s.getId();
int age = s.getAge();
%>
<tr>
<td><%=ids%></td>
<td><%=name%></td>
<td><%=age%></td>
</tr>
</table>
<a href="../index.jsp">返回</a>
</body>
</html>
跳转成功
<%@page import="com.yiki.dbutil.*"%>
<%@ page language="java" import="java.util.*,java.sql.*"
pageEncoding="gb2312"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>
<h1>操作成功</h1>
<a href="myServlet?action=look">查看</a>
<a href="../index.jsp">返回</a>
</body>
</html>