编写代码
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。