0 JavaWeb项目目录
└──JavaWeb├──resources│ └──db.properties├──src│ └──com.sdust.web│ ├──servlet│ │ └──StudentServlet│ ├──pojo│ │ └──Student│ └──util│ └──JDBCUtil├──web│ ├──static│ │ └──bootstrap-3.4.1-dist│ ├──WEB-INF│ │ ├──lib│ │ │ └──mysql-connector-j-8.0.31.jar│ │ └──web.xml│ ├──index.jsp│ └──student_list.jsp└──JavaWeb.iml
bootstrap下载(美化包)
mysql-connector-j-8.0.31.jar
1 IDEA、Tomcat环境搭建
1.1 版本
IDEA:IntelliJ IDEA 2023.2.4
Tomcat:apache-tomcat-9.0.87
官方下载地址
用IDEA进行JavaWeb的话,不需要配置Tomcat的环境变量,下载后解压就可以用了。
1.2 IDEA2023如何将项目变成Web项目
1.2.1 Help中点击Find Action
1.2.2 搜索Add Framework Support
1.2.3 勾选Web Application
1.3 配置Tomcat Server
1.3.1 点击Edit Configurations
1.3.2 点击加号,选择Tomcat Server Local
1.4 添加依赖
浏览器既可以访问JSP也可以访问Servlet,但是绝大部分情况下浏览器不直接访问JSP,JSP主要用来展示数据,
所以绝大部分情况是先访问Servlet查找出数据来之后转发到JSP页面进行展示。
2 Student类与数据库表
2.1 Student类
/** 适度编码益脑,沉迷编码伤身,合理安排时间,享受快乐生活。* Copyright @TangXJ* Created by TangXJ* Created&Used date: 2024/4/2 上午11:31 ~ 2024/4/2 下午1:44* Modified date: 2024/4/2 下午1:44*/package com.sdust.web.pojo;public class Student {private Integer id;private String name;private Integer age;private String gender;public Student() {}public Student(Integer id, String name, Integer age, String gender) {this.id = id;this.name = name;this.age = age;this.gender = gender;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", age=" + age +", gender='" + gender + '\'' +'}';}
}
2.2 数据库student表
2.3 JDBCUtil
/** 适度编码益脑,沉迷编码伤身,合理安排时间,享受快乐生活。* Copyright @TangXJ* Created by TangXJ* Created&Used date: 2024/3/27 下午4:00 ~ 2024/4/2 下午1:40* Modified date: 2024/4/2 下午1:40*/package com.sdust.web.util;import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;public class JDBCUtil {private static String driver;private static String url;private static String username;private static String password;private JDBCUtil(){}//静态代码块,在类加载的时候只会执行一次,避免重复加载驱动 还没调方法就执行了//读取配置文件static {try {//1.通过当前的类获取类加载器ClassLoader classLoader = JDBCUtil.class.getClassLoader();//反射 JVM会说 先当成固定的结论就行了//2.通过类加载器的方法获得一个输入流InputStream inputStream = classLoader.getResourceAsStream("db.properties");//不是因为叫了resource,是因为标识了Mark as//3.创建一个Properties对象 对配置文件的封装Properties properties = new Properties();properties.load(inputStream);//配置文件//4.获取配置文件中的参数的值driver = properties.getProperty("driver");url = properties.getProperty("url");username = properties.getProperty("username");password = properties.getProperty("password");} catch (IOException e) {throw new RuntimeException(e);}try {Class.forName(driver);} catch (ClassNotFoundException e) {throw new RuntimeException(e);}}public static Connection getConnection() throws SQLException {Connection connection = DriverManager.getConnection(url, username, password);return connection;/*Connection connection = null;try {connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/study?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8", "root", "xiangjie");} catch (SQLException e) {throw new RuntimeException(e);}return connection;*/}public static void close(Connection connection, Statement statement, ResultSet resultSet) {if (resultSet != null) {try {resultSet.close();} catch (SQLException e) {throw new RuntimeException(e);}}if (statement != null) {try {statement.close();} catch (SQLException e) {throw new RuntimeException(e);}}if (connection != null) {try {connection.close();} catch (SQLException e) {throw new RuntimeException(e);}}}
}
2.4 resources/db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxxx?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8
username=root
password=xxxxx
3 StudentServlet
@WebServlet("/student")
public class StudentServlet extends HttpServlet {//默认访问service@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("StudentServlet.service");Connection connection = null;PreparedStatement preparedStatement = null;ResultSet resultSet = null;List<Student> list = new ArrayList<>();try {connection = JDBCUtil.getConnection();String sql = "SELECT id,name,age,gender FROM student";//预编译preparedStatement = connection.prepareStatement(sql);resultSet = preparedStatement.executeQuery();while (resultSet.next()) {//判断下一个有没有,如果返回true而且指向下一个,没有返回falseint id = resultSet.getInt("id");String name = resultSet.getString("name");int age = resultSet.getInt("age");String gender = resultSet.getString("gender");Student student = new Student(id, name, age, gender);list.add(student);}for (Student student : list) {System.out.println(student);}} catch (SQLException throwables) {throwables.printStackTrace();} finally {JDBCUtil.close(connection, preparedStatement, resultSet);}//把list数据放到req里面req.setAttribute("list", list);//转发到student_list.jsp页面进行展示req.getRequestDispatcher("student_list.jsp").forward(req, resp);}
}
4 student_list.jsp
<%@ page import="com.situ.web.pojo.Student" %>
<%@ page import="java.util.List" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>Title</title><link rel="stylesheet" href="static/bootstrap-3.4.1-dist/css/bootstrap.css">
</head>
<body><%//JSP页面中可以嵌套Java代码//JSP脚本:在这里可以写任意的Java代码//request、response:JSP页面的内置对象List<Student> list = (List<Student>) request.getAttribute("list");%><table class="table table-striped table-bordered table-hover table-condensed"><tr><td>ID</td><td>名字</td><td>年龄</td><td>性别</td><td>编辑</td><td>删除</td></tr><%for (Student student : list) {%><tr><td><%=student.getId()%></td><td><%=student.getName()%></td><td><%=student.getAge()%></td><td><%=student.getGender()%></td><td>编辑</td><td>删除</td></tr><%}%></table>
</body>
</html>
5 结果
6 tomcat中文乱码问题
6.1 方法一
添加一行代码-Dfile.encoding=UTF-8
添加同样的一行代码-Dfile.encoding=UTF-8
6.2 方法二
如果上面方法不管用,请先删掉加了的代码,再尝试方法二
按照路径找到logging.properties
文件
有notepad++就用notepad++打开,没有记事本打开就行
把所有的UTF-8
编码改成GBK
,可以把原来的注释掉,方便出现其他情况时改回。
7 代码
Day16_JSP、Servlet