Java基礎入門day52

day52

servlet

綜合案例

登錄功能

  • 設置歡迎頁

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><welcome-file-list><welcome-file>login.html</welcome-file></welcome-file-list>
</web-app>

項目啟動直接加載login.html頁面

  • login.html,用戶輸入自己的用戶名和密碼,提交后交給mylogin請求

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>login</title>
</head>
<body>
?
<form action="mylogin" method="post">username: <input type="text" name="username" placeholder="username"><p />password: <input type="password" name="password" placeholder="password"><p /><input type="submit" value="login"><p />
</form>
</body>
</html>
  • 由mylogin請求對應的servlet來進行處理

package com.saas.servlet;
?
import com.saas.service.IAccountService;
import com.saas.service.impl.AccountServiceImpl;
?
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 java.io.IOException;
?
@WebServlet(urlPatterns = "/mylogin")
public class MyLoginServlet extends HttpServlet {
?private IAccountService ias = new AccountServiceImpl();
?@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}
?@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html");System.out.println("this is my login servlet .");
?String username = req.getParameter("username");String password = req.getParameter("password");
?
?boolean flag = ias.login(username, password);
?if (flag) {System.out.println("login success");req.getRequestDispatcher("main.html").forward(req, resp);} else {System.out.println("login fail");req.getRequestDispatcher("login.html").forward(req, resp);}}
}
  • mylogin所對用的MyLoginServlet會調用IAccountService接口和AccountServiceImpl實現類完成成service中登錄方法的校驗

package com.saas.service;
?
public interface IAccountService {boolean login(String username, String password);
}
  • AccountServiceImpl是service的實現類,調用dao接口和dao實現類完成dao層的登錄方法校驗

package com.saas.service.impl;
?
import com.saas.dao.IAccountDao;
import com.saas.dao.impl.AccountDaoImpl;
import com.saas.service.IAccountService;
?
public class AccountServiceImpl implements IAccountService {
?private IAccountDao iAccountDao = new AccountDaoImpl();@Overridepublic boolean login(String username, String password) {return iAccountDao.login(username, password);}
}
  • dao接口

package com.saas.dao;
?
public interface IAccountDao {boolean login(String username, String password);
}
  • dao實現類,使用apache的dbutil工具jar包的queryrunner對象即可完成所有的crud功能

    • 本方法完成登錄功能

    • 借助DruidUtil工具類的getDataSource()方法得到一個DataSource對象來創建QueryRunner對象

package com.saas.dao.impl;
?
import com.saas.dao.IAccountDao;
import com.saas.entity.Account;
import com.saas.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
?
import java.sql.SQLException;
?
public class AccountDaoImpl implements IAccountDao {
?private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());@Overridepublic boolean login(String username, String password) {
?try {String sql = "select * from account where name = ? and pass = ?";Account a = qr.query(sql, new BeanHandler<Account>(Account.class), new Object[]{username, password});
?return a != null;} catch (SQLException e) {throw new RuntimeException(e);}}
}
  • dao借助工具類完成與數據庫的交互,得到一個用戶名和密碼對應的Account對象,通過Account對象是否為空判斷用戶是否存在

  • dao完成用戶賬戶信息的判斷后,返回給service,返回給servlet

  • 在servlet中通過返回值動態決定調轉到main.html頁面還是繼續回到login.html頁面,最終完成一個登錄功能

查詢所有學生

main.html頁面中有一個查詢所有學生的超鏈接

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>main</title>
</head>
<body>
<h1>this is main page</h1>
?
<a href="stus">show all students</a>
</body>
</html>
  • 該超鏈接發送一個地址為stus的請求,該請求交給一個servlet: AllStudentServlet.java

