- 先來看一看分頁的實現(xiàn)原理
萬能公式.jpg
項目目錄.PNG
首先,新建Java Web項目
一. 梳理業(yè)務(wù)邏輯
重定向到URL(跳轉(zhuǎn)到StudentViewAction頁面)//index.jsp頁面
1.從頁面接收可變的值
2.接收值有問題時,初始化為1
3.如果沒有問題,把String類型接收值強轉(zhuǎn)成Integer
4.實例DAO方法,調(diào)用findStudentListByPageCount()方法(該方法得到總條數(shù))
5.計算總頁數(shù):總頁數(shù) = 總條數(shù) % 頁容量
6.判斷接收到頁面?zhèn)鱽淼闹凳欠裥∮?頁
7.調(diào)用DAO中findStudentListByPageCount()(該方法獲取數(shù)據(jù)集合)
8.封裝打包頁面
9.轉(zhuǎn)發(fā)頁面
request.getRequestDispatcher("list.jsp").forward(request, response);
//request.getRequestDispatcher("list.jsp") 找到要轉(zhuǎn)發(fā)的頁面
//forward(request, response); 實現(xiàn)轉(zhuǎn)發(fā)
二. 實現(xiàn)界面展示
1.封裝工具類JDBCUtil.java文件, 作用是連接數(shù)據(jù)庫
package com.fyl.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
/**
* 文檔注釋(Java連接數(shù)據(jù)庫的工具類)
*
*/
public class JDBCUtil {
// 注意:四個屬性:驅(qū)動, 地址(URL), 用戶名, 密碼
// 驅(qū)動類:通過一個類名告訴java我現(xiàn)在使用的是什么數(shù)據(jù)庫
private static final String CONN_DRIVER = "com.mysql.jdbc.Driver";
// URL:告訴Java我的數(shù)據(jù)庫的具體位置(網(wǎng)絡(luò)標識:通過什么端口哪臺電腦獲取什么資源)
private static final String CONN_URL = "jdbc:mysql://127.0.0.1:3306/student_db?characterEncoding=UTF-8";
// 用戶名
private static final String CONN_USER_NAME = "root";
// 密碼
private static final String CONN_USER_PASS = "123456";
public static Connection getConn() {
// 創(chuàng)建方法的返回變量
Connection conn = null;
try {
// 1.加載驅(qū)動類 讓Java知道我們創(chuàng)建什么數(shù)據(jù)庫的實例
Class.forName(CONN_DRIVER);
// 通過已經(jīng)加載好的驅(qū)動類給我們提供連接
conn = DriverManager.getConnection(CONN_URL, CONN_USER_NAME,
CONN_USER_PASS);
} catch (ClassNotFoundException e) {
System.out.println("add DriverManager error!");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("SQL error!");
e.printStackTrace();
}
return conn;
}
public static void closeAll(ResultSet set, PreparedStatement ps,
Connection conn) {
try {
if (null != set) {
set.close();
}
if (null != ps) {
ps.close();
}
if (null != conn) {
conn.close();
}
} catch (SQLException e) {
System.out.println("closeAll ERROR!");
e.printStackTrace();
}
}
public static void main(String[] args) {
// 獲取數(shù)據(jù)庫連接
Connection conn = JDBCUtil.getConn();
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("請素輸入要查看的數(shù)據(jù):");
int i = scan.nextInt();
int start = (i - 1) * 10;
int size = 10;
// 2.編寫SQL語句(查詢id > 0的數(shù)據(jù), 連續(xù)查詢10條記錄)
String sql = "SELECT * FROM student WHERE s_id LIMIT ?,?";
// SELECT * FROM student WHERE s_id > 10 AND s_id <= (10 + 10)
// 3.運行SQL語句
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, start);
ps.setInt(2, size);
// 4.執(zhí)行后返回結(jié)果(execute執(zhí)行Query結(jié)果)
ResultSet set = ps.executeQuery();
System.out.println("學(xué)生編號\t學(xué)生姓名\t學(xué)生年齡\t入學(xué)時間\t學(xué)費");
for (; set.next();) {
System.out.print(set.getInt("S_ID") + "\t");
System.out.print(set.getString("S_NAME") + "\t");
System.out.print(set.getInt("S_AGE") + "\t");
System.out.print(set.getDate("S_INTODATE") + "\t");
System.out.print(set.getDouble("S_MONEY") + "\t");
System.out.println();
}
} catch (SQLException e) {
System.out.println("select error");
e.printStackTrace();
}
}
}
}
2.創(chuàng)建數(shù)據(jù)庫實體類Student.java文件(Model層)
package com.fyl.entity;
import java.io.Serializable;
import java.util.Date;
/**
* 實體類
* @author Administrator
*
*/
public class Student implements Serializable {
private static final long serialVersionUID = 1L;//添加唯一標識
private Integer id;
private String name;
private int age;
private Date date;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
3.index.jsp界面(呈現(xiàn)給用戶的第一個界面)
<head>
<title>系統(tǒng)首頁</title>
</head>
<body>
<%
// 重定向到URL
request.getRequestDispatcher("StudentViewAction").forward(request, response);
%>
</body>
4.新建servlet文件StudentViewAction.java(Controller層)
package com.fyl.web;
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.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//封裝數(shù)據(jù)給頁面
//整理頁面需要的數(shù)據(jù)
int pageIndex = 0;//頁面 //頁面每次請求傳過來的
int pageSize = 10;//
int totalCount = 0;
int totalPge = 0;
List<Student> list = null;
//從頁面接收可變的值
String pi = request.getParameter("pageIndex");
//pi有問題的時候,初始化為1
if (null == pi || "".equals(pi)) {
pi = "1";
}
//如果pi沒有問題的時候
pageIndex = Integer.parseInt(pi);
//從數(shù)據(jù)接收值
StudentDAO dao = new StudentDAOImpl();
//調(diào)用DAO方法
totalCount = dao.findStudentListByPageCount();
//計算總頁數(shù)
totalPge = totalCount % pageSize == 0?totalCount/pageSize:totalCount/pageSize + 1;
//判斷pageIndex的邊界值
if (pageIndex < 1) {
pageIndex = 1;
}
if (pageIndex > totalPge) {
pageIndex = totalPge;
}
//獲取數(shù)據(jù)集合
list = dao.findStudentListByPage(pageIndex, pageSize);
//封裝打包頁面
request.setAttribute("pageIndex", pageIndex);
request.setAttribute("pageSize", pageSize);
request.setAttribute("totalCount", totalCount);
request.setAttribute("totalPge", totalPge);
request.setAttribute("list", list);
//轉(zhuǎn)發(fā)頁面
request.getRequestDispatcher("list.jsp").forward(request, response);
}
}
新建list.jsp界面接收StudentViewAction傳來的值
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>數(shù)據(jù)展示</title>
<script type="text/javascript">
function goUpdate(id){
window.location.href = "StudentFindByIDViewAction?id=" + id;
}
function goDelete(id){
var con = window.confirm("您確定刪除ID為" + id + "這條數(shù)據(jù)嗎?" );
if(con){
//刪除
window.location.href = "StudentDeleteAction?id=" + id;
}
}
function goPage(pageIndex){
window.location.href = "StudentViewAction?pageIndex="+pageIndex;
}
function goPage(pageIndex){
window.location.href = "StudentViewAction?pageIndex="+pageIndex;
}
function goAdd(){
window.location.href = "add.jsp";
}
</script>
</head>
<body>
<input type="button" value="添加新學(xué)生" onclick="goAdd();" />
<table border="1">
<tr>
<th colspan="6">
一共查詢出${totalCount}條數(shù)據(jù),每頁展示${pageSize}條,一共有${totalPage}頁,當前瀏覽的是第${pageIndex}頁
</th>
</tr>
<tr>
<th>學(xué)生ID</th>
<th>學(xué)生姓名</th>
<th>學(xué)生年齡</th>
<th>入學(xué)時間</th>
<th>學(xué)費</th>
<th>操作</th>
</tr>
<c:forEach items="${list}" var="s">
<tr align="center">
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.age}</td>
<td><fmt:formatDate pattern="yyyy年MM月dd日" value="${s.date}" /></td>
<td>
<fmt:formatNumber type="currency" value="${s.money}" />
</td>
<td>
<input type="button" value="更新" onclick="goUpdate(${s.id});" /> ||
<input type="button" value="刪除" onclick="goDelete(${s.id});" />
</td>
</tr>
</c:forEach>
<tr>
<th colspan="6">
<input type="button" value="首頁" onclick="goPage(1);"/>
<c:choose>
<c:when test="${pageIndex <= 1}">
<input type="button" value="上一頁" disabled="disabled" />
</c:when>
<c:otherwise>
<input type="button" value="上一頁" onclick="goPage(${pageIndex-1});"/>
</c:otherwise>
</c:choose>
<c:choose>
<c:when test="${pageIndex >= totalPage}">
<input type="button" value="下一頁" disabled="disabled" />
</c:when>
<c:otherwise>
<input type="button" value="下一頁" onclick="goPage(${pageIndex+1});"/>
</c:otherwise>
</c:choose>
<input type="button" value="末頁" onclick="goPage(${totalPge});"/>
</th>
</tr>
</table>
</body>
</html>
三. 實現(xiàn)增刪查改
- 創(chuàng)建接口, 新建StudentDAO.java接口文件, 添加增刪查改方法
package com.fyl.dao;
import java.util.List;
import com.fyl.entity.Student;
public interface StudentDAO {
/**
* 更據(jù)id刪除
* @param id
* @return
* @throws RuntimeException
*/
public boolean deleteStudent(Integer id) throws RuntimeException;
/**
* 根據(jù)ID查詢單個學(xué)生對象
* @param id
* @return
* @throws RuntimeException
*/
public Student findStudentByID(Integer id) throws RuntimeException;
/*
* 添加學(xué)生方法
* @param student 要添加的學(xué)生
* @return 添加成功返回true 添加失敗返回false
* @throws RuntimeException
*/
public boolean insertStudent(Student student)throws RuntimeException;
/**
* 查詢數(shù)據(jù)庫的總條數(shù)
* @return 總條數(shù)
* @throws RuntimeException
*/
public int findStudentListByPageCount() throws RuntimeException;
/**
* 獲取分頁數(shù)集合
* @param pageIndex 頁碼
* @param pageSize 頁容量
* @return 已經(jīng)分頁的list集合
* @throws RuntimeException
*/
public List<Student> findStudentListByPage(Integer pageIndex, Integer pageSize) throws RuntimeException;
/*
* 更新學(xué)生信息
* @param student
* @return
* @throws RuntimeException
*/
public boolean updateStudent(Student student) throws RuntimeException;
}
2.新建StudentDAOImpl.java文件,實現(xiàn)接口
package com.fyl.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.fyl.dao.StudentDAO;
import com.fyl.entity.Student;
import com.fyl.util.JDBCUtil;
public class StudentDAOImpl implements StudentDAO {
// TODO
public int findStudentListByPageCount() throws RuntimeException {
// 1.創(chuàng)建方法的返回變量
int totalCount = 0;
// 3.獲取數(shù)據(jù)庫連接
Connection conn = JDBCUtil.getConn();
// 4.編寫SQL語句
String sql = "SELECT COUNT(S_ID) FROM STUDENT";
// 執(zhí)行SQL語句
PreparedStatement ps = null;
ResultSet set = null;
try {
ps = conn.prepareStatement(sql);
set = ps.executeQuery();
//處理
if (set.next()) {
totalCount = set.getInt(1);
}
} catch (SQLException e) {
// TODO
e.printStackTrace();
} finally {
JDBCUtil.closeAll(set, ps, conn);
}
return totalCount;
}
// TODO
public List<Student> findStudentListByPage(Integer pageIndex,
Integer pageSize) throws RuntimeException {
List<Student> list = new ArrayList<Student>();
//2.1獲取數(shù)據(jù)庫連接
Connection conn = JDBCUtil.getConn();
//3. 創(chuàng)建SQL語句
String sql = "SELECT * FROM STUDENT WHERE S_ID LIMIT ?,?";
//4.執(zhí)行SQL語句
PreparedStatement ps = null;
ResultSet set = null;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, (pageIndex-1) * pageSize);
ps.setInt(2, pageSize);
set = ps.executeQuery();
Student s = null;
while (set.next()) {
s = new Student();
//封裝數(shù)據(jù)
s.setId(set.getInt("S_ID"));
s.setName(set.getString("S_NAME"));
s.setAge(set.getInt("S_AGE"));
s.setMoney(set.getDouble("S_MONEY"));
s.setDate(set.getDate("S_INTODATE"));
// 將封裝好的Student對像裝入集合
list.add(s);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JDBCUtil.closeAll(set, ps, conn);
}
return list;
}
public boolean insertStudent(Student student) throws RuntimeException {
// TODO Auto-generated method stub
//1.定義方法返回變量
boolean con = false;
//3. 獲取數(shù)據(jù)庫連接
Connection conn = JDBCUtil.getConn();
//4. 編寫SQL語句
String sql = "INSERT INTO STUDENT (S_NAME,S_AGE,S_INTODATE,S_MONEY) VALUES (?,?,?,?)";
// 5. 執(zhí)行SQL語句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
// 6. 是否有占位符賦值?
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setDate(3, new java.sql.Date(student.getDate().getTime()));
ps.setDouble(4, student.getMoney());
int count = ps.executeUpdate(); // 執(zhí)行增 刪 改 SQL 返回int類型的受影響行數(shù)
// 7. 改變方法的返回值
con = count>0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 2. 返回con
return con;
}
// TODO 根據(jù)id查詢
public Student findStudentByID(Integer id) throws RuntimeException {
//創(chuàng)建方法的返回值
Student student = null;
Connection conn = JDBCUtil.getConn();
//編寫SQL語句
String sql = "SELECT * FROM STUDENT WHERE S_ID = ?";
//執(zhí)行SQL語句
PreparedStatement ps = null;
ResultSet set = null;
try {
ps = conn.prepareStatement(sql);
//是否有占位符
ps.setInt(1, id);
set = ps.executeQuery();
if(set.next()){
//創(chuàng)建實例對象封裝查詢數(shù)據(jù)
student = new Student();
student.setId(set.getInt("S_ID"));
student.setAge(set.getInt("S_AGE"));
student.setDate(set.getDate("S_INTODATE"));
student.setMoney(set.getDouble("S_MONEY"));
student.setName(set.getString("S_NAME"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.closeAll(set, ps, conn);
}
return student;
}
// TODO 更新學(xué)生信息
public boolean updateStudent(Student student) throws RuntimeException {
//創(chuàng)建方法的返回值
boolean con = false;
//獲取數(shù)據(jù)庫連接
Connection conn = JDBCUtil.getConn();
//編寫SQL語句
String sql = "UPDATE STUDENT SET S_NAME=?,S_AGE=?,S_INTODATE=?,S_MONEY=? WHERE S_ID=?";
//執(zhí)行SQL語句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
//是否有占位符
ps.setString(1, student.getName());
ps.setInt(2, student.getAge());
ps.setDate(3, new java.sql.Date(student.getDate().getTime()));
ps.setDouble(4, student.getMoney());
ps.setInt(5, student.getId());
int count = ps.executeUpdate();
con = count>0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
// TODO delete
public boolean deleteStudent(Integer id) throws RuntimeException {
//創(chuàng)建方法的返回變量
boolean con = false;
//獲取數(shù)據(jù)庫鏈接
Connection conn = JDBCUtil.getConn();
//編寫SQL語句
String sql = "DELETE FROM STUDENT WHERE S_ID = ?";
//執(zhí)行SQL語句
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
int count = ps.executeUpdate();
con = count > 0?true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
JDBCUtil.closeAll(null, ps, conn);
}
return con;
}
// TODO main
public static void main(String[] args) {
StudentDAO dao = new StudentDAOImpl();
System.out.println(dao.findStudentListByPageCount());
}
}
3.創(chuàng)建servlet文件StudentAddAction.java接收用戶傳入的值,添加到數(shù)據(jù)庫并展示到list.jsp(增)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentAddAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設(shè)置請求來源的編碼
request.setCharacterEncoding("UTF-8");
//1. 接收頁面數(shù)據(jù)
String studentName = request.getParameter("studentName");
String studentAge = request.getParameter("studentAge");
String intoDate = request.getParameter("intoDate");
String money = request.getParameter("money");
//2. 封裝
Student student = new Student();
student.setName(studentName);
student.setAge(Integer.parseInt(studentAge));
student.setMoney(Double.parseDouble(money));
// String 轉(zhuǎn) 時間
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = df.parse(intoDate);
student.setDate(d);
} catch (ParseException e) {
e.printStackTrace();
}
// 3. 創(chuàng)建DAO層對象添加到數(shù)據(jù)庫
StudentDAO dao = new StudentDAOImpl();
boolean con = dao.insertStudent(student);
if(con){
// 添加成功
response.sendRedirect("StudentViewAction");
}else{
// 添加失敗
// 通過服務(wù)器的響應(yīng)流主動向客戶端發(fā)送信息
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String msg = "<script type=\"text/javascript\">alert(\"添加失敗\");history.back();</script>";
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
}
}
}
4.創(chuàng)建servlet文件StudentDeleteAction.java接收用戶傳入的值,刪除數(shù)據(jù)庫中指定文件并展示到list.jsp(刪)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
public class StudentDeleteAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1. 確定編碼
request.setCharacterEncoding("UTF-8");
//2. 獲取頁面數(shù)據(jù)
String id = request.getParameter("id");
//3. 創(chuàng)建DAO方法執(zhí)行刪除
StudentDAO dao = new StudentDAOImpl();
boolean con = dao.deleteStudent(Integer.parseInt(id));
if(con){
//添加成功
response.sendRedirect("StudentViewAction");
}else{
//添加失敗
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String msg = "<script type=\"text/javascript\">alert(\"添加失敗\");history.back();</script>";
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
}
}
}
- 創(chuàng)建servlet文件StudentFindByIDViewAction.java接收用戶傳入的值,查詢數(shù)據(jù)庫中指定文件并展示到list.jsp(查)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentFindByIDViewAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設(shè)置編碼
request.setCharacterEncoding("UTF-8");
//接收頁面輸入
String id = request.getParameter("id");
//創(chuàng)建DAO層對象
StudentDAO dao = new StudentDAOImpl();
Student student = dao.findStudentByID(new Integer(id));
request.setAttribute("stu", student);
request.getRequestDispatcher("update.jsp").forward(request, response);
}
}
6.創(chuàng)建servlet文件StudentUpdateAction.java接收用戶傳入的值,更新數(shù)據(jù)庫中指定文件并展示到list.jsp(改)
package com.fyl.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fyl.dao.StudentDAO;
import com.fyl.dao.impl.StudentDAOImpl;
import com.fyl.entity.Student;
public class StudentUpdateAction extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//設(shè)置請求來源的編碼格式
request.setCharacterEncoding("UTF-8");
//1. 設(shè)置接收頁面數(shù)據(jù)
String studentId = request.getParameter("studentId");
String studentName = request.getParameter("studentName");
String studentAge = request.getParameter("studentAge");
String intoDate = request.getParameter("Date");
String money = request.getParameter("money");
//2. 封裝
Student student = new Student();
String studentId1 = studentId.trim();
student.setId(Integer.parseInt(studentId1));
student.setName(studentName);
student.setAge(Integer.parseInt(studentAge));
student.setMoney(Double.parseDouble(money));
//String轉(zhuǎn)時間
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = df.parse(intoDate);
student.setDate(d);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//3. 創(chuàng)建DAO層對象添加到數(shù)據(jù)庫
StudentDAO dao = new StudentDAOImpl();
boolean con = dao.updateStudent(student);
if(con)0.{
//添加成功
response.sendRedirect("StudentViewAction");
}else{
//添加失敗
//通過服務(wù)器的響應(yīng)流主動向客戶端發(fā)送信息
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
String msg = "<script type=\"text/javascript\">alert(\"添加失敗\");history.back();</script>";
PrintWriter out = response.getWriter();
out.print(msg);
out.flush();
out.close();
}
}
}