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();

        }

    }



}
相关推荐
2401_857439692 分钟前
SpringBoot框架在资产管理中的应用
java·spring boot·后端
怀旧6663 分钟前
spring boot 项目配置https服务
java·spring boot·后端·学习·个人开发·1024程序员节
李老头探索5 分钟前
Java面试之Java中实现多线程有几种方法
java·开发语言·面试
芒果披萨11 分钟前
Filter和Listener
java·filter
qq_49244844615 分钟前
Java实现App自动化(Appium Demo)
java
阿华的代码王国24 分钟前
【SpringMVC】——Cookie和Session机制
java·后端·spring·cookie·session·会话
找了一圈尾巴1 小时前
前后端交互通用排序策略
java·交互
哎呦没3 小时前
SpringBoot框架下的资产管理自动化
java·spring boot·后端
m0_571957585 小时前
Java | Leetcode Java题解之第543题二叉树的直径
java·leetcode·题解
魔道不误砍柴功7 小时前
Java 中如何巧妙应用 Function 让方法复用性更强
java·开发语言·python