package com.saas.servlet;import com.saas.entity.Student;
import com.saas.service.IStudentService;
import com.saas.service.impl.StudentServiceImpl;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 java.io.IOException;
import java.io.PrintWriter;
import java.util.List;@WebServlet(urlPatterns = "/stus")
public class AllStudentServlet extends HttpServlet {private IStudentService iss = new StudentServiceImpl();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html");resp.setCharacterEncoding("UTF-8");req.setCharacterEncoding("UTF-8");List<Student> list = iss.getAllStudents();System.out.println(list);PrintWriter out = resp.getWriter();out.print("<table border='1' align='center' width='80%'>");out.print("<tr>");out.print("<td>編號</td>");out.print("<td>姓名</td>");out.print("<td>性別</td>");out.print("<td>年齡</td>");out.print("<td>成績</td>");out.print("<td>管理</td>");out.print("</tr>");for (Student s : list) {out.print("<tr>");out.print("<td>" + s.getSid() + "</td>");out.print("<td>" + s.getName() + "</td>");out.print("<td>" + s.getSex() + "</td>");out.print("<td>" + s.getAge() + "</td>");out.print("<td>" + s.getScore() + "</td>");out.print("<td><a href='GetStudentBySidServlet?sid=" + s.getSid() + "'>update</a> <a href='#'>delete</a> </td>");out.print("</tr>");}out.print("</table>");}
}
  • 該servlet借助IStudentService的service接口和StudentServiceImpl的service接口的實現類,完成全部學生信息的查詢

  • service接口IStudentService.java

package com.saas.service;import com.saas.entity.Student;import java.util.List;public interface IStudentService {List<Student> getAllStudents();Student getStudentBySid(int sid);boolean updateStudent(Student student);
}
  • service接口的實現類StudentServiceImpl.java

package com.saas.service.impl;import com.saas.dao.IStudentDao;
import com.saas.dao.impl.StudentDaoImpl;
import com.saas.entity.Student;
import com.saas.service.IStudentService;import java.util.List;public class StudentServiceImpl implements IStudentService {private IStudentDao isd = new StudentDaoImpl();@Overridepublic List<Student> getAllStudents() {return isd.getAllStudents();}@Overridepublic Student getStudentBySid(int sid) {return isd.getStudentBySid(sid);}@Overridepublic boolean updateStudent(Student student) {return isd.updateStudent(student) > 0;}
}

Student的service接口調用Student的dao完成與數據庫的交互,并將數據返回

package com.saas.dao;import com.saas.entity.Student;import java.util.List;public interface IStudentDao {List<Student> getAllStudents();Student getStudentBySid(int sid);int updateStudent(Student student);
}
package com.saas.dao.impl;import com.saas.dao.IStudentDao;
import com.saas.entity.Student;
import com.saas.util.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.SQLException;
import java.util.List;public class StudentDaoImpl implements IStudentDao{private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());@Overridepublic List<Student> getAllStudents() {try {return qr.query("select * from student", new BeanListHandler<Student>(Student.class));} catch (SQLException e) {throw new RuntimeException(e);}}@Overridepublic Student getStudentBySid(int sid) {try {return qr.query("select * from student where sid = ?", new BeanHandler<Student>(Student.class), sid);} catch (SQLException e) {throw new RuntimeException(e);}}@Overridepublic int updateStudent(Student student) {try {return qr.update("update student set name = ?, sex = ?, score = ?, cid = ?, age = ? where sid = ? ",student.getName(), student.getSex(), student.getScore(), student.getCid(), student.getAge(), student.getSid());} catch (SQLException e) {throw new RuntimeException(e);}}
}
  • 完成所有學生信息的查詢,返回給service,返回給servlet

  • 在servlet中將學生的list借助servlet在頁面中以表格方式呈現

查詢單個學生對象

  • 在AllStudentServlet這個servlet的表格中,每一個數據的最后放置了一個修改的超鏈接

  • <a href='GetStudentBySidServlet?sid=" + s.getSid() + "'>update</a>
  • 在這個超鏈接中,href為GetStudentBySidServlet,那么請求將交給GetStudentBySidServlet地址所對應的sevlet,該請求的最后還有一個問號傳參

  • 該請求將交由GetStudentBySidServlet.java的servlet來處理

package com.saas.servlet;import com.saas.entity.Student;
import com.saas.service.IStudentService;
import com.saas.service.impl.StudentServiceImpl;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 java.io.IOException;
import java.io.PrintWriter;@WebServlet("/GetStudentBySidServlet")
public class GetStudentBySidServlet extends HttpServlet {private IStudentService studentService = new StudentServiceImpl();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.setContentType("text/html");resp.setCharacterEncoding("UTF-8");req.setCharacterEncoding("UTF-8");System.out.println("this is update student page.");String ssid = req.getParameter("sid");int sid = ssid == null ? 0 : Integer.parseInt(ssid);Student s = studentService.getStudentBySid(sid);PrintWriter out = resp.getWriter();out.print("<h1>this is update student page.</h1>");out.print("<form action='UpdateStudentServlet' method='post'>");out.print("<input type=\"hidden\" name=\"sid\" value=\"" + s.getSid() + "\"><p />");out.print("name:<input type=\"text\" name=\"name\" value=\"" + s.getName() + "\"><p />");out.print("sex:<input type=\"text\" name=\"sex\" value=\"" + s.getSex() + "\"><p />");out.print("age:<input type=\"text\" name=\"age\" value=\"" + s.getAge() + "\"><p />");out.print("score:<input type=\"text\" name=\"score\" value=\"" + s.getScore() + "\"><p />");out.print("cid:<input type=\"text\" name=\"cid\" value=\"" + s.getCid() + "\"><p />");out.print("<input type=\"submit\" value=\"update\"><p />");out.print("</form>");}
}
  • 該servlet借助IStudentService對象的getStudentBySid方法,進行用戶編號查詢用戶的操作

  • 該servlet同樣調用service以及dao完成數據的查詢,得到sid對應的學生對象

  • 得到問號傳參傳遞過來的sid的值,將該sid對應的學生對象以表單方式呈現給用戶

修改學生對象

  • 在GetStudentBySidServlet的servlet里面,由form表單將數據庫中指定sid對應的學生對象呈現在頁面表單中

  • 用戶在該表單中修改該學生信息

  • 點擊提交按鈕,將發送一個新的請求,該請求是form表單中action所對應的UpdateStudentServlet的servlet

  • 所以該表單提交后交給UpdateStudentServlet這個sevlet

package com.saas.servlet;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 java.io.IOException;import com.saas.entity.Student;
import com.saas.service.IStudentService;
import com.saas.service.impl.StudentServiceImpl;@WebServlet(urlPatterns = "/UpdateStudentServlet")
public class UpdateStudentServlet extends HttpServlet {private IStudentService istudentService = new StudentServiceImpl();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.setCharacterEncoding("utf-8");resp.setCharacterEncoding("utf-8");resp.setContentType("text/html;charset=utf-8");int sid = Integer.parseInt(req.getParameter("sid"));String name = req.getParameter("name");String sex = req.getParameter("sex");double score = Double.parseDouble(req.getParameter("score"));int cid = Integer.parseInt(req.getParameter("cid"));int age = Integer.parseInt(req.getParameter("age"));Student student = new Student(sid, name, sex, score, cid, age);boolean flag = istudentService.updateStudent(student);if (flag) {resp.getWriter().write("<script>alert('修改成功');location.href='/day51/stus'</script>");} else {resp.getWriter().write("<script>alert('修改失敗');location.href='/day51/stus'</script>");}}
}

該servlet收集用戶輸入的所有信息,將這些所有信息封裝為一個Student對象

再將Student對象借助Student的service和dao完成一個修改功能

修改成功后給用戶一個修改成功的彈框并跳轉到stus所對應的servlet展示最新的學生列表信息

修改失敗給用戶一個提示,也跳轉到stus請求對應的serlvet

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/13807.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/13807.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/13807.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

SpringBoot 國際化

如下四步 1 建資源文件 2 在yml文件中指定資源文件名稱 3 自定義類型轉換&#xff0c;轉換locale Configuration public class DefaultLocaleResolver implements LocaleResolver {Overridepublic Locale resolveLocale(HttpServletRequest request) {String locrequest.getP…

基于語音識別的智能電子病歷(三)之 M*Modal

討論“基于語音識別的智能電子病歷”&#xff0c;就繞不開 Nuance 和 M*Modal。這2個公司長時間的占據第一和第二的位置。下面介紹一下M*Modal。 這是2019年的一個新聞“專業醫療軟件提供商3M公司為自己購買了一份圣誕禮物&#xff0c;即M*Modal IP LLC的醫療技術業務&#xf…

SQL靶場搭建

概述 簡單介紹一下SQL靶場的搭建&#xff0c;以及在搭建過程中遇到的一些問題。使用該軟件搭建靶場相對簡單&#xff0c;適合新手小白。當然&#xff0c;也可以在自己的虛擬機下進行搭建&#xff0c;相對來說就較為復雜。本章主要講解使用Phpstudy進行SQL靶場搭建。 這里我推…

前后端編程語言和運行環境的理解

我已重新檢查了我的回答,并確保信息的準確性。以下是常用的編程語言,以及它們通常用于前端或后端開發,以及相應的框架和運行環境: 前端開發 JavaScript 框架:React, Angular, Vue.js, Ember.js, Backbone.js運行環境:Web 瀏覽器HTML (HyperText Markup Language) 不是編…

嵌入式學習——3——TCP-UDP 數據交互,握手,揮手

1、更新源 cd /etc/apt/ sudo cp sources.list sources.list.save 將原鏡像備份 sudo vim sources.list 將原鏡像修改成阿里源/清華源&#xff0c;如所述 阿里源 deb http://mirrors.aliyun.com/ubuntu/ bionic main …

Flutter 中的 DrawerController 小部件:全面指南

Flutter 中的 DrawerController 小部件&#xff1a;全面指南 Flutter 是一個流行的跨平臺移動應用開發框架&#xff0c;它提供了豐富的組件和工具來幫助開發者構建高質量的應用。在Flutter中&#xff0c;DrawerController并不是一個內置的組件&#xff0c;但是它的概念可以用于…

每周題解:牛的旅行

題目描述 牛的旅行 農民John的農場里有很多牧區。有的路徑連接一些特定的牧區。一片所有連通的牧區稱為一個牧場。但是就目前而言&#xff0c;你能看到至少有兩個牧區不連通。 現在&#xff0c;John想在農場里添加一條路徑 ( 注意&#xff0c;恰好一條 )。對這條路徑有這樣的…

RA-RISK ANALYSIS

文章目錄 一、期刊簡介二、征稿信息三、期刊表現四、投稿須知五、咨詢 一、期刊簡介 Risk Analysis代表風險分析學會出版&#xff0c;在ISI期刊引文報告中的社會科學、數學方法類別中排名前10位&#xff0c;為風險分析領域的新發展提供了焦點。這本國際同行評審期刊致力于發表…

MultiHop-RAG:多跳查詢的基準檢索增強生成

【摘要】檢索增強生成&#xff08;RAG&#xff09;通過檢索相關知識來增強大語言模型&#xff08;LLM&#xff09;&#xff0c;在減輕 LLM 幻覺和提高響應質量方面顯示出巨大的潛力&#xff0c;從而促進 LLM 在實踐中的廣泛采用。然而&#xff0c;我們發現現有的 RAG 系統不足以…

DNS域名解析服務器搭建

基礎介紹 DNS 從哪里獲取 IP 地址&#xff1f; 本地緩存&#xff1a; DNS服務器會將先前查詢過的域名和對應的IP地址存儲在本地緩存中&#xff0c;以便在后續查詢中加快響應速度。如果之前已經查詢過某個域名&#xff0c;DNS服務器會直接從本地緩存中獲取對應的IP地址。遞歸查…

02. Redis 事務

文章目錄 Redis 事務執行事務放棄事務編譯性異常運行時異常 Redis 事務 Redis 單條明令是原子性的&#xff0c;但Redis事務不保證原子性。 事務的本質就是&#xff1a;一組命令一起執行&#xff01;一個事務中的所有命令都會被序列化&#xff0c;在事務執行過程中&#xff0c;會…

2024-05-19 問AI: 大語言模型的BPE方向是什么意思?

文心一言 大語言模型的上下文中&#xff0c;BPE&#xff08;Byte-Pair Encoding&#xff09;是一種常用的子詞單元&#xff08;subword unit&#xff09;編碼方法&#xff0c;尤其在處理自然語言處理任務時。這種方法的主要目的是解決自然語言中的詞匯表大小問題&#xff0c;特…

mock.js和apifox模擬接口的能力

mock.js 和 Apifox 都是前端開發中常用的工具&#xff0c;用于模擬后端接口和數據。下面是它們的主要特點和模擬接口的能力的比較&#xff1a; mock.js mock.js 是一個用于生成隨機數據的 JavaScript 庫。它允許你定義數據模板&#xff0c;并生成模擬數據。mock.js 主要用于前…

VSCode下STM32開發環境搭建

VSCode下STM32開發環境搭建 需要的軟件 make-3.81 https://udomain.dl.sourceforge.net/project/gnuwin32/make/3.81/make-3.81.exe arm-none-eabi-gcc https://developer.arm.com/open-source/gnu-toolchain/gnu-rm/downloads https://links.jianshu.com/go?tohttps%3A%2F%…

RH850F1KM-S4-100Pin_ R7F7016453AFP MCAL Gpt 配置

1、Gpt組件包含的子配置項 GptDriverConfigurationGptDemEventParameterRefsGptConfigurationOfOptApiServicesGptChannelConfigSet2、GptDriverConfiguration 2.1、GptAlreadyInitDetCheck 該參數啟用/禁用Gpt_Init API中的GPT_E_ALREADY_INITIALIZED Det檢查。 true:開啟Gpt_…

Django5+React18前后端分離開發實戰13 使用React創建前端項目

先將nodejs的版本切換到18&#xff1a; 接著&#xff0c;創建項目&#xff1a; npx create-react-app frontend接著&#xff0c;使用webstorm打開這個剛創建的項目&#xff1a; 添加一個npm run start的配置&#xff1a; 通過start啟動服務&#xff1a; 瀏覽器訪問&…

機器學習之決策樹算法

使用決策樹訓練紅酒數據集 完整代碼&#xff1a; import numpy as np import matplotlib.pyplot as plt from matplotlib.colors import ListedColormap from sklearn import tree, datasets from sklearn.model_selection import train_test_split# 準備數據&#xff0c;這里…

【云原生】Kubernetes 核心概念

什么是 Kubernetes Kubernetes&#xff0c;從官方網站上可以看到&#xff0c;它是一個工業級的容器編排平臺。Kubernetes 這個單詞是希臘語&#xff0c;它的中文翻譯是“舵手”或者“飛行員”。在一些常見的資料中也會看到“ks”這個詞&#xff0c;也就是“k8s”&#xff0c;它…

科大訊飛筆試題---刪除數字

1、 題目描述&#xff1a; 給定一個長度為 n 的數組&#xff0c;數組元素為 a1, a2, . . , an&#xff0c;每次能刪除任意 a 的任意一位&#xff0c;求將所有數字變成 0 最少需要幾步。例如 103 若刪除第 1 位則變成 3; 若刪除第 2 位則變成13; 若刪除第 3 位則變成 10。 輸入…

AWS容器之Amazon ECS

Amazon Elastic Container Service&#xff08;Amazon ECS&#xff09;是亞馬遜提供的一種完全托管的容器編排服務&#xff0c;用于在云中運行、擴展和管理Docker容器化的應用程序。可以理解為Docker在云中對應的服務就是ECS。