Java:Java Web--分頁效果

  • 先來看一看分頁的實現(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)增刪查改

  1. 創(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();
        }
        
    }

}
  1. 創(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();
        }
        
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末埋嵌,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子俱恶,更是在濱河造成了極大的恐慌雹嗦,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,378評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件合是,死亡現(xiàn)場離奇詭異了罪,居然都是意外死亡,警方通過查閱死者的電腦和手機聪全,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,970評論 3 399
  • 文/潘曉璐 我一進店門泊藕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人难礼,你說我怎么就攤上這事娃圆。” “怎么了蛾茉?”我有些...
    開封第一講書人閱讀 168,983評論 0 362
  • 文/不壞的土叔 我叫張陵讼呢,是天一觀的道長。 經(jīng)常有香客問我臀稚,道長吝岭,這世上最難降的妖魔是什么三痰? 我笑而不...
    開封第一講書人閱讀 59,938評論 1 299
  • 正文 為了忘掉前任吧寺,我火速辦了婚禮窜管,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘稚机。我一直安慰自己幕帆,他們只是感情好,可當我...
    茶點故事閱讀 68,955評論 6 398
  • 文/花漫 我一把揭開白布赖条。 她就那樣靜靜地躺著失乾,像睡著了一般。 火紅的嫁衣襯著肌膚如雪纬乍。 梳的紋絲不亂的頭發(fā)上碱茁,一...
    開封第一講書人閱讀 52,549評論 1 312
  • 那天,我揣著相機與錄音仿贬,去河邊找鬼纽竣。 笑死,一個胖子當著我的面吹牛茧泪,可吹牛的內(nèi)容都是我干的蜓氨。 我是一名探鬼主播,決...
    沈念sama閱讀 41,063評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼队伟,長吁一口氣:“原來是場噩夢啊……” “哼穴吹!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起嗜侮,我...
    開封第一講書人閱讀 39,991評論 0 277
  • 序言:老撾萬榮一對情侶失蹤港令,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后锈颗,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體缠借,經(jīng)...
    沈念sama閱讀 46,522評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,604評論 3 342
  • 正文 我和宋清朗相戀三年宜猜,在試婚紗的時候發(fā)現(xiàn)自己被綠了泼返。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,742評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡姨拥,死狀恐怖绅喉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情叫乌,我是刑警寧澤柴罐,帶...
    沈念sama閱讀 36,413評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站憨奸,受9級特大地震影響革屠,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,094評論 3 335
  • 文/蒙蒙 一似芝、第九天 我趴在偏房一處隱蔽的房頂上張望那婉。 院中可真熱鬧,春花似錦党瓮、人聲如沸详炬。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,572評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽呛谜。三九已至,卻和暖如春枪萄,著一層夾襖步出監(jiān)牢的瞬間隐岛,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,671評論 1 274
  • 我被黑心中介騙來泰國打工瓷翻, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留礼仗,地道東北人。 一個月前我還...
    沈念sama閱讀 49,159評論 3 378
  • 正文 我出身青樓逻悠,卻偏偏與公主長得像元践,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子童谒,可洞房花燭夜當晚...
    茶點故事閱讀 45,747評論 2 361

推薦閱讀更多精彩內(nèi)容

  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法单旁,類相關(guān)的語法,內(nèi)部類的語法饥伊,繼承相關(guān)的語法象浑,異常的語法,線程的語...
    子非魚_t_閱讀 31,664評論 18 399
  • 一. Java基礎(chǔ)部分.................................................
    wy_sure閱讀 3,814評論 0 11
  • 從三月份找實習(xí)到現(xiàn)在琅豆,面了一些公司愉豺,掛了不少,但最終還是拿到小米茫因、百度蚪拦、阿里、京東冻押、新浪驰贷、CVTE、樂視家的研發(fā)崗...
    時芥藍閱讀 42,278評論 11 349