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.mzph.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。