Java基础入门day57

news/2024/12/23 1:46:49/

day57

JSP、Servlet,Java bean和JDBC整合项目

index.jsp页面

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head><title>JSP - Hello World</title>
</head>
<body>
<h1><%= "student page!" %>
</h1>
<br/>
<a href="Stu">all student</a>
<a href="stu.jsp">save student</a>
</body>
</html>

用户点击all student超链接会请求Stu这个url所对应Servlet叫做StudentServlet

StudentServlet.java

package com.saas.servlet;
​
import com.saas.service.IStudentService;
import com.saas.service.impl.StudentServiceImpl;
import com.saas.entity.Student;
​
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.util.List;
​
@WebServlet(urlPatterns = "/Stu")
public class StudentServlet 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 {System.out.println("Student Servlet");
​List<Student> students =iss.getAllStudents();
​
//        resp.getWriter().write(students.toString());
​req.setAttribute("students",students);
​req.getRequestDispatcher("stus.jsp").forward(req,resp);}
}

该servlet结束StudentService以及StudentDao完成数据的查询,得到Student的List数据,并将该list存放在key值为students所对应的request范围内

最后跳转到stus.jsp页面

stus.jsp

<%@ page import="com.saas.entity.Student" %>
<%@ page import="java.util.List" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2024/5/23
Time: 9:24
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>students</title>
</head>
<body>
<h1>all students</h1>
​
<table border="1" width="80%" align="center"><tr><td>sid</td><td>name</td><td>sex</td><td>age</td><td>score</td><td>cid</td><td>operation</td></tr><%List<Student> students = (List<Student>) request.getAttribute("students");for (Student student : students) {%><tr><td><%=student.getSid()%></td><td><%=student.getName()%></td><td><%=student.getSex()%></td><td><%=student.getAge()%></td><td><%=student.getScore()%></td><td><%=student.getCid()%></td><td><a href="Stu?action=getStudentBySid&sid=<%=student.getSid()%>">update</a></td></tr><%}%>
</table>
</body>
</html>

在该JSP页面中通过JSP的内置对象request获取到key值为students的value所对应的Student的list数据

在该页面中使用循环对于Student类所对应的list students进行遍历

先画表格的头部

再去循环list

list中嵌套html标签,通过表格里面的tr循环所有的数据到表格中

最终将Student的所有对象的list在浏览器页面中以表格的方式呈现给用户

升级StudentServlet.java

package com.saas.servlet;
​
import com.saas.service.IStudentService;
import com.saas.service.impl.StudentServiceImpl;
import com.saas.entity.Student;
​
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.util.List;
​
@WebServlet(urlPatterns = "/Stu")
public class StudentServlet extends BaseServlet {
​private IStudentService iss = new StudentServiceImpl();
​
​protected void getAllStudents(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("Student Servlet");
​List<Student> students =iss.getAllStudents();
​
//        resp.getWriter().write(students.toString());
​req.setAttribute("students",students);
​req.getRequestDispatcher("stus.jsp").forward(req,resp);}
​
​protected void getStudentBySid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doGet(req, resp);String ssid = req.getParameter("sid");
​int sid = ssid == null ? 0 : Integer.parseInt(ssid);
​Student student = iss.getStudentBySid(sid);
​
//        resp.getWriter().write(student.toString());
​req.setAttribute("student", student);
​req.getRequestDispatcher("stu.jsp").forward(req, resp);}
​protected void saveStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String name = req.getParameter("name");String sex = req.getParameter("sex");String sage = req.getParameter("age");int age = sage == null ? 0 : Integer.parseInt(sage);String sscore = req.getParameter("score");double score = sscore == null ? 0 : Double.parseDouble(sscore);String scid = req.getParameter("cid");int cid = scid == null ? 0 : Integer.parseInt(scid);String ssid = req.getParameter("sid");int sid = ssid == null ? 0 : Integer.parseInt(ssid);
​Student s = new Student();s.setSid(sid);s.setName(name);s.setSex(sex);s.setAge(age);s.setScore(score);s.setCid(cid);boolean flag = iss.updateStudent(s);
​if(flag){resp.sendRedirect("Stu?action=getAllStudents");}}
}

这个Servlet里面完成了三个功能,查询所有学生,查询单个学生和修改学生

这个类继承了我们之前反射完成的BaseServlet,可以保证整个项目中,只需要一个方法完成对于不同操作的分支处理

BaseServlet.java

package com.saas.servlet;
​
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
​
public class BaseServlet extends HttpServlet {
​@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
​
//        req.setCharacterEncoding("UTF-8");
//        resp.setCharacterEncoding("UTF-8");
//        resp.setContentType("text/html;charset=UTF-8");
​
​Class<? extends BaseServlet> clazz = getClass();
​String action = req.getParameter("action");
​try {Method method = clazz.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
​method.setAccessible(true);
​method.invoke(this, req, resp);} catch (NoSuchMethodException e) {throw new RuntimeException(e);} catch (IllegalAccessException e) {throw new RuntimeException(e);} catch (InvocationTargetException e) {throw new RuntimeException(e);}}
}

这个Servlet中,让所有的Servlet都继承自该类,该类的service方法中动态获取传递过来的action用来交给各自Servlet中的业务方法

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 s);
}

这个业务类中只是实现了查询所有,根据id查询单个对象以及修改功能,我们可以根据自己的需要进行方法的增减

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 studentDao = new StudentDaoImpl();
​@Overridepublic List<Student> getAllStudents() {return studentDao.getAllStudents();}
​@Overridepublic Student getStudentBySid(int sid) {return studentDao.getStudentBySid(sid);}
​@Overridepublic boolean updateStudent(Student s) {return studentDao.updateStudent(s) > 0;}
}

service接口的实现类,通过调用dao来完成自己的业务方法

IStudentDao.java

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 s);
}

dao接口中用来完成dao层的查询所有,查询单个对象,以及修改功能,我们也可以后期做增减

StudentDaoImpl.java

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 s) {try {return qr.update("update student set name = ?, age =? , sex = ?, score = ?, cid = ? where sid = ?",s.getName(), s.getAge(), s.getSex(), s.getScore(), s.getCid(), s.getSid());} catch (SQLException e) {throw new RuntimeException(e);}}
}

dao层的实现类,借助apache的dbutil工具jar包的api query runner完成dao的具体功能

Student.java

package com.saas.entity;public class Student {private int  sid;private String  name;private String  sex;private double  score;private int  cid;private int  age;@Overridepublic String toString() {return "Student{" +"sid=" + sid +", name='" + name + '\'' +", sex='" + sex + '\'' +", score=" + score +", cid=" + cid +", age=" + age +'}';}public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public double getScore() {return score;}public void setScore(double score) {this.score = score;}public int getCid() {return cid;}public void setCid(int cid) {this.cid = cid;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}
}

学生的实体类

MySQL

mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| sid   | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| sex   | char(6)     | YES  |     | NULL    |       |
| score | double      | YES  |     | NULL    |       |
| cid   | int(11)     | YES  |     | NULL    |       |
| age   | int(11)     | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
6 rows in set (0.00 sec)

数据库中student的表结构

DruidUtil.java

package com.saas.util;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;public class DruidUtil {private static Env env = Env.getInstance();public static DataSource getDataSource(){try {DruidDataSource dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(env);dataSource.setUrl(env.getProperty("url"));dataSource.setUsername(env.getProperty("user"));dataSource.setPassword(env.getProperty("pass"));dataSource.setDriverClassName(env.getProperty("driver"));return dataSource;} catch (Exception e) {throw new RuntimeException(e);}}
}

连接池工具类

Env.java

package com.saas.util;import java.io.IOException;
import java.util.Properties;public class Env extends Properties {private static final long serialVersionUID = 1L;private static Env env = new Env();private Env() {super();try {load(getClass().getResourceAsStream("/db.properties"));} catch (IOException e) {throw new RuntimeException(e);}}public static Env getInstance() {return env;}public static String get(String key) {return env.getProperty(key);}
}

单例模式动态加载db.properties文件是为了更好地实现跨平台操作

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/saas?characterEncoding=utf-8
user=root
pass=Abc@1234

CharacterFilter.java

package com.saas.filter;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;//@WebServlet("/*")
public class CharacterFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");chain.doFilter(request, response);}}

关于中文乱码的处理交给当前的过滤器来完成

web.xml

<?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"><filter><filter-name>CharacterFilter</filter-name><filter-class>com.saas.filter.CharacterFilter</filter-class></filter><filter-mapping><filter-name>CharacterFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping>
</web-app>

三个jar包支持

commons-dbutils-1.6.jar druid-1.0.28.jar mysql-connector-java-5.1.37.jar

小结:

以上功能写了三个功能,查询所有学生对象,根据sid查询单个学生对象以及修改功能

之前我们也写过,只不过今天关于serlet中编写的html代码完全交给了jsp页面,杜绝了在Servlet的java代码中编写了大量的Java代码

只要是页面标签性的东西都交给jsp去完成

只要是逻辑控制的东西都交给servlet的逻辑控制去完成


http://www.ppmy.cn/news/1463625.html

相关文章

Spring MVC的请求流程

Spring MVC&#xff08;Model-View-Controller&#xff09;是一种基于Java的实现了MVC设计模式的轻量级Web框架。它通过一套注解&#xff0c;可以快速地搭建一个可扩展、易维护的Web应用程序。下面是Spring MVC处理请求的基本流程&#xff1a; 用户发起请求&#xff1a;用户通过…

2024电激世界脉动-中国汽车品牌全球化制胜手册

来源&#xff1a;奥美Ogilvy&#xff1a; 近期历史回顾&#xff1a; 2024中国宏观经济专题报告-数据要素市场建设 2023-2024年度报告.pdf 2024制药与生化医疗技术产业链白皮书.pdf 从可再生能源到绿氢-中国投资助力埃及能源转型.pdf 2024有机旅行中国行业指引.pdf 2024中国技术…

Go源码--sync库(1)

简介 这篇主要介绍 sync.Once、sync.WaitGroup和sync.Mutex sync.Once once 顾名思义 只执行一次 废话不说 我们看源码 英文介绍直接略过了 感兴趣的建议读一读 获益匪浅 其结构体如下 Once 是一个严格只执行一次的object type Once struct {// 建议看下源码的注解&#xf…

Web组态可视化编辑器 快速绘制组态图

演示地址&#xff1a;by组态[web组态插件] 随着工业智能制造的发展&#xff0c;工业企业对设备可视化、远程运维的需求日趋强烈&#xff0c;传统的单机版组态软件已经不能满足越来越复杂的控制需求&#xff0c;那么实现Web组态可视化界面成为了主要的技术路径。 行业痛点 对于…

postman调用Grpc

环境&#xff1a; .net6.0 一、准备 安装nuget&#xff1a; Grpc.AspNetCore Google.Protobuf Grpc.Core.Api Grpc.Tools Grpc.AspNetCore.Server.Reflection Program.cs&#xff1a; public class Program{public static void Main(string[] args){var builder WebApplicat…

OpenCV Haar小波变换

文章目录 一、简介二、实现代码三、实现效果参考资料一、简介 图像Haar小波变换是一种基于小波分析的信号处理技术,特别适用于图像处理领域。以下是关于图像Haar小波变换过程: 分解:(1)假设原始图像为f(x,y),其中(x,y)表示图像上的像素坐标。 (2)对原始图像进行Haar小…

python web自动化(Pytest实战)

1.UnitTest框架与Pytest框架对⽐ 1&#xff09; unittest框架介绍 Unittest则是Python语⾔的标准单元测试框架。 Unittest⽀持⾃动化测试&#xff0c;测试⽤例的初 始化、关闭和测试⽤例的聚合等功能&#xff0c;它有⼀个很重要的特性&#xff…

瑞吉外卖项目学习笔记(一)

项目展示&#xff1a; 一、软件开发整体介绍 1.1 软件开发流程 作为软件开发人员&#xff0c;我们的主要工作是在 编码阶段 1.2 角色分工 1.3 软件环境 二、瑞吉外面项目介绍 2.1 项目介绍 系统管理后台页面&#xff1a; 移动端页面&#xff1a; 2.2 产品原型展示 产品原型是…