[笔记]【IDEA2020.2 Ultra】JSP+Servelt+JDBC+Tomcat Helloworld+增删改查(二)

简介: [笔记]【IDEA2020.2 Ultra】JSP+Servelt+JDBC+Tomcat Helloworld+增删改查(二)

编写代码

HelloJspServlet.java

public class HelloJspServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        request.setAttribute("msg","helloword");
        request.getRequestDispatcher("/index.jsp").forward(request,response);
    }
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
    this.doPost(request,response);
    }
}

注意:这里是doGet会默认调到doPost 都会走到doPost里面,所以不管是get请求还是post请求都会走到doPost

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>TestJsp</title>
  </head>
  <body>
  ${msg}
  </body>
</html>

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">
    <servlet>
        <servlet-name>HelloJspServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.HelloJspServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloJspServlet</servlet-name>
        <url-pattern>/hellojsp</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <!--        <welcome-file>login.jsp</welcome-file>-->
        <welcome-file>hellojsp</welcome-file>
    </welcome-file-list>
</web-app>

注意:也有注解方式映射方法,在servlet上加上注解 @WebServlet(name = “Servlet”,urlPatterns = “/Servlet”)

<welcome-file-list>
        <welcome-file>hellojsp</welcome-file>
    </welcome-file-list>

这一步操作有点复杂,就是项目首页路径http://localhost:8080/testJsp/

默认请求到http://localhost:8080/testJsp/hellojsp

会自动调用HelloJspServlet.java

再来简单运行一下

运行成功 这是hellojspservlet传过来的helloworld

集成JDBC

准备lib库

web/WEB-INF/libs 放入以下jar包:

(私聊,博主提供)

添加依赖

选择web/WEB-INF/libs目录

(jsp-api.jar和servlet-api.jar是tomcat/lib里面有的)

最后点击ok

增删改查

数据库导入

web/WEB-INF/sql目录 有test_jsp.sql文件

使用Navicat Premuim创建mysql 创建test_jsp数据库 然后导入sql文件

JDBC配置

com.test.shiver.util包

创建JDBCUtil.class

配置好driverClass/url/username/password

public class JDBCUtils {
  private static final String driverClass = "com.mysql.jdbc.Driver";
  private static final String url = "jdbc:mysql://localhost:3306/test_jsp";
  private static final String username = "root";
  private static final String password = "123456";
  /**
   * 注册驱动的方法
   * @throws ClassNotFoundException
   */
  public static void loadDriver() throws ClassNotFoundException{
    Class.forName(driverClass);
  }
  /**
   * 获得连接的方法:
   * @throws SQLException
   */
  public static Connection getConnection() throws Exception{
    loadDriver();
    Connection conn = DriverManager.getConnection(url, username, password);
    return conn;
  }
  /**
   * 资源释放
   */
  public static void release(Statement stmt,Connection conn){
    if(stmt != null){
      try {
        stmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      stmt = null;
    }
    if(conn != null){
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      conn = null;
    }
  }
  public static void release(ResultSet rs,Statement stmt,Connection conn){
    if(rs!= null){
      try {
        rs.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      rs = null;
    }
    if(stmt != null){
      try {
        stmt.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      stmt = null;
    }
    if(conn != null){
      try {
        conn.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
      conn = null;
    }
  }
}

创建实体 User

com.test.shiver.entity包 添加User

package com.test.shiver.entity;
public class User {
    public int id ;
    public String username;
    public String password;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

创建数据层 UserDao

com.test.shiver.dao包 添加UserDao

里面包括了对User的增删查改

public class UserDao
{
    public UserDao(){
    }
    public List<User> selectAll(){
            Connection conn = null;
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            List<User> userList = null;
                   try {
                    // 获得连接:
                    conn = JDBCUtils.getConnection();
                    // 编写SQL:
                    String sql = "select id,username,password from t_user;";
                    // 预编译SQL:
                    pstmt = conn.prepareStatement(sql);
                    // 设置参数
                    // 执行SQL:
                    rs = pstmt.executeQuery();
                    userList = new ArrayList<User>();
                    while (rs.next()) {
                        User user = new User();
                        user.id = rs.getInt("id");
                        user.username = rs.getString("username");
                        user.password = rs.getString("password");
                        userList.add(user);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    JDBCUtils.release(rs, pstmt, conn);
                }
                return userList;
    }
    public User find(int id){
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<User> userList = null;
        try {
            // 获得连接:
            conn = JDBCUtils.getConnection();
            // 编写SQL:
            String sql = "select id,username,password from t_user where id = ?";
            // 预编译SQL:
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            pstmt.setInt(1,id);
            // 执行SQL:
            rs = pstmt.executeQuery();
            userList = new ArrayList<User>();
            while (rs.next()) {
                User user = new User();
                user.id = rs.getInt("id");
                user.username = rs.getString("username");
                user.password = rs.getString("password");
                userList.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(rs, pstmt, conn);
        }
        return userList.get(0);
    }
    public int insert(User user){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = -1;
        List<User> userList = null;
        try {
            // 获得连接:
            conn = JDBCUtils.getConnection();
            // 编写SQL:
            String sql = "insert into t_user (username, password) VALUES (?,?);";
            // 预编译SQL:
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            // 执行SQL:
            result = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(null, pstmt, conn);
        }
        return result;
    }
    public int update(User user){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = -1;
        try {
            // 获得连接:
            conn = JDBCUtils.getConnection();
            // 编写SQL:
            String sql = "update t_user set username=?, password=? where id=?";
            System.out.println("sql:"+sql);
            // 预编译SQL:
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            System.out.println("pwd:"+user.getPassword());
            pstmt.setInt(3, user.getId());
            // 执行SQL:
            result = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(null, pstmt, conn);
        }
        return result;
    }
    public int delete(int id){
        Connection conn = null;
        PreparedStatement pstmt = null;
        int result = -1;
        List<User> userList = null;
        try {
            // 获得连接:
            conn = JDBCUtils.getConnection();
            // 编写SQL:
            String sql = "delete from t_user where id = ?;";
            // 预编译SQL:
            pstmt = conn.prepareStatement(sql);
            // 设置参数
            pstmt.setInt(1, id);
            // 执行SQL:
            result = pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.release(null, pstmt, conn);
        }
        return result;
    }
    public static void main(String[] args) {
        UserDao userDao = new UserDao();
        List<User> userList =   userDao.selectAll();
        if(userList == null || userList.size() == 0){
            return;
        }
        for (User user:userList) {
            System.out.println(user.username);
            System.out.println(user.password);
        }
       // userDao.delete(1);
    }
}

创建业务逻辑层 UserService

com.test.shiver.service包 添加UserService 接口Interface

com.test.shiver.service,impl包 添加UserServiceImpl 实现类

业务逻辑层 就是具体的业务逻辑,比如登录

public interface UserService {
    public List<User> GetUserList();
    public int removeUserById(int id);
    public User getUserById(int id);
    public int addUser(User user);
    public int updateUser(User user);
}
public class UserServiceImpl implements UserService {
    private UserDao userDao = new UserDao();
    @Override
    public List<User> GetUserList() {
        return userDao.selectAll();
    }
    @Override
    public int removeUserById(int id) {
        return userDao.delete(id);
    }
    @Override
    public User getUserById(int id) {
        return userDao.find(id);
    }
    @Override
    public int addUser(User user) {
        return userDao.insert(user);
    }
    @Override
    public int updateUser(User user) {
        return userDao.update(user);
    }
    public static void main(String[] args) {
        UserDao userDao = new UserDao();
        List<User> userList = userDao.selectAll();
        for (int i = 0; i < userList.size(); i++) {
            System.out.println("userName:"+userList.get(i).username);
        }
    }
}

创建控制器层Controller

由于使用servlet 一个接口需要一个Servlet

有对User的增加、删除、详细信息和列表等

以UserListServlet为例子

public class UserListServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<User> userList = userService.GetUserList();
        if(userList == null || userList.size() == 0){
            System.out.println("size 0 ");
            return;
        }
        request.setAttribute("userList",userList);
        request.setAttribute("userCount",userList.size());
        request.setAttribute("msg",request.getParameter("msg"));
        request.getRequestDispatcher("/userList.jsp").forward(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request,response);
    }
}

注意:

userList.jsp就是我们后面的视图层,专门显示数据。

同时别忘了在web.xml里 注册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">
    <servlet>
        <servlet-name>HelloJspServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.HelloJspServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>UserListServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.UserListServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>UserDeleteServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.UserDeleteServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>UserDetailServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.UserDetailServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>UserAddServlet</servlet-name>
        <servlet-class>com.test.shiver.controller.UserAddServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloJspServlet</servlet-name>
        <url-pattern>/hellojsp</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserDeleteServlet</servlet-name>
        <url-pattern>/userDelete</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserAddServlet</servlet-name>
        <url-pattern>/userAdd</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserDetailServlet</servlet-name>
        <url-pattern>/userDetail</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>UserListServlet</servlet-name>
        <url-pattern>/userList</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
<!--        <welcome-file>login.jsp</welcome-file>-->
        <welcome-file>hellojsp</welcome-file>
    </welcome-file-list>
</web-app>

创建视图层 jsp

userList.jsp

<%--
  Created by IntelliJ IDEA.
  User: zsw
  Date: 2021/11/9
  Time: 0:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
  <head>
    <title>用户列表</title>
  </head>
  <body>
  <table border="1" width="50%" align="center" style="text-align: center;">
    <tr>
      <td colspan="4">用户信息表</td>
    </tr>
    <tr>
      <td colspan="2"><a href="${pageContext.request.contextPath}/userAdd.jsp">添加用户</a></td>
    </tr>
    <tr>
      <td>用户id</td>
      <td>用户名</td>
      <td>密码</td>
      <td>操作</td>
    </tr>
    <c:forEach items="${userList}" var="userItem" varStatus="id">
      <tr>
        <td>${userItem.id}</td>
        <td>${userItem.username}</td>
        <td>${userItem.password}</td>
        <td>
          <a href="${pageContext.request.contextPath}/userDetail?id=${userItem.id}">修改</a>
          <a href="${pageContext.request.contextPath}/userDelete?id=${userItem.id}">删除</a>
        </td>
      </tr>
    </c:forEach>
    <tr>
      <td>用户总数</td>
      <td colspan="3">${userCount}</td>
    </tr>
    <tr>
      <td>操作提示</td>
      <td colspan="3"><font color="red">${msg}</font></td>
    </tr>
  </table>
  </body>
</html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

这个使用了jstl库的语法,用来foreach遍历

<c:forEach items="${userList}" var="userItem" varStatus="id">
      <tr>
        <td>${userItem.id}</td>
        <td>${userItem.username}</td>
        <td>${userItem.password}</td>
        <td>
          <a href="${pageContext.request.contextPath}/userDetail?id=${userItem.id}">修改</a>
          <a href="${pageContext.request.contextPath}/userDelete?id=${userItem.id}">删除</a>
        </td>
      </tr>
    </c:forEach>

基本效果

基本就这样了。

demo可以私聊博主,博主后期有空会分享到gitee。

代码地址



相关文章
|
2月前
|
Java 应用服务中间件 开发工具
如何使用IDEA创建JSP页面
如何使用IDEA创建JSP页面
215 0
|
2月前
|
Java 应用服务中间件 Maven
idea+maven+tomcat+spring 创建一个jsp项目
这篇文章介绍了如何在IntelliJ IDEA中使用Maven和Tomcat创建一个JSP项目,包括配置Maven依赖、设置Tomcat服务器、编写JSP页面、创建控制器和配置文件,以及项目的运行结果。
238 0
idea+maven+tomcat+spring 创建一个jsp项目
|
4月前
|
前端开发 JavaScript Java
idea中如何不重启tomcat 即可看到修改内容变化
这篇文章介绍了在IntelliJ IDEA中实现对Java Web应用的热部署(Hot Swap)的多种方法,包括启用自动构建、使用Exploded Artifact、安装JRebel插件、更改静态资源、使用Spring Boot的devtools以及IDEA的HotSwap功能,以便在不重启Tomcat服务器的情况下看到修改内容的变化。
idea中如何不重启tomcat 即可看到修改内容变化
|
4月前
|
XML JSON Java
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
本文介绍了如何使用IntelliJ IDEA和Maven搭建一个整合了Struts2、Spring4、Hibernate4的J2EE项目,并配置了项目目录结构、web.xml、welcome.jsp以及多个JSP页面,用于刷新和学习传统的SSH框架。
115 0
使用IDEA+Maven搭建整合一个Struts2+Spring4+Hibernate4项目,混合使用传统Xml与@注解,返回JSP视图或JSON数据,快来给你的SSH老项目翻新一下吧
|
4月前
|
Java 应用服务中间件 Apache
使用IDEA修改Web项目访问路径,以及解决Apache Tomcat控制台中文乱码问题
本文介绍了在IntelliJ IDEA中修改Web项目访问路径的步骤,包括修改项目、模块、Artifacts的配置,编辑Tomcat服务器设置,以及解决Apache Tomcat控制台中文乱码问题的方法。
263 0
使用IDEA修改Web项目访问路径,以及解决Apache Tomcat控制台中文乱码问题
|
5月前
|
应用服务中间件
入职必会-开发环境搭建23-IDEA配置Tomcat
IDEA配置Tomcat分为两部分: 1. IDEA集成本地Tomcat 2. IDEA中使用Tomcat部署Web项目 在配置IntelliJ IDEA中的Tomcat时,首先需要打开IDEA,选择菜单中的Run -> Edit Configurations,在左侧菜单中找到+并点击,然后选择Tomcat Server下的Local(注意不要选择错了,下方还有个TomEE Server,不是选这个)。接下来,输入一个自定义的名字作为Tomcat的配置名称,点击Configure...配置Tomcat的安装路径。这样IDEA就配置好了Tomcat。
|
4月前
|
应用服务中间件
2022年最新最详细在IDEA中配置Tomcat(含有详细图解过程)、建立使用IEDA建立一个Web项目的案例
这篇文章提供了在IntelliJ IDEA中配置Tomcat服务器的详细步骤,包括添加Tomcat Server、选择安装路径、添加项目Artifact,以及创建和展示Web项目的流程。
|
6月前
|
存储 设计模式 搜索推荐
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(下)
早期javeweb技术 JSP JDBC JSTJ Servlet BooStrap(下)
40 1
|
6月前
|
应用服务中间件
|
2月前
|
Java 关系型数据库 MySQL
mysql5.7 jdbc驱动
遵循上述步骤,即可在Java项目中高效地集成MySQL 5.7 JDBC驱动,实现数据库的访问与管理。
421 1
下一篇
DataWorks