之前挖的坑,遲早要往裏掉。基礎太薄弱,要惡補。在此程序前,我還對Servlet沒有一個清晰的概念;一週時間寫好此程序以後,對Servlet的理解清晰許多。javascript
這週一直在惡補Spring,今天正好完成了Spring的每日任務,因而抽空來寫一下博客,但願這篇隨筆能夠幫到各位新手們。css
此文章省略了bean,這個很簡單,有須要的能夠自行建立。html
1、 簡單介紹java
這是一個很是簡單的一個程序,功能並不完整,只實現了學生方面的登陸和選課操做,可是代碼乾淨、整潔。node
主要模塊:1. 登陸方面寫入了MD5密碼加密模塊;mysql
2. 選課方面查詢、選中、取消選中操做;jquery
3. 攔截器。web
2、總體預覽ajax
1. Web項目預覽sql
其中applicationContext.xml是Druid配置文件。雖然Druid是配好的,可是寫着寫着莫名用得JDBC。
2. lib文件夾->jar包
3. pages文件夾->jsp頁面
4. src文件夾->.java
3、 JSP代碼
1. 登陸——login.jsp
<body style="text-align: center;"> <br><br> <h3>學生登陸</h3> <form action="LoginServlet" method="post"> 學號:<input type="text" name="numText"> <br><br> 密碼:<input type="password" name="passowrdText"> <br><br> <input type="submit" value="登陸" name="submit"> </form> </body>
2. 學生選課主頁面——studentIndex.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% 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>學生選課</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="pages/css/studentIndex.css"> <script type="text/javascript" src="jQuery/jquery-3.2.1.js"></script> <script type="text/javascript"> //選擇課程 $(document).ready( function() { $("input[name='select']").click(function(){ var node = $(this); var remainNum = $(this).parent().parent().children("td").eq(1).html(); if (!(remainNum == "0")) { $.ajax({ url:"http://localhost:8080/StudentSelect/RemainAddServlet", //請求的url地址 dataType:"json", //返回格式爲json async:true, //請求是否異步,默認爲異步,這也是ajax重要特性 data:{"id":$(this).attr("id")}, //參數值 type:"POST", //請求方式 beforeSend:function(){ //請求前的處理 }, success:function(req){ //請求成功時處理 //node.parent().parent().remove(); node.parent().parent().children("td").eq(1).html(parseInt(remainNum)-parseInt(1)); alert("已選中!"); document.getElementById("stuInfoIframe").contentWindow.location.reload(true); }, complete:function(){ //請求完成的處理 //alert("請求完成!"); }, error:function(){ //請求出錯處理 alert("重複選擇!"); } }); } else { alert("此課程人數已滿!"); } }); }); </script> </head> <body> <h3>學生選課界面</h3> <form action="SearchServlet" method="post"> 查找:<input type="text" name="search" value=<%=request.getParameter("search") == null?"":request.getParameter("search")%> > <input type="submit" value="搜索" name="ok" /> </form> <br><br> <table class="courseTable"> <tr> <td>課程名稱</td> <td>剩餘量</td> <td>總數量</td> <td>任課教師</td> <td>課程地點</td> <td>課程時間</td> <td>課程時長</td> <td>操做</td> </tr> <c:forEach items="${courseList }" var="courseList"> <tr> <td>${courseList.courseName }</td> <td>${courseList.courseRemain }</td> <td>${courseList.courseTotal }</td> <td>${courseList.courseTeacher }</td> <td>${courseList.coursePlace }</td> <td>${courseList.courseTime }</td> <td>${courseList.courseTimelength }</td> <td> <input type="button" value="選中" name="select" id="${courseList.courseId }"/> </td> </tr> </c:forEach> </table> <br><br> <hr> <br><br> <frameset> <iframe style="width: 80%;" id="stuInfoIframe" src="StudentInfoServlet"></iframe> </frameset> </body> </html>
3. 學生選中的課程信息顯示頁面——studentInfo.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <% 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>學生課程</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="pages/css/studentIndex.css"> <script type="text/javascript" src="jQuery/jquery-3.2.1.js"></script> <script type="text/javascript"> //學生課程 $(document).ready( function() { $.ajax({ url:"http://localhost:8080/StudentSelect/StudentInfoServlet", //請求的url地址 //dataType:"text", //返回格式 async:true,//請求是否異步,默認爲異步,這也是ajax重要特性 data:{ }, //參數值,發送個服務端的數據 type:"GET", //請求方式 beforeSend:function(){ //請求前的處理 }, success:function(req){ //請求成功時處理 //alert("學生課程顯示成功!"); }, complete:function(){ //請求完成的處理 //alert("請求完成!"); }, error:function(){ //請求出錯處理 //alert("學生課程顯示失敗!"); } }); }); //取消課程 $(document).ready( function() { $("input[name='cancel']").click(function(){ var node = $(this); var nodeId = $(this).attr("id"); var remainNum = $("#"+nodeId, window.parent.document).parent().parent().children("td").eq(1).html(); $.ajax({ url:"http://localhost:8080/StudentSelect/CancelServlet", //請求的url地址 dataType:"json", //返回格式爲json async:true,//請求是否異步,默認爲異步,這也是ajax重要特性 data:{"id":$(this).attr("id")}, //參數值 type:"POST", //請求方式 beforeSend:function(){ //請求前的處理 }, success:function(req){ //請求成功時處理 /* var iframe = window.parent; var div =iframe.document.getElementById(nodeId); alert(div.length); */ node.parent().parent().remove(); $("#"+nodeId, window.parent.document).parent().parent().children("td").eq(1).html(parseInt(remainNum)+parseInt("1")); alert("取消成功!"); //window.location.reload(); }, complete:function(){ //請求完成的處理 //alert("請求完成!"); }, error:function(){ //請求出錯處理 alert("取消失敗!"); } }); }); }); </script> </head> <body> <table class="courseTable"> <tr> <td>課程名稱</td> <td>任課教師</td> <td>課程地點</td> <td>課程時間</td> <td>課程時長</td> <td>操做</td> </tr> <c:forEach items="${studentCourseList }" var="studentCourseList"> <tr> <td>${studentCourseList.courseName }</td> <td>${studentCourseList.courseTeacher }</td> <td>${studentCourseList.coursePlace }</td> <td>${studentCourseList.courseTime }</td> <td>${studentCourseList.courseTimelength }</td> <td> <input type="button" value="取消" name="cancel" id="${studentCourseList.courseId }" /> </td> </tr> </c:forEach> </table> </body> </html>
4、 Servlet代碼
1. 登陸功能的Servlet——LoginServlet.java
賬號見數據庫(下文有顯示)
密碼爲123
package com.studentselect.servlet; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.NoSuchAlgorithmException; import java.sql.DriverManager; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import com.studentselect.util.MD5Util; public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "zhao1110"; Connection conn = (Connection) DriverManager.getConnection(url, username, password); Statement statement = (Statement) conn.createStatement(); //根據學號查詢 //獲取學號 req.setCharacterEncoding("UTF-8"); String keyNum = req.getParameter("numText"); //String keyNum = new String(req.getParameter("numText").getBytes("iso-8859-1"), "utf-8"); if(keyNum == null) { keyNum = ""; } String sql1 = "select * from student where student_num='" + keyNum + "'"; ResultSet resultSet = statement.executeQuery(sql1); //獲取密碼 req.setCharacterEncoding("UTF-8"); String keyPassword = req.getParameter("passowrdText"); //String keyPassword = new String(req.getParameter("passowrdText").getBytes("iso-8859-1"), "utf-8"); if(keyPassword == null) { keyPassword = ""; } //密碼加密 MD5Util md5 = new MD5Util(); String newString = ""; try { newString = md5.EncoderByMd5(keyPassword); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } //比對密碼 String passwordString = ""; while (resultSet.next()) { passwordString = resultSet.getString("student_password"); } if (passwordString.equals(newString)) { //將學號存入session HttpSession session = req.getSession(); session.setAttribute("numSession", keyNum); resp.sendRedirect("/StudentSelect/FindServlet"); } else { resp.setContentType("text/html;charset=UTF-8"); resp.getWriter().write("<script language='javascript'>alert('學號或密碼錯誤!')</script>"); resp.setHeader("refresh", "0; url=/StudentSelect"); } resultSet.close(); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } } }
2. 主頁顯示信息的Servlet——FindServlet.java
package com.studentselect.servlet; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.ArrayList; 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.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import com.studentselect.bean.Course; public class FindServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } public void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { // 加載數據庫驅動,註冊到驅動管理器 Class.forName("com.mysql.jdbc.Driver"); // 數據庫鏈接字符串 String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; // 數據庫用戶名 String username = "root"; // 數據庫密碼 String password = "zhao1110"; // 建立Connection鏈接 Connection conn = (Connection) DriverManager.getConnection(url, username, password); // SQL語句 String sql = "select * from course"; // 獲取Statement Statement statement = (Statement) conn.createStatement(); ResultSet resultSet = statement.executeQuery(sql); List<Course> courseList = new ArrayList<Course>(); while (resultSet.next()) { Course course = new Course(); course.setCourseId(resultSet.getInt("course_Id")); course.setCourseName(resultSet.getString("course_Name")); course.setCourseRemain(resultSet.getInt("course_Remain")); course.setCourseTotal(resultSet.getInt("course_Total")); course.setCourseTeacher(resultSet.getString("course_Teacher")); course.setCoursePlace(resultSet.getString("course_Place")); course.setCourseTime(resultSet.getString("course_Time")); course.setCourseTimelength(resultSet.getString("course_Timelength")); courseList.add(course); } req.setAttribute("courseList", courseList); //後臺顯示數據 /*JSONArray jsonArray = JSONArray.fromObject(courseList); System.out.println(jsonArray.toString());*/ resultSet.close(); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } req.getRequestDispatcher("pages/studentIndex.jsp").forward(req, resp); } }
3. 查詢功能的Servlet——SearchServlet.java
package com.studentselect.servlet; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.ArrayList; 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.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import com.studentselect.bean.Course; public class SearchServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); String keyString = req.getParameter("search"); if(keyString == null) { keyString = ""; } try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "zhao1110"; Connection conn = (Connection) DriverManager.getConnection(url, username, password); Statement statement = (Statement) conn.createStatement(); String sql = "select * from course where course_name like '%" + keyString + "%' or course_remain like '%" + keyString + "%' " + "or course_total like '%" + keyString + "%' or course_teacher like '%" + keyString + "%'" + " or course_place like '%" + keyString + "%' or course_time like '%" + keyString + "%'" + " or course_timelength like '%" + keyString + "%'"; ResultSet resultSet = statement.executeQuery(sql); List<Course> courseList = new ArrayList<Course>(); while (resultSet.next()) { Course course = new Course(); course.setCourseId(resultSet.getInt("course_Id")); course.setCourseName(resultSet.getString("course_Name")); course.setCourseRemain(resultSet.getInt("course_Remain")); course.setCourseTotal(resultSet.getInt("course_Total")); course.setCourseTeacher(resultSet.getString("course_Teacher")); course.setCoursePlace(resultSet.getString("course_Place")); course.setCourseTime(resultSet.getString("course_Time")); course.setCourseTimelength(resultSet.getString("course_Timelength")); courseList.add(course); } req.setAttribute("courseList", courseList); //後臺顯示數據 /*JSONArray jsonArray = JSONArray.fromObject(courseList); System.out.println(jsonArray.toString());*/ resultSet.close(); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } req.getRequestDispatcher("pages/studentIndex.jsp?search='"+keyString+"'").forward(req, resp); } }
4. 選中課程時觸發的Servlet——RemainAddServlet.java
package com.studentselect.servlet; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class RemainAddServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "zhao1110"; Connection conn = (Connection) DriverManager.getConnection(url, username, password); Statement statement = (Statement) conn.createStatement(); //String keyString = new String(req.getParameter("id").getBytes("iso-8859-1"), "utf-8"); req.setCharacterEncoding("UTF-8"); String keyString = req.getParameter("id"); if(keyString == null) { keyString = ""; resp.sendRedirect("FindServlet"); return; } //添加課程 String numSession = (String) req.getSession().getAttribute("numSession"); String sql1 = "select student_selected_course from student where student_num = '" + numSession + "'"; ResultSet resultSet = statement.executeQuery(sql1); String courseString = ""; while (resultSet.next()) { courseString = resultSet.getString("student_selected_course"); } //檢查課程選擇是否重複 String[] courseStrings = courseString.split(","); for (int i=0; i<courseStrings.length; i++) { if (courseStrings[i].equals(keyString)) { return; } } courseString = courseString + keyString + ","; //課程餘量-1 String sql = "update course set course_remain=course_remain-1 where course_id = '"+ keyString + "'"; statement.executeUpdate(sql); //修改課程數據 String sql2 = "update student set student_selected_course='" + courseString + "' where student_num = '" + numSession + "'"; statement.executeUpdate(sql2); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } resp.getWriter().print("{\"data\":\"返回json數據!\"}"); } }
5. 取消選中的課程時觸發的Servlet——CancelServlet.java
package com.studentselect.servlet; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class CancelServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "zhao1110"; Connection conn = (Connection) DriverManager.getConnection(url, username, password); Statement statement = (Statement) conn.createStatement(); //String keyString = new String(req.getParameter("id").getBytes("iso-8859-1"), "utf-8"); req.setCharacterEncoding("UTF-8"); String keyString = req.getParameter("id"); if(keyString == null) { keyString = ""; resp.sendRedirect("FindServlet"); return; } String numSession = (String) req.getSession().getAttribute("numSession"); String sql1 = "select student_selected_course from student where student_num = '" + numSession + "'"; ResultSet resultSet = statement.executeQuery(sql1); //取出課程字符串 String courseString = ""; while (resultSet.next()) { courseString = resultSet.getString("student_selected_course"); } //找到課程id Integer spot = courseString.indexOf(keyString); courseString = courseString.substring(0, spot) + courseString.substring(spot+2); //更新課程數據 String sql2 = "update student set student_selected_course='" + courseString + "' where student_num = '" + numSession + "'"; statement.executeUpdate(sql2); //課程餘量+1 String sql3 = "update course set course_remain=course_remain+1 where course_id = '"+ keyString + "'"; statement.executeUpdate(sql3); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } resp.getWriter().print("{\"data\":\"返回json數據!\"}"); } }
6. 學生選中的課程信息顯示Servlet——StudentInfoServlet.java
package com.studentselect.servlet; import java.io.IOException; import java.sql.DriverManager; import java.sql.ResultSet; import java.util.ArrayList; 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.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import com.studentselect.bean.Course; import com.studentselect.bean.Student; public class StudentInfoServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { process(req, resp); } protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/studentselect?useUnicode=true&characterEncoding=utf-8"; String username = "root"; String password = "zhao1110"; Connection conn = (Connection) DriverManager.getConnection(url, username, password); Statement statement = (Statement) conn.createStatement(); String numSession = (String) req.getSession().getAttribute("numSession"); String sql1 = "select * from student where student_num = '" + numSession + "'"; ResultSet resultSet = statement.executeQuery(sql1); //判斷參數是否爲空 /*req.setCharacterEncoding("UTF-8"); String keyString = req.getParameter("id"); if(keyString == null) { keyString = ""; resp.sendRedirect("FindServlet"); return; }*/ List<Student> courseStudentList = new ArrayList<Student>(); while (resultSet.next()) { Student student = new Student(); student.setStudentSelectedCourse(resultSet.getString("student_selected_course")); courseStudentList.add(student); } String courseStudentString = courseStudentList.get(0).getStudentSelectedCourse(); String[] array = courseStudentString.split(","); List<Course> studentCourseList = new ArrayList<Course>(); for (String s:array) { String sql2 = "select * from course where course_id = '" + s + "'"; resultSet = statement.executeQuery(sql2); while (resultSet.next()) { Course course = new Course(); course.setCourseId(resultSet.getInt("course_Id")); course.setCourseName(resultSet.getString("course_Name")); course.setCourseTeacher(resultSet.getString("course_Teacher")); course.setCoursePlace(resultSet.getString("course_Place")); course.setCourseTime(resultSet.getString("course_Time")); course.setCourseTimelength(resultSet.getString("course_Timelength")); studentCourseList.add(course); } } req.setAttribute("studentCourseList", studentCourseList); //後臺顯示數據 /*JSONArray jsonArray2 = JSONArray.fromObject(studentCourseList); System.out.println(jsonArray2.toString());*/ //返回json數據 /*PrintWriter out = resp.getWriter(); out.print(jsonArray2.toString());*/ resultSet.close(); statement.close(); conn.close(); } catch (Exception e) { e.printStackTrace(); } resp.setCharacterEncoding("UTF-8"); req.getRequestDispatcher("pages/studentInfo.jsp").forward(req, resp); } }
7. MD5密碼加密——MD5Util.java
package com.studentselect.util; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import com.yangcheboshi.util.weibo.http.BASE64Encoder; public class MD5Util { /**利用MD5進行加密*/ public String EncoderByMd5(String string) throws NoSuchAlgorithmException, UnsupportedEncodingException { //肯定計算方法 MessageDigest md5 = MessageDigest.getInstance("MD5"); BASE64Encoder base64en = new BASE64Encoder(); //加密後的字符串 @SuppressWarnings("static-access") String newString = base64en.encode(md5.digest(string.getBytes("utf-8"))); return newString; } //判斷用戶密碼是否正確 public boolean checkpassword(String newpassword,String initialpassword) throws NoSuchAlgorithmException, UnsupportedEncodingException { if(EncoderByMd5(newpassword).equals(initialpassword)) return true; else return false; } }
5、 filter攔截器代碼
1. 登陸攔截——LoginFilter.java
package com.studentselect.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class LoginFilter implements Filter{ @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("------login過濾器初始化------"); } @Override public void destroy() { System.out.println("------login過濾器銷燬------"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //對request和response進行一些預處理 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); HttpServletRequest req = (HttpServletRequest)request; Object numSession = req.getSession().getAttribute("numSession"); String url = req.getRequestURI(); if (numSession != null || (url.endsWith("pages/login.jsp") || url.endsWith("LoginServlet"))) { chain.doFilter(request, response); //讓目標資源執行,放行 return; } else { req.getRequestDispatcher("/").forward(request, response); } } }
2. JSP頁面攔截——JSPFilter.java
package com.studentselect.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class JSPFilter implements Filter { @Override public void init(FilterConfig arg0) throws ServletException { System.out.println("------.jsp過濾器初始化------"); } @Override public void destroy() { System.out.println("------.jsp過濾器銷燬------"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //對request和response進行一些預處理 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); HttpServletRequest req = (HttpServletRequest)request; String url = req.getRequestURI(); if (!(url.endsWith(".jsp"))) { chain.doFilter(request, response); //讓目標資源執行,放行 return; } else { req.getRequestDispatcher("/").forward(request, response); } } }
6、 web.xml配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>StudentSelect</display-name> <welcome-file-list> <welcome-file>pages/login.jsp</welcome-file> <welcome-file>pages/default.jsp</welcome-file> </welcome-file-list> <!--配置過濾器--> <filter> <filter-name>LoginFilter</filter-name> <filter-class>com.studentselect.filter.LoginFilter</filter-class> </filter> <!--映射過濾器--> <filter-mapping> <filter-name>LoginFilter</filter-name> <!--/*表示攔截全部的請求 --> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>JSPFilter</filter-name> <filter-class>com.studentselect.filter.JSPFilter</filter-class> </filter> <filter-mapping> <filter-name>JSPFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 課程信息 --> <servlet> <!-- 聲明Servlet對象 --> <servlet-name>FindServlet</servlet-name> <!-- 上面一句指定Servlet對象的名稱 --> <servlet-class>com.studentselect.servlet.FindServlet</servlet-class> <!-- 上面一句指定Servlet對象的完整位置,包含包名和類名 --> </servlet> <servlet-mapping> <!-- 映射Servlet --> <servlet-name>FindServlet</servlet-name> <!--<servlet-name>與上面<Servlet>標籤的<servlet-name>元素相對應,不能夠隨便起名 --> <url-pattern>/FindServlet</url-pattern> <!-- 上面一句話用於映射訪問URL --> </servlet-mapping> <!-- 學生課程 --> <servlet> <servlet-name>StudentInfoServlet</servlet-name> <servlet-class>com.studentselect.servlet.StudentInfoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>StudentInfoServlet</servlet-name> <url-pattern>/StudentInfoServlet</url-pattern> </servlet-mapping> <!-- 搜索課程 --> <servlet> <servlet-name>SearchServlet</servlet-name> <servlet-class>com.studentselect.servlet.SearchServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SearchServlet</servlet-name> <url-pattern>/SearchServlet</url-pattern> </servlet-mapping> <!-- 課程餘量、添加課程 --> <servlet> <servlet-name>RemainAddServlet</servlet-name> <servlet-class>com.studentselect.servlet.RemainAddServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RemainAddServlet</servlet-name> <url-pattern>/RemainAddServlet</url-pattern> </servlet-mapping> <!-- 學生取消課程 --> <servlet> <servlet-name>CancelServlet</servlet-name> <servlet-class>com.studentselect.servlet.CancelServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CancelServlet</servlet-name> <url-pattern>/CancelServlet</url-pattern> </servlet-mapping> <!-- 學生登陸 --> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.studentselect.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> <!-- 鏈接池 啓用Web監控統計功能 start--> <filter> <filter-name>DruidWebStatFilter</filter-name> <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class> <init-param> <param-name>exclusions</param-name> <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value> </init-param> </filter> <filter-mapping> <filter-name>DruidWebStatFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置 Druid 監控信息顯示頁面 --> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> <init-param> <!-- 容許清空統計數據 --> <param-name>resetEnable</param-name> <param-value>true</param-value> </init-param> <init-param> <!-- 用戶名 --> <param-name>loginUsername</param-name> <param-value>overfly</param-value> </init-param> <init-param> <!-- 密碼 --> <param-name>loginPassword</param-name> <param-value>zhao1110</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <!-- 鏈接池 啓用Web監控統計功能 end--> </web-app>
7、 表結構
8、 程序運行圖
9、簡單說說
1. filter攔截器我是用來攔截未登陸就訪問內容和地址欄URL直接訪問Servlet,我將用戶的登陸信息存在Session中,用來判斷用戶是否已經登陸。
2. 密碼加密是用戶將密碼輸入提交後,MD5Util對密碼進行加密操做,轉換成一系列字符編碼,而後用轉換後的字符編碼與數據庫進行比對。
雖然MD5是不可逆的,可是我認爲依舊不安全,可是能在必定程度上簡單防止它人盜取數據庫獲取用戶信息這種黑客行爲。