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的逻辑控制去完成