javaEE14(网站第9章常用开发组件课后题第4题)

StudentDao:

java 复制代码
package dao;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.util.ArrayList;

import java.util.List;



import util.JdbcUtil;

import entity.Student;

public class StudentDao {

   //�����ݿ�������û���¼�ķ���add()

   public void add(Student student) throws Exception{

        Connection conn = null;

        PreparedStatement ps = null;

        try {

               conn = JdbcUtil.getConnection();

               String sql = "insert into student2  values (null,?,?,?,?) ";

               ps = conn.prepareStatement(sql);

               ps.setString(1, student.getSno());

               ps.setString(2,student.getSname());

               ps.setString(3,student.getSex());

               ps.setString(4,student.getPhoto());

               ps.executeUpdate();

        }finally {JdbcUtil.free(null,ps, conn);}

   }

   //�޸����ݿ��û���¼�ķ���update()

   public void update(Student student) throws Exception{

       Connection conn = null;

       PreparedStatement ps = null;

       try {

              conn = JdbcUtil.getConnection();

              String sql = "update student2 set sno=?,sname=?,sex=?,photo=? where id=? ";

              ps = conn.prepareStatement(sql);

              ps.setString(1,student.getSno());

              ps.setString(2,student.getSname());

              ps.setString(3, student.getSex());

              ps.setString(4, student.getPhoto());

              ps.setInt(5, student.getId());

              ps.executeUpdate();

       }finally {JdbcUtil.free(null,ps, conn);}

   }

   //ɾ�����ݿ��û���¼�ķ���delete()

   public void delete(int id) throws Exception{

        Connection conn = null;

        PreparedStatement ps = null;

        try {

              conn = JdbcUtil.getConnection();

              String sql = "delete from student2 where id=?";

              ps = conn.prepareStatement(sql);

              ps.setInt(1,id);

              ps.executeUpdate();

       }finally {JdbcUtil.free( null,ps, conn);}

   }

   //����id��ѯ�û��ķ���findStudentById()

   public Student findStudentById(int id) throws Exception{

       Connection conn = null;

       PreparedStatement ps = null;

       ResultSet rs = null;

       Student student=null;

       try {

              conn = JdbcUtil.getConnection();

              String sql = "select * from student2 where id=? ";

              ps = conn.prepareStatement(sql);

              ps.setInt(1, id);

              rs=ps.executeQuery();

              if(rs.next()){

                 student=new Student();

                 student.setId(rs.getInt(1));

                 student.setSno(rs.getString(2));

                 student.setSname(rs.getString(3));

                 student.setSex(rs.getString(4));

              }

       }finally {JdbcUtil.free(rs, ps, conn);}

       return student;

   }

   //��ѯȫ���û��ķ���QueryAll()

   public List<Student> query() throws Exception{

       Connection conn = null;

       PreparedStatement ps = null;

       ResultSet rs = null;

       List<Student> studentList=new ArrayList<Student>();

       try {

              conn = JdbcUtil.getConnection();

              String sql = "select * from student2 ";

              ps=conn.prepareStatement(sql);

              rs=ps.executeQuery();

              while(rs.next()){

                 Student student=new Student();

                 student.setId(rs.getInt(1));

                 student.setSno(rs.getString(2));

                 student.setSname(rs.getString(3));

                 student.setSex(rs.getString(4));

                 student.setPhoto(rs.getString(5));

                 studentList.add(student);

              }

       }finally {JdbcUtil.free(rs, ps, conn);}

       return studentList;

   }

}

Servlet:

java 复制代码
package servlet;



import java.io.File;

import java.io.IOException;

import java.io.PrintWriter;

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.oreilly.servlet.MultipartRequest;

import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import com.oreilly.servlet.multipart.FileRenamePolicy;



import dao.StudentDao;

import entity.Student;

/**

 * Servlet implementation class StudentServlet

 */

@WebServlet("/admin/studentServlet")

public class StudentServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    StudentDao studentDao = new StudentDao();

    /**

     * @see HttpServlet#HttpServlet()

     */

    public StudentServlet() {

        super();

        // TODO Auto-generated constructor stub

    }

    /**

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    protected void doGet(HttpServletRequest request,

            HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        this.doPost(request, response);

    }



    /**

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse

     *      response)

     */

    protected void doPost(HttpServletRequest request,

            HttpServletResponse response) throws ServletException, IOException {

        // TODO Auto-generated method stub

        request.setCharacterEncoding("UTF-8");

        String op = request.getParameter("op");

        if ("add".equals(op)) {

            this.add(request, response);

        } else if ("update".equals(op)) {

            this.update(request, response);



        } else if ("delete".equals(op)) {

            this.delete(request, response);

        } else if ("query".equals(op)) {

            this.query(request, response);

        }

    }



    private void add(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

        String saveDirectory =this.getServletContext().getRealPath("/photo");  

        int maxPostSize =3  * 1024 * 1024 ; 

        String info="";

        FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();

        MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"utf-8",policy);

        String photo=multi.getFilesystemName("photo");

        if(photo==null){

            photo="";

        }

        StudentDao studentDao = new StudentDao();

        try {

           

                Student student = new Student();

                student.setSno(multi.getParameter("sno"));

                student.setSname(multi.getParameter("sname"));

                student.setSex(multi.getParameter("sex"));

                student.setPhoto(photo);

                studentDao.add(student);

                info="添加成功";

           

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

            info="添加失败";

           

        }

        request.setAttribute("info",info);

        request.getRequestDispatcher("/admin/student/add.jsp").forward(request, response);

       

    }

    private void update(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

        String saveDirectory =this.getServletContext().getRealPath("/photo");  

       

        int maxPostSize =3  * 1024 * 1024 ;  //���ϴ���С���ƣ�3M

        FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();

        MultipartRequest multi = new MultipartRequest(request, saveDirectory, maxPostSize,"utf-8",policy);

        String photo=multi.getFilesystemName("photo");

        String oldphoto=multi.getParameter("oldphoto");

        if(photo==null){

            photo=oldphoto;

        }

        else{

            if(!"".equals(oldphoto))

                new File(saveDirectory+"/"+oldphoto).delete();

        }

            StudentDao studentDao = new StudentDao();



            try {

                   Student student = new Student();

                    student.setId(Integer.parseInt(multi.getParameter("id")));

                   student.setSno(multi.getParameter("sno"));

                   student.setSname(multi.getParameter("sname"));

                   student.setSex(multi.getParameter("sex"));

                   student.setPhoto(photo);

                   studentDao.update(student);

                   response.sendRedirect("/zdwxz/admin/studentServlet?op=query");

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

                response.setContentType("text/html;charset=UTF-8");

                PrintWriter out = response.getWriter();

                out.print("<script>alert('更新失败')</script>");

            }

    }

    private void delete(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

       

        try {

            studentDao.delete(Integer.parseInt(request.getParameter("id")));

            String photo=request.getParameter("photo");

            String appPath=this.getServletContext().getRealPath("/photo");

            if(!"".equals(photo))

              new File(appPath+"/"+photo).delete();

            response.sendRedirect("/zdwxz/admin/studentServlet?op=query");

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

    private void query(HttpServletRequest request, HttpServletResponse response)

            throws ServletException, IOException {

        // TODO Auto-generated method stub

        try {

            List<Student> studentList=studentDao.query();

            request.setAttribute("studentList",studentList );

           request.getRequestDispatcher("/admin/student/query.jsp").forward(request, response);

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }



}
相关推荐
秋天下着雨2 分钟前
apifox调用jar程序
java·python·jar
m0_748251087 分钟前
docker安装nginx,docker部署vue前端,以及docker部署java的jar部署
java·前端·docker
A22748 分钟前
Redis——缓存雪崩
java·redis·缓存
Mr.朱鹏9 分钟前
操作002:HelloWorld
java·后端·spring·rabbitmq·maven·intellij-idea·java-rabbitmq
顽疲30 分钟前
从零用java实现 小红书 springboot vue uniapp (6)用户登录鉴权及发布笔记
java·vue.js·spring boot·uni-app
oscar9991 小时前
Maven项目中不修改 pom.xml 状况下直接运行OpenRewrite的配方
java·maven·openrewrite
南宫生1 小时前
力扣-数据结构-3【算法学习day.74】
java·数据结构·学习·算法·leetcode
工业甲酰苯胺1 小时前
聊一聊 C#线程池 的线程动态注入
java·开发语言·c#
m0_748240251 小时前
docker--压缩镜像和加载镜像
java·docker·eureka
向宇it1 小时前
【从零开始入门unity游戏开发之——C#篇30】C#常用泛型数据结构类——list<T>列表、`List<T>` 和数组 (`T[]`) 的选择
java·开发语言·数据结构·unity·c#·游戏引擎·list