Day16_学点儿JavaEE_实践_基于IDEA2023的简易JavaWeb项目、Tomcat输出乱码解决

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类

java 复制代码
/*
 * 适度编码益脑,沉迷编码伤身,合理安排时间,享受快乐生活。
 * 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;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                '}';
    }
}

2.2 数据库student表

2.3 JDBCUtil

java 复制代码
/*
 * 适度编码益脑,沉迷编码伤身,合理安排时间,享受快乐生活。
 * 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

java 复制代码
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

java 复制代码
@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    //默认访问service
    @Override
    protected 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而且指向下一个,没有返回false
                int 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

html 复制代码
<%@ 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

相关推荐
江深竹静,一苇以航几秒前
springboot3项目整合Mybatis-plus启动项目报错:Invalid bean definition with name ‘xxxMapper‘
java·spring boot
confiself16 分钟前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
Wlq041521 分钟前
J2EE平台
java·java-ee
XiaoLeisj28 分钟前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee
阑梦清川30 分钟前
JavaEE初阶---网络原理(五)---HTTP协议
网络·http·java-ee
豪宇刘42 分钟前
SpringBoot+Shiro权限管理
java·spring boot·spring
Elaine2023911 小时前
02多线程基础知识
java·多线程
gorgor在码农1 小时前
Redis 热key总结
java·redis·热key
百事老饼干1 小时前
Java[面试题]-真实面试
java·开发语言·面试
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS医院管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·开源·intellij-idea