Web開發基礎_Servlet學習_0029_專案練習(十)
阿新 • • 發佈:2018-12-10
專案名稱:中國電信運營支援系統-網路版(十)
驗證碼
登入驗證碼
案例演示:
工程案例目錄結構
DBUtil.java
package util; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import org.apache.commons.dbcp.BasicDataSource; /** * 該類用來管理連線 * 資料庫連線資訊,儲存在屬性檔案中 * 使用連線池獲取連線 * @author Cher_du * */ public class DBUtil { private static BasicDataSource ds; static{ //載入屬性檔案資料 Properties prop = new Properties(); try { prop.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties")); String driverclass = prop.getProperty("jdbc.driverclass"); String url=prop.getProperty("jdbc.url"); String user = prop.getProperty("jdbc.user"); String password = prop.getProperty("jdbc.password"); String strMaxActive =prop.getProperty("dbcp.maxActive"); String strInitSize =prop.getProperty("dbcp.initSize"); //例項化,並初始化連線池 ds = new BasicDataSource(); ds.setDriverClassName(driverclass); ds.setUrl(url); ds.setUsername(user); ds.setPassword(password); ds.setMaxActive(Integer.parseInt(strMaxActive)); ds.setInitialSize(Integer.parseInt(strInitSize)); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("讀取屬性檔案錯誤",e); } } //2、建立連線 public static Connection getConnection() throws SQLException{ return ds.getConnection(); } //3、歸還連線 public static void close(Connection conn){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("歸還連線錯誤",e); } } } //測試 public static void main(String[] args) throws SQLException { Connection conn = getConnection(); System.out.println(conn.getClass().getName()); close(conn); } }
login.jsp
<%@page pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <title>案例-NetCTOSS</title> <link type="text/css" rel="stylesheet" media="all" href="styles/global.css"/> <link type="text/css" rel="stylesheet" media="all" href="styles/global_color.css"/> </head> <body class="index"> <div class="login_box"> <form action="login.do" method="post"> <table> <tr> <td class="login_info">賬號:</td> <td colspan="2"><input name="adminCode" value="${param.adminCode }" type="text" class="width150" /></td> <td class="login_error_info"><span class="required">30長度的字母、數字和下劃線</span></td> </tr> <tr> <td class="login_info">密碼:</td> <td colspan="2"><input name="password" value="${param.password }" type="password" class="width150"/></td> <td><span class="required">30長度的字母、數字和下劃線</span></td> </tr> <tr> <td class="login_info">驗證碼:</td> <td class="width70"><input name="code" type="text" class="width70"/></td> <td><img src="createImg.do" onclick="this.src='createImg.do?x='+Math.random();" alt="驗證碼" title="點選更換"/></td> <td><span class="required"></span></td> </tr> <tr> <td></td> <td class="login_button" colspan="2"> <a href="javascript:document.forms[0].submit();"><img src="images/login_btn.png" alt="" /></a> </td> <td><span class="required">${error }</span></td> </tr> </table> </form> </div> </body> </html>
MainServlet.java
package web; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.List; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dao.AdminDao; import dao.CostDao; import entity.Admin; import entity.Cost; import util.ImageUtil; public class MainServlet extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String path = req.getServletPath(); if("/findCost.do".equals(path)){ //查詢資費 System.out.println(path); findCost(req,res); }else if("/toAddCost.do".equals(path)){ //開啟增加資費頁 toAddCost(req,res); }else if("/addCost.do".equals(path)){ //增加儲存資費 addCost(req,res); }else if("/toUpdateCost.do".equals(path)){ //開啟修改資費頁 toUpdateCost(req,res); }else if("/updateCost.do".equals(path)){ //修改資費 updateCost(req,res); }else if("/deleteCost.do".equals(path)){ //刪除資費 deleteCost(req,res); }else if("/toLogin.do".equals(path)){ //開啟登入頁 toLogin(req,res); }else if("/toIndex.do".equals(path)){ //開啟主頁 toIndex(req,res); }else if("/login.do".equals(path)){ //登入驗證 login(req,res); }else if("/logout.do".equals(path)){ //退出 logout(req,res); }else if("/createImg.do".equals(path)){ //生成驗證碼 createImg(req,res); }else{ //錯誤的路徑 throw new RuntimeException("沒有這個頁面"); } } protected void createImg(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("createImg.do"); //生成隨機的驗證碼和圖片 Object[] objs = ImageUtil.createImage(); //將驗證碼存入session HttpSession session = req.getSession(); session.setAttribute("imgCode", objs[0]); //將圖片輸出給瀏覽器 BufferedImage img = (BufferedImage)objs[1]; //格式見/tomcat/conf/web.xml res.setContentType("image/png"); //該輸出流的目標就是瀏覽器 OutputStream os= res.getOutputStream(); ImageIO.write(img, "png", os); os.close(); } protected void logout(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //登出session req.getSession().invalidate(); //重定向到登入 res.sendRedirect(req.getContextPath()+"/toLogin.do"); } protected void login(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //接收表單資料 String adminCode = req.getParameter("adminCode"); String password = req.getParameter("password"); System.out.println("login=="+adminCode+":"+password); //校驗 String code = req.getParameter("code"); HttpSession session = req.getSession(); String imgCode = (String)session.getAttribute("imgCode");System.out.println(imgCode); if(code ==null || code.equals("")|| !code.equalsIgnoreCase(imgCode)){ req.setAttribute("error", "驗證碼錯誤"); req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res); return; } AdminDao dao = new AdminDao(); Admin admin = dao.findByCode(adminCode); if(admin == null){ //賬號不存在 req.setAttribute("error", "賬號不存在"); req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res); }else if(!admin.getPassword().equals(password)){ //密碼錯誤 req.setAttribute("error", "密碼錯誤"); req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res); }else{ //校驗通過 //將賬號存入cookie Cookie c = new Cookie("adminCode",adminCode); res.addCookie(c); //登入成功後,將賬號存入session, //以記錄使用者的登入狀態,將來好做檢查 session.setAttribute("adminCode", adminCode); //當前:/netctoss/login.do //目標:/netctoss/toIndex.do res.sendRedirect("toIndex.do"); } } protected void toIndex(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("toIndex......"); req.getRequestDispatcher("WEB-INF/main/index.jsp").forward(req, res); } protected void toLogin(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //當前:/netctoss/toLogin.do //目標:/netctoss/WEB-INF/main/login.jsp System.out.println("toLogin.do"); req.getRequestDispatcher("WEB-INF/main/login.jsp").forward(req, res); } protected void deleteCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String costId = req.getParameter("costId"); CostDao dao = new CostDao(); dao.delete(new Integer(costId)); System.out.println("deleteCost......"); //3.重定向到查詢 //當前:/netctoss/deleteCost.do //目標:/netctoss/findCost.do res.sendRedirect("findCost.do"); } protected void updateCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //1.接收表單資料 String costId = req.getParameter("costId"); String name = req.getParameter("name"); String costType = req.getParameter("costType"); String descr = req.getParameter("descr"); String baseDuration = req.getParameter("baseDuration"); String baseCost = req.getParameter("baseCost"); String unitCost = req.getParameter("unitCost"); //2.儲存這些資料 Cost c = new Cost(); c.setCostId(new Integer(costId)); c.setName(name); c.setCostType(costType); c.setDescr(descr); if(baseDuration !=null && !baseDuration.equals("")){// c.setBaseDuration(new Integer(baseDuration)); } if(baseCost !=null && !baseCost.equals("")){ c.setBaseCost(new Double(baseCost)); } if(unitCost !=null && !unitCost.equals("")){ c.setUnitCost(new Double(unitCost)); } CostDao dao = new CostDao(); System.out.println(c); dao.update(c); //3.重定向到查詢 //當前:/netctoss/addCost.do //目標:/netctoss/findCost.do res.sendRedirect("findCost.do"); } protected void toUpdateCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { System.out.println("toUpdateCost......."); //接收引數 String id = req.getParameter("id"); //查詢要修改的資費 CostDao dao = new CostDao(); Cost cost = dao.findById(new Integer(id)); //轉發到修改頁 req.setAttribute("cost", cost); req.getRequestDispatcher("WEB-INF/cost/update.jsp").forward(req, res); } protected void addCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); //1.接收表單資料 String name = req.getParameter("name"); String costType = req.getParameter("costType"); String descr = req.getParameter("descr"); String baseDuration = req.getParameter("baseDuration"); String baseCost = req.getParameter("baseCost"); String unitCost = req.getParameter("unitCost"); //2.儲存這些資料 Cost c = new Cost(); c.setName(name); c.setCostType(costType); c.setDescr(descr); if(baseDuration !=null && !baseDuration.equals("")){// c.setBaseDuration(new Integer(baseDuration)); } if(baseCost !=null && !baseCost.equals("")){ c.setBaseCost(new Double(baseCost)); } if(unitCost !=null && !unitCost.equals("")){ c.setUnitCost(new Double(unitCost)); } CostDao dao = new CostDao(); dao.save(c); //3.重定向到查詢 //當前:/netctoss/addCost.do //目標:/netctoss/findCost.do res.sendRedirect("findCost.do"); } protected void toAddCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //當前:/netctoss/toAddCost.do //目標:/netctoss/WEB-INF/cost/add.jsp req.getRequestDispatcher("WEB-INF/cost/add.jsp").forward(req, res); } protected void findCost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //v1 // //查詢資費 // CostDao dao = new CostDao(); // List<Cost> list = dao.findAll(); // //轉發到查詢頁面 // req.setAttribute("costs", list); // //當前:/netctoss/findCost.dao // //目標:/netctoss/WEB-INF/cost/find.jsp // System.out.println("into--findCost"); // req.getRequestDispatcher("WEB-INF/cost/find.jsp").forward(req, res); //v2 分頁 //獲取請求引數 String page = req.getParameter("page"); if(page == null || page.equals("")){ page = "1"; } System.out.println(page); //獲取常量 String size = this.getServletContext().getInitParameter("size"); //查詢資費 CostDao dao = new CostDao(); List<Cost> list= dao.findByPage(new Integer(page), new Integer(size)); //查詢總行數,計算出總頁數 int rows = dao.findRows(); int total =rows/(new Integer(size)); if(rows%new Integer(size) != 0){ total++; } //轉發到查詢頁面 req.setAttribute("costs", list); req.setAttribute("total", total); req.setAttribute("page", page); //當前:/netctoss/findCost.do //目標:/netctoss/WEB-INF/cost/find.jsp req.getRequestDispatcher("WEB-INF/cost/find.jsp").forward(req, res); } }
將netctoss工程部署到Tomcat上,執行Tomcat啟動案例工程,
點選驗證碼圖片 更換驗證碼
若錄入驗證碼錯誤則 提示驗證碼錯誤
驗證碼正確 且賬號與密碼正確 才能登入到主頁