今日完成了Servlet+JSP+JDBC的综合案例,实现对学生姓名,成绩,编号的增删改查:
连接数据库的类:
public class DBHelper { private static String driver="com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/classname?useUnicode=true&characterEncoding=UTF-8"; //数据库名 private static String username = "root"; //数据库用户名 private static String password = "123456"; //数据库用户密码 private static Connection conn=null; static { try { Class.forName(driver); } catch(Exception ex) { ex.printStackTrace(); } } public static Connection getConnection() throws SQLException { if(conn==null) { conn= DriverManager.getConnection(url,username,password); } return conn; } public static void main(String[] args) { try { Connection conn=DBHelper.getConnection(); if(conn!=null) { System.out.println("数据库连接正常"); } else { System.out.println("数据库连接异常"); } } catch(Exception ex) { ex.printStackTrace(); } } }
student数据类:
public class Studentdate { private Integer id; private String name; private Double score; private Date birthday; 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 Double getScore() { return score; } public void setScore(Double score) { this.score = score; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Studentdate(Integer id,String name,Double score,Date birthday) { this.id=id; this.name=name; this.score=score; this.birthday=birthday; } public Studentdate(){} }
servlet与filter:
@WebServlet("/student") public class StudentServlet extends HttpServlet { private StudentRepository studentrs=new StudentRepository(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String method=req.getParameter("method"); if(method==null){ method="findAll"; } switch(method.charAt(0)) { case 'f': List<Studentdate> list=null; try { list = studentrs.findAll(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } req.setAttribute("list", list); req.getRequestDispatcher("index.jsp").forward(req, resp); break; case 'd': String idstr=req.getParameter("id"); Integer id=Integer.parseInt(idstr); try { studentrs.delete(id); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } resp.sendRedirect("/biliwork2/student"); break; case 'F': String idstr2=req.getParameter("id"); Integer id2=Integer.parseInt(idstr2); try { req.setAttribute("studate", studentrs.Find(id2)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } req.getRequestDispatcher("update.jsp").forward(req, resp); break; } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub String method=req.getParameter("method"); switch(method.charAt(0)) { case 'a': String name=req.getParameter("name"); String scorestr=req.getParameter("score"); Double score=Double.parseDouble(scorestr); try { studentrs.add(name,score); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } resp.sendRedirect("/biliwork2/student"); case 'u': String name1=req.getParameter("name"); String idstr=req.getParameter("id"); Integer id=Integer.parseInt(idstr); String scorestr1=req.getParameter("score"); Double score1=Double.parseDouble(scorestr1); try { studentrs.update(id,name1,score1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } resp.sendRedirect("/biliwork2/student"); break; } } }
@WebFilter("/student") public class CharacterFilter implements Filter{ public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { // TODO Auto-generated method stub arg0.setCharacterEncoding("utf-8"); arg2.doFilter(arg0, arg1); } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
实现数据库的增删改查的类:
public class StudentRepository { public List<Studentdate> findAll() throws SQLException { List<Studentdate> list=new ArrayList<Studentdate>(); Connection conn=DBHelper.getConnection(); String sql="SELECT * FROM student"; PreparedStatement ps=conn.prepareStatement(sql); ResultSet rs=ps.executeQuery(); Studentdate studate=null; while(rs.next()) { Integer id=rs.getInt(1); String name=rs.getString(2); Double score=rs.getDouble(3); Date birthday=rs.getDate(4); studate=new Studentdate(id,name,score,birthday); list.add(studate); } return list; } public void add(String name,Double score) throws SQLException { PreparedStatement ps=null; Connection conn=DBHelper.getConnection(); conn.setAutoCommit(false); String sql="INSERT INTO student(name,score,birthday) values(?,?,?)"; ps= conn.prepareStatement(sql); ps.setString(1,name); ps.setDouble(2,score); ps.setDate(3, new java.sql.Date(10)); ps.executeUpdate(); conn.commit(); } public void delete(Integer id) throws SQLException { PreparedStatement ps=null; Connection conn=DBHelper.getConnection(); conn.setAutoCommit(false); String sql="DELETE FROM student where id=?"; ps=conn.prepareStatement(sql); ps.setInt(1, id); ps.executeUpdate(); conn.commit(); } public Studentdate Find(Integer id) throws SQLException { Studentdate studate=null; PreparedStatement ps=null; Connection conn=DBHelper.getConnection(); conn.setAutoCommit(false); ResultSet rs=null; String sql="SELECT * FROM student where id=?"; ps=conn.prepareStatement(sql); ps.setInt(1,id); rs=ps.executeQuery(); while(rs.next()) { String name=rs.getString(2); Double score=rs.getDouble(3); Date birthday=rs.getDate(4); studate=new Studentdate(id,name,score,birthday); } return studate; } public void update(Integer id,String name,Double score) throws SQLException { PreparedStatement ps=null; Connection conn=DBHelper.getConnection(); conn.setAutoCommit(false); String sql="UPDATE student set name=?,score=? where id=?"; ps= conn.prepareStatement(sql); ps.setString(1,name); ps.setDouble(2,score); ps.setInt(3,id); ps.executeUpdate(); conn.commit(); } }
以及三个jsp文件实现修改,增加,查询,删除界面显示:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'add.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="/biliwork2/student" method="post"> <table> <tr> <td>姓名</td> <td><input type="text" name="name"></td> </tr> <tr> <td>成绩</td> <td><input type="text" name="score"></td> </tr> <tr> <td><input type="hidden" name="method" value="add"> <td><input type="submit" value="提交"></td> </tr> </table> </form> <br> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>学生管理系统</h1> <table> <tr> <th>编号</th> <th>姓名</th> <th>成绩</th> <th>注册日期</th> <th>操作</th> </tr> <c:forEach items="${list}" var="studentdate" > <tr> <td>${studentdate.id}</td> <td>${studentdate.name}</td> <td>${studentdate.score}</td> <td>${studentdate.birthday}</td> <td> <a href="/biliwork2/student?method=delete&id=${studentdate.id }">删除</a> <a href="/biliwork2/student?method=Find&id=${studentdate.id }">修改</a> </tr> </c:forEach> </table> <br> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'add.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="/biliwork2/student" method="post"> <table> <tr> <td>编号</td> <td><input type="text" name="id" readonly value="${studate.id }"></td> </tr> <tr> <td>姓名</td> <td><input type="text" name="name" value="${studate.name }"></td> </tr> <tr> <td>成绩</td> <td><input type="text" name="score" value="${studate.score }"></td> </tr> <tr> <td><input type="hidden" name="method" value="update"> <td><input type="submit" value="修改"></td> </tr> </table> </form> <br> </body> </html>