JAVA课程之简易课程登记
实现技术JSP+Servlet+MySQL
思想:首先前台用jsp获取数据,然后用Form表单传值给Servlet,Servlet操作MySQL,获取数据再通过jsp显示
1.jsp功能选择界面
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ page import ="MySQL.*" %> 4 <!DOCTYPE html> 5 <html> 6 <head> 7 <meta charset="UTF-8"> 8 <title>Insert title here</title> 9 </head> 10 <body style="text-align: center;"> 11 12 13 <!--设置body的样式 --> 14 <div id="menu" style="background-color:#D5D5D5;height:30px;width:;"> 15 <!-- 添加标题 --> 16 <div id="content" style="float:left;"> 17 课程基本信息管理系统 18 </div> 19 <!-- 添加div样式 --> 20 </div> 21 <div id="menu-m" style="background-color:#ccffff;height:40px;width:200px;text-align:center;"> 22 <br> 23 <!-- 添加跳转的A标签 --> 24 <b><a href="add.jsp">添加新课程</a></b> 25 </div> 26 <div id="menu-m" style="background-color:#ccffff;height:40px;width:200px;text-align:center;"> 27 <br><b><a href="delete.jsp">删除课程信息</a></b> 28 </div> 29 <div id="menu-m" style="background-color:#ccffff;height:40px;width:200px;text-align:center;"> 30 <br> 31 <b><a href="search.jsp">查询课程信息</a></b> 32 </div> 33 <div id="menu-m" style="background-color:#ccffff;height:40px;width:200px;text-align:center;"> 34 <br> 35 <b><a href="modification.jsp">修改课程信息</a></b> 36 </div> 37 38 </body> 39 </html>
2.添加新课程(jsp+servlet)
add.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body style="text-align: center;"> 10 11 <div id="login"> 12 <div id="form"> 13 <fieldset> 14 15 <legend>添加新课程</legend> 16 <form action="Add" name="add" method="get"> 17 课程名称:<input type="text" name="addclass"><br> 18 上课老师:<input type="text" name="addteacher"><br> 19 上课地点:  <input type="text" name="addplace"><br> 20 <input type="submit" value="添加"> 21 <input type="reset" value="清空"> 22 <br> 23 </form> 24 25 </fieldset> 26 </div> 27 </div> 28 29 </body> 30 </html>
对应的servlet
Add.java
1 package MySQL; 2 3 import java.io.IOException; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 import java.sql.Statement; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.annotation.WebServlet; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 17 /** 18 * Servlet implementation class Add 19 */ 20 @WebServlet("/Add") 21 public class Add extends HttpServlet { 22 private static final long serialVersionUID = 1L; 23 24 // JDBC 驱动名及数据库 URL 25 static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; 26 static final String DB_URL = "jdbc:mysql://localhost:3306/experiment?useSSL=false&serverTimezone=UTC"; 27 28 // 数据库的用户名与密码,需要根据自己的设置 29 static final String USER = "root"; 30 static final String PASS = "HEIYANG"; 31 static boolean flag=true; 32 33 /** 34 * @see HttpServlet#HttpServlet() 35 */ 36 public Add() { 37 super(); 38 // TODO Auto-generated constructor stub 39 } 40 41 /** 42 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 43 */ 44 @SuppressWarnings("resource") 45 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 46 // TODO Auto-generated method stub 47 48 response.setContentType("text/html;charset=UTF-8"); 49 response.getWriter().append("Served at: ").append(request.getContextPath()); 50 51 String addclass=request.getParameter("addclass");//获取输入 52 String addteacher=request.getParameter("addteacher"); //获取输入 53 String addplace =request.getParameter("addplace");//获取输入 54 if(addplace.startsWith("一教")||addplace.startsWith("二教")||addplace.startsWith("三教")||addplace.startsWith("基教")) { 55 //对教室的判断若不为这几个教室则无法录入 56 if(addteacher.equals("王建民")||addteacher.equals("刘立嘉")||addteacher.equals("刘丹")||addteacher.equals("王辉")||addteacher.equals("杨子光")) { 57 //对老师额判断 58 //连接数据库 59 Connection conn = null; 60 Statement stmt = null; 61 62 // 设置响应内容类型 63 response.setContentType("text/html;charset=UTF-8"); 64 65 66 try{ 67 68 // 注册 JDBC 驱动器 69 Class.forName("com.mysql.jdbc.Driver"); 70 71 // 打开一个连接 72 conn = DriverManager.getConnection(DB_URL,USER,PASS); 73 74 // 执行 SQL 查询 75 stmt = conn.createStatement(); 76 String sql; 77 sql = "SELECT name FROM classroom"; 78 ResultSet rs = stmt.executeQuery(sql); 79 // 展开结果集数据库 80 while(rs.next()){ 81 // 通过字段检索 82 83 String username = rs.getString("name"); 84 85 if(username.equals(addclass)) 86 flag=false; 87 } 88 89 // 完成后关闭 90 rs.close(); 91 stmt.close(); 92 conn.close(); 93 if(flag==true) 94 { 95 PreparedStatement stmt1 = null; 96 // 注册 JDBC 驱动器 97 Class.forName("com.mysql.jdbc.Driver"); 98 99 // 打开一个连接 100 conn = DriverManager.getConnection(DB_URL,USER,PASS); 101 102 String add= "INSERT into classroom values(?,?,?)"; 103 stmt1 = conn.prepareStatement(add); 104 ((PreparedStatement) stmt1).setString(1, addclass); 105 ((PreparedStatement) stmt1).setString(2, addteacher ); 106 ((PreparedStatement) stmt1).setString(3, addplace); 107 108 stmt1.executeUpdate(); 109 110 111 // 完成后关闭 112 stmt.close(); 113 conn.close(); 114 115 } 116 117 118 } catch(SQLException se) { 119 // 处理 JDBC 错误 120 se.printStackTrace(); 121 } catch(Exception e) { 122 // 处理 Class.forName 错误 123 e.printStackTrace(); 124 }finally{ 125 // 最后是用于关闭资源的块 126 try{ 127 if(stmt!=null) 128 stmt.close(); 129 }catch(SQLException se2){ 130 } 131 try{ 132 if(conn!=null) 133 conn.close(); 134 }catch(SQLException se){ 135 se.printStackTrace(); 136 } 137 } 138 if(flag==true) 139 { 140 response.getWriter().print("<script language='javascript'>alert('操作失败!')</script>"); 141 response.setHeader("refresh", "1;function.jsp"); 142 } 143 else 144 response.sendRedirect("add.jsp"); 145 146 }else 147 response.sendRedirect("add.jsp"); 148 } 149 else 150 response.sendRedirect("add.jsp"); 151 152 153 154 155 156 157 } 158 159 160 161 /** 162 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 163 */ 164 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 165 // TODO Auto-generated method stub 166 doGet(request, response); 167 } 168 169 }
3.修改内容(jsp+servlet)
modification.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body style="text-align: center;"> 10 11 <div id="login"> 12 <div id="form"> 13 <fieldset> 14 15 <legend>修改课程信息</legend> 16 <form action="Modification" name="add" method="get"> 17 选择修改的课程名称:<input type="text" name="addclass0">  修改后的课程名称:<input type="text" name="addclass1"><br> 18 选择修改的上课老师:<input type="text" name="addteacher0">  修改后的上课老师:<input type="text" name="addteacher1"><br> 19 选择修改的上课地点:<input type="text" name="addplace0">  修改后的上课地点:<input type="text" name="addplace1"><br> 20 <input type="submit" value="修改"> 21 <input type="reset" value="清空"> 22 <br> 23 </form> 24 25 </fieldset> 26 </div> 27 </div> 28 </body> 29 </html>
对应的servlet:
Modification.java
1 package MySQL; 2 3 import java.io.IOException; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.annotation.WebServlet; 12 import javax.servlet.http.HttpServlet; 13 import javax.servlet.http.HttpServletRequest; 14 import javax.servlet.http.HttpServletResponse; 15 16 /** 17 * Servlet implementation class Modification 18 */ 19 @WebServlet("/Modification") 20 public class Modification extends HttpServlet { 21 private static final long serialVersionUID = 1L; 22 23 24 // JDBC 驱动名及数据库 URL 25 static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; 26 static String DB_URL = "jdbc:mysql://localhost:3306/experiment?useSSL=false&serverTimezone=UTC"; 27 28 29 // 数据库的用户名与密码,需要根据自己的设置 30 static String USER = "root"; 31 static String PASS = "HEIYANG"; 32 /** 33 * @see HttpServlet#HttpServlet() 34 */ 35 public Modification() { 36 super(); 37 // TODO Auto-generated constructor stub 38 } 39 40 /** 41 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 42 */ 43 @SuppressWarnings("resource") 44 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 45 // TODO Auto-generated method stub 46 response.getWriter().append("Served at: ").append(request.getContextPath()); 47 48 Connection conn =null; 49 PreparedStatement stmt = null; 50 ResultSet rs = null; 51 boolean Flag=false; 52 53 String class0=request.getParameter("addclass0");//获取输入 54 String class1=request.getParameter("addclass1");//获取输入 55 String teacher0=request.getParameter("addteacher0");//获取输入 56 String teacher1=request.getParameter("addteacher1");//获取输入 57 String place0=request.getParameter("addplace0");//获取输入 58 String place1=request.getParameter("addplace1");//获取输入 59 60 try{ 61 62 try { 63 Class.forName("com.mysql.jdbc.Driver"); 64 conn = DriverManager.getConnection(DB_URL,USER,PASS); 65 } catch (ClassNotFoundException e) { 66 // TODO Auto-generated catch block 67 e.printStackTrace(); 68 } 69 70 String sql; 71 System.out.println("数据库连接成功"); 72 if(class0!=null) 73 { 74 sql="update classroom set name='"+class1+"' where name='"+class0+"'"; 75 stmt = conn.prepareStatement(sql); 76 stmt.executeUpdate(); 77 } 78 if(teacher0!=null) 79 { 80 sql="update classroom set teacher='"+teacher1+"' where teacher='"+teacher0+"'"; 81 stmt = conn.prepareStatement(sql); 82 stmt.executeUpdate(); 83 } 84 if(place0!=null) 85 { 86 sql="update classroom set place='"+place1+"' where place='"+place0+"'"; 87 stmt = conn.prepareStatement(sql); 88 stmt.executeUpdate(); 89 90 } 91 92 System.out.println("success"); 93 Flag=true; 94 // out.flush(); 95 // out.close(); 96 }catch (SQLException e) { 97 e.printStackTrace(); 98 }finally { 99 try { 100 //注意关闭原则:从里到外 101 if (rs != null) { 102 rs.close(); 103 } 104 if (stmt != null) { 105 stmt.close(); 106 } 107 if (conn != null) { 108 conn.close(); 109 } 110 } catch (SQLException e) { 111 e.printStackTrace(); 112 } 113 } 114 if(Flag==true) 115 response.sendRedirect("function.jsp"); 116 else 117 response.sendRedirect("modification.jsp"); 118 } 119 120 /** 121 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 122 */ 123 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 124 doGet(request, response); 125 } 126 127 }
4.删除(jsp+servlet)
delete.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body style="text-align: center;"> 10 11 <div id="login"> 12 <div id="form"> 13 <fieldset> 14 <legend>删除课程信息</legend> 15 <form action="delete" name="add" method="get"> 16 要删除的课程名称:<input type="text" name="addclass"><br> 17 要删除的上课老师:<input type="text" name="addteacher"><br> 18 要删除的上课地点:  <input type="text" name="addplace"><br> 19 <input type="submit" value="删除"> 20 <input type="reset" value="清空"> 21 <br> 22 </form> 23 24 </fieldset> 25 </div> 26 </div> 27 28 </body> 29 </html>
delete.java
1 package MySQL; 2 3 import java.io.IOException; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.PreparedStatement; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 import java.sql.Statement; 10 11 import javax.servlet.ServletException; 12 import javax.servlet.annotation.WebServlet; 13 import javax.servlet.http.HttpServlet; 14 import javax.servlet.http.HttpServletRequest; 15 import javax.servlet.http.HttpServletResponse; 16 17 import com.mysql.cj.protocol.Resultset; 18 19 20 /** 21 * Servlet implementation class delete 22 */ 23 @WebServlet("/delete") 24 public class delete extends HttpServlet { 25 private static final long serialVersionUID = 1L; 26 27 // JDBC 驱动名及数据库 URL 28 static String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; 29 static String DB_URL = "jdbc:mysql://localhost:3306/experiment?useSSL=false&serverTimezone=UTC"; 30 31 // 数据库的用户名与密码,需要根据自己的设置 32 static String USER = "root"; 33 static String PASS = "HEIYANG"; 34 35 //连接数据库 36 static Connection conn = null; 37 static PreparedStatement stmt = null; 38 39 /** 40 * @see HttpServlet#HttpServlet() 41 */ 42 public delete() { 43 super(); 44 // TODO Auto-generated constructor stub 45 } 46 47 /** 48 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 49 */ 50 @SuppressWarnings("unused") 51 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 52 // TODO Auto-generated method stub 53 boolean Flag=false; 54 response.setContentType("text/html;charset=UTF-8"); 55 response.getWriter().append("Served at: ").append(request.getContextPath()); 56 57 String delclass=request.getParameter("addclass");//获取输入 58 String delteacher=request.getParameter("addteacher"); //获取输入 59 String adelplace =request.getParameter("addplace");//获取输入 60 61 String del1= "DELETE from classroom where name=?"; 62 String del2= "DELETE from classroom where teacher=?"; 63 String del3= "DELETE from classroom where place=?"; 64 65 try { 66 Class.forName("com.mysql.jdbc.Driver"); 67 Connection conn = DriverManager.getConnection(DB_URL,USER,PASS); 68 if(delclass!=null) 69 { 70 stmt = conn.prepareStatement(del1); 71 stmt.setString(1,delclass); 72 int rs = stmt.executeUpdate(); 73 Flag=true; 74 } 75 else if(delteacher!=null) 76 { 77 stmt = conn.prepareStatement(del2); 78 stmt.setString(2,delteacher); 79 int rs = stmt.executeUpdate(); 80 Flag=true; 81 } 82 else if(adelplace!=null) 83 { 84 stmt = conn.prepareStatement(del3); 85 stmt.setString(3,adelplace); 86 int rs = stmt.executeUpdate(); 87 Flag=true; 88 } 89 90 91 stmt.close(); 92 conn.close(); 93 if(Flag==true) { 94 response.getWriter().print("<script language='javascript'>alert('操作失败!')</script>"); 95 response.setHeader("refresh", "1;function.jsp"); 96 // response.sendRedirect("function.jsp"); 97 } 98 else 99 response.sendRedirect("delete.jsp"); 100 } catch (SQLException | ClassNotFoundException e) { 101 // TODO Auto-generated catch block 102 e.printStackTrace(); 103 } 104 105 106 107 108 109 110 111 112 } 113 114 /** 115 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 116 */ 117 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 118 // TODO Auto-generated method stub 119 doGet(request, response); 120 } 121 122 }
5.查找(jsp+servlet)
search.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body style="text-align: center;"> 10 11 <div id="login"> 12 <div id="form"> 13 <fieldset> 14 <legend>查询课程信息</legend> 15 <form action="display" name="add" method="get"> 16 课程名称:<input type="text" name="class"><br> 17 上课老师:<input type="text" name="teacher"><br> 18 上课地点:  <input type="text" name="place"><br> 19 <input type="submit" value="查询"> 20 <input type="reset" value="清空"> 21 <br> 22 </form> 23 </fieldset> 24 </div> 25 </div> 26 27 28 29 30 </body> 31 </html>
display.java
1 package MySQL; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.ResultSet; 8 import java.sql.SQLException; 9 import java.sql.Statement; 10 import java.util.LinkedList; 11 import java.util.List; 12 13 import javax.servlet.ServletException; 14 import javax.servlet.annotation.WebServlet; 15 import javax.servlet.http.HttpServlet; 16 import javax.servlet.http.HttpServletRequest; 17 import javax.servlet.http.HttpServletResponse; 18 19 /** 20 * Servlet implementation class display 21 */ 22 @WebServlet("/display") 23 public class display extends HttpServlet { 24 private static final long serialVersionUID = 1L; 25 26 27 /** 28 * @see HttpServlet#HttpServlet() 29 */ 30 public display() { 31 super(); 32 // TODO Auto-generated constructor stub 33 } 34 35 /** 36 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 37 */ 38 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 // TODO Auto-generated method stub 40 response.setContentType("text/html;charset=utf-8"); 41 42 response.setContentType("text/html"); 43 44 response.getWriter().append("Served at: ").append(request.getContextPath()); 45 46 String addclass=request.getParameter("class");//获取输入 47 String addteacher=request.getParameter("teacher"); //获取输入 48 String addplace =request.getParameter("place");//获取输入 49 50 // 设置响应内容类型 51 response.setContentType("text/html;charset=utf-8"); 52 response.setContentType("text/html;charset=GBK"); 53 response.setContentType("text/html"); 54 55 Connection connection = null; 56 Statement statement = null; 57 ResultSet resultSet = null; 58 PrintWriter printWriter = response.getWriter(); 59 List<String> list = new LinkedList<String>(); 60 try { 61 Class.forName("com.mysql.jdbc.Driver"); 62 String url = "jdbc:mysql://localhost:3306/experiment?useSSL=false&serverTimezone=UTC"; 63 connection = DriverManager.getConnection(url, "root", "HEIYANG"); 64 statement = connection.createStatement(); 65 66 resultSet = statement.executeQuery("SELECT name,teacher,place FROM classroom"); 67 printWriter.print("<html><head><title>Servlet连接数据库</title></head>"); 68 printWriter.print("<body><table border=1 align=\"center\">"); 69 70 while (resultSet.next()) { 71 if(addclass!=null) { 72 if((resultSet.getString("name")).indexOf(addclass)!=-1) { 73 printWriter.print("<tr>"); 74 printWriter.print("<td>" + resultSet.getString("name") + "</td>"+"<td>" + resultSet.getString("teacher") + "</td>"+"<td>" + resultSet.getString("place") + "</td>"); 75 printWriter.print("</tr>"); 76 } 77 } 78 else if(addteacher!=null) { 79 if((resultSet.getString("teacher")).indexOf(addteacher)!=-1) 80 { 81 printWriter.print("<tr>"); 82 printWriter.print("<td>" + resultSet.getString("name") + "</td>"+"<td>" + resultSet.getString("teacher") + "</td>"+"<td>" + resultSet.getString("place") + "</td>"); 83 printWriter.print("</tr>"); 84 String name=resultSet.getString("name"); 85 list.add(name); 86 } 87 } 88 else if(addplace!=null) { 89 90 if((resultSet.getString("place")).indexOf(addplace)!=-1) 91 { 92 printWriter.print("<tr>"); 93 printWriter.print("<td>" + resultSet.getString("name") + "</td>"+"<td>" + resultSet.getString("teacher") + "</td>"+"<td>" + resultSet.getString("place") + "</td>"); 94 printWriter.print("</tr>"); 95 } 96 } 97 } 98 }catch (ClassNotFoundException e) { 99 // TODO Auto-generated catch block 100 e.printStackTrace(); 101 } catch (SQLException e) { 102 // TODO Auto-generated catch block 103 e.printStackTrace(); 104 }finally { 105 try { 106 // resultSet.close(); 107 statement.close(); 108 connection.close(); 109 } catch (SQLException e) { 110 // TODO Auto-generated catch block 111 e.printStackTrace(); 112 } 113 } 114 115 request.setAttribute( "list ",list); 116 request.getRequestDispatcher("show.jsp").forward(request,response); 117 118 } 119 120 /** 121 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 122 */ 123 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 124 // TODO Auto-generated method stub 125 doGet(request, response); 126 } 127 128 }