使用IDEA练习一个最基础的java web项目(适合新手)

使用Servlet、JDBC、Maven和IDEA完成最基础的增删改查,整体逻辑浅显易懂,希望能帮助到各位更好的学习web基础,如果有问题欢迎留言,

完整代码免费下载地址:https://wwa.lanzous.com/ih0tRhfneba

目录

  • 主要功能
  • 整体架构
  • 1.新建mysql表
  • 2.IDEA新建maven项目
  • 3.整理pom.xml文件
  • 4.过滤器
  • 5.实体类User
  • 6.数据库工具类DBCoon
  • 7.UserDao接口和实现类
  • 8.servlet
    • 登录LoginServlet
    • 注册RegisterServlet
    • 查询所有SearchAllServlet
    • 删除DeleteServlet
    • 更新UpdateServlet
  • 9.在web.xml里注册servlet
  • 10.jsp页面
    • 登录login.jsp
    • 注册register.jsp
    • 操作成功success.jsp
    • 操作失败error.jsp
    • 显示所有用户信息showAll.jsp
  • 可能会遇到的一些坑
  • 进阶
    • 搜索功能的实现
    • 分页功能的实现
    • 搜索加分页功能
    • 验证码的实现
    • 文件上传功能
    • 购物车功能
  • 总结

主要功能

1.用户注册
2.用户登录
3.用户列表展示
4.用户信息修改
5.用户信息删除

整体架构

使用IDEA练习一个最基础的java web项目(适合新手)_第1张图片

1.新建mysql表

CREATE TABLE `user` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(255) NOT NULL,
  `pwd` varchar(255) NOT NULL,
  `sex` varchar(255) NOT NULL,
  `home` varchar(255) NOT NULL,
  `info` varchar(255) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
 
/*添加两个值用于测试*/
INSERT INTO `user` VALUES ('1', '123', '123', '男', '北京', '123');
INSERT INTO `user` VALUES ('2', '123123', '123123', '男', '北京', '123123');

2.IDEA新建maven项目

使用IDEA练习一个最基础的java web项目(适合新手)_第2张图片
这里选择设置好的maven环境使用IDEA练习一个最基础的java web项目(适合新手)_第3张图片
在src下建立项目包结构
使用IDEA练习一个最基础的java web项目(适合新手)_第4张图片

3.整理pom.xml文件

注意:
1.删除没用的内容
2.导入需要使用的依赖



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>org.examplegroupId>
  <artifactId>csdn3artifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

    <dependencies>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.20version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>4.0.0version>
        dependency>
        
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>javax.servlet.jsp-apiartifactId>
            <version>2.3.3version>
        dependency>
        
        <dependency>
            <groupId>javax.servlet.jsp.jstlgroupId>
            <artifactId>jstl-apiartifactId>
            <version>1.2version>
        dependency>
        
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>1.1.2version>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.12version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.11version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-clean-pluginartifactId>
                <version>3.0.0version>
            plugin>
        plugins>
    build>


project>

4.过滤器

作用:过滤所有页面解决乱码问题
注意:在web.xml里注册

package com.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
     
    public EncodingFilter() {
     
        System.out.println("执行过滤器");
    }

    public void init(FilterConfig filterConfig) throws ServletException {
     

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
     
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        filterChain.doFilter(request, response);
    }

    public void destroy() {
     

    }
}

5.实体类User

作用:映射数据库创建的user表
注意:这里我使用到了lombok包,需要先下载lombok插件再在pom.xml里导入lombok依赖,在方法上加上**@Data**就会生成这个类所有属性的setter和getter方法,在左侧Structure里可以看到生成的方法,也可以手动生成setter和getter方法,二者没区别使用IDEA练习一个最基础的java web项目(适合新手)_第5张图片

package com.entiy;
import lombok.Data;
@Data
public class User {
     
    private int id;
    private String name;
    private String pwd;
    private String sex;
    private String home;
    private String info;
}

6.数据库工具类DBCoon

作用:用于连接数据库,执行SQL语句和返回执行结果
注:我使用了PreparedStatement 预编译SQL方法通过遍历Object数组的方式传递SQL参数,原作者使用的是字符串拼接的方式,比较复杂且易错

package com.util;
import java.sql.*;
/*数据库工具类:
* 1.连接数据库
* 2.增删改查
* 3.执行SQL语句并返回执行结果
* 4.关流
* */
public class DBCoon {
     
	//serverTimezone=UTC设置连接时区,不设置可能会报时区错误
    static String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
    static String username = "root";
    //密码换成自己的
    static String password = "root";
    static Connection conn = null;
    static ResultSet rs = null;
    static PreparedStatement ps = null;

  /*连接数据库*/
      public static void init() {
     
        try {
     
          /*1.加载驱动获得驱动管理器*/
          Class.forName("com.mysql.cj.jdbc.Driver");
          /*2.连接数据库*/
          conn = DriverManager.getConnection(url, username, password);
          System.out.println("数据库连接成功");
        } catch (Exception e) {
     
          e.printStackTrace();
          System.out.println("数据库连接失败");
        }
    }
    /*查询数据(传递参数)*/
    public static ResultSet searchSql(String sql,Object[] args){
     
        try {
     
            ps = conn.prepareStatement(sql);
            for (int j = 0; j < args.length; j++) {
     
                ps.setObject(j+1, args[j]);
            }
            rs = ps.executeQuery();
            System.out.println("数据查询成功");
        } catch (SQLException e) {
     
            e.printStackTrace();
            System.out.println("数据查询失败");
        }
        return rs;
    }
    /*增删改查数据(传递参数)*/
    public static int addUpdDel(String sql,Object[] args){
     
        int i = 0;
        try{
     
            ps = conn.prepareStatement(sql);
            for (int j = 0; j < args.length; j++) {
     
                ps.setObject(j+1, args[j]);
            }
            i = ps.executeUpdate();
            System.out.println("增删改成功");
        } catch (SQLException e) {
     
            e.printStackTrace();
            System.out.println("增删改失败");
        }
        return i;
    }
    /*不传递参数查询所有用户信息*/
    public static ResultSet getUsers(String sql){
     
        try {
     
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            System.out.println("数据查询成功");
        } catch (SQLException e) {
     
            e.printStackTrace();
            System.out.println("数据查询失败");
        }
        return rs;
    }
    /*关流*/
    public static void close() {
     
        try {
     
            if (rs != null){
     
                rs.close();
            }
            if (ps != null) {
     
                ps.close();
            }
            if (conn != null){
     
                conn.close();
            }
        }catch (SQLException e) {
     
            System.out.println("数据流关闭异常");
        }
}

7.UserDao接口和实现类

注意:接口是为了使代码更简洁规范,注意每个方法传递的参数意义

package com.dao;
import com.entiy.User;
import java.util.List;

public interface UserDao {
     
    /*获取前台的账号密码判断能否登录成功*/
    public boolean login(String name, String pwd);
    /*获取前台的注册信息,封装成user对象*/
    public boolean register(User user);
    /*返回所有的用户信息*/
    public List<User> searchAll();
    /*根据获取到的内容更新用户信息*/
    public boolean update(int id,String name, String pwd,String sex, String home,String info) ;//更新用户信息
    /*获取前台传递的id删除用户*/
    public boolean delete(int id);
}
package com.dao;
import com.entiy.User;
import com.util.DBCoon;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
     
    /*创建一个返回值标志*/
    static boolean flag = false;
    /*提高sql作用域,每个方法里都要编写sql语句*/
    static String sql = null;
    public boolean login(String name, String pwd) {
     
        try {
     
            DBCoon.init();
            sql = "select * from user where name= ? and pwd = ?";
            /*使用预编译SQL传递参数*/
            Object[] args = {
     name,pwd};
            ResultSet rs = DBCoon.searchSql(sql, args);
            /*遍历数据库里的账号密码与从jsp传来的账号密码作对比*/
            while (rs.next()) {
     
                if (rs.getString("name").equals(name)&&rs.getString("pwd").equals(pwd)){
     
                    flag = true;
                    System.out.println("登录成功");
                }
            }
        }catch (Exception e) {
     
            System.out.println("登录失败");
            e.printStackTrace();
        } finally {
     
            DBCoon.close();
        }
        return flag;
    }

    public boolean register(User user) {
     
        try {
     
            DBCoon.init();
            sql="insert into user(name,pwd,sex,home,info)"+"values(?,?,?,?,?)";
            Object[] args = {
     user.getName(),user.getPwd(),user.getSex(),user.getHome(),user.getInfo()};
            int i = DBCoon.addUpdDel(sql,args);
            if (i>0){
     
                flag = true;
                System.out.println("注册成功");
            }
        }catch (Exception e) {
     
            e.printStackTrace();
            System.out.println("注册失败");
        }finally {
     
            DBCoon.close();
        }
        return flag;
    }

    public List<User> searchAll() {
     
        List<User> list = new ArrayList<User>();
        try {
     
            DBCoon.init();
            sql = "select * from user";
            ResultSet rs = DBCoon.getUsers(sql);
            System.out.println("获取所有用户信息成功");
            while (rs.next()) {
     
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setName(rs.getString("name"));
                user.setPwd(rs.getString("pwd"));
                user.setSex(rs.getString("sex"));
                user.setHome(rs.getString("home"));
                user.setInfo(rs.getString("info"));
                list.add(user);
            }
        }catch (Exception e){
     
            System.out.println("获取所有用户信息失败");
            e.printStackTrace();
        }finally{
     
            DBCoon.close();
        }
        return list;
    }

    public boolean update(int id, String name, String pwd, String sex, String home, String info) {
     
        try {
     
            DBCoon.init();
            sql = "update user set name=?,pwd=?,sex=?,home=?,info=? where id=?";
            Object[] args={
     name,pwd,sex,home,info,id};
            int i = DBCoon.addUpdDel(sql,args);
            if (i>0){
     
                flag=true;
                System.out.println("数据更新成功");
            }
        }catch (Exception e) {
     
            System.out.println("数据更新失败");
            e.printStackTrace();
        }finally {
     
            DBCoon.close();
        }
        return flag;
    }

    public boolean delete(int id) {
     
        try {
     
            DBCoon.init();
            sql = "delete from user where id = ?";
            Object[] args = {
     id};
            int i = DBCoon.addUpdDel(sql,args);
            if (i>0){
     
                flag=true;
                System.out.println("删除成功");
            }
        }catch (Exception e) {
     
            System.out.println("删除失败");
            e.printStackTrace();
        }finally {
     
            DBCoon.close();
        }
        return flag;
    }
}

8.servlet

注意:
1.这里用到了请求转发和重定向,二者的不同可以看下这篇文章,详细介绍了什么时候用转发和重定向https://blog.csdn.net/weixin_40001125/article/details/88663468
2.req.getParameter获取前台输入框的值即input框里的name属性的值
3.req.setAttribute向request域中添加名为msg值为object对象类型的信息,前台可以通过el表达式${msg}获取对象的值

登录LoginServlet

package com.servlet;

import com.dao.UserDao;
import com.dao.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        /*req.getParameter获取前台输入框的值即input框里的name属性的值*/
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        UserDao ud = new UserDaoImpl();
        if(ud.login(name,pwd)){
     
            /*如果要获取request存放的参数则使用请求转发,路径加不加/都行 */
            System.out.println("用户"+name+"登录成功");
            /*req.setAttribute向request域中添加名为msg对象object为string类型的信息*/
            req.setAttribute("msg","用户"+name+"登录成功");

            req.getRequestDispatcher("success.jsp").forward(req, resp);
        }else {
     
            /*如果不获取参数则使用重定向到错误页面*/
            resp.sendRedirect("error.jsp");
        }
    }
}

注册RegisterServlet

package com.servlet;

import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entiy.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        String sex = req.getParameter("sex");
        String home = req.getParameter("home");
        String info = req.getParameter("info");
        //实例化一个对象,组装属性
        User user = new User();
        user.setName(name);
        user.setPwd(pwd);
        user.setSex(sex);
        user.setHome(home);
        user.setInfo(info);
        UserDao ud = new UserDaoImpl();
        if (ud.register(user)){
     
            System.out.println("用户"+name+"注册成功");
            req.setAttribute("msg","用户"+name+"注册成功");
            req.getRequestDispatcher("success.jsp").forward(req, resp);
        }else {
     
            resp.sendRedirect("error.jsp");
        }
    }
}

查询所有SearchAllServlet

package com.servlet;

import com.dao.UserDao;
import com.dao.UserDaoImpl;
import com.entiy.User;

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.util.List;

public class SearchAllServlet extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        UserDao ud = new UserDaoImpl();
        List<User> users = ud.searchAll();
        req.setAttribute("users",users);
        System.out.println("查询全部用户成功");
        req.getRequestDispatcher("/showAll.jsp").forward(req, resp);
    }
}

删除DeleteServlet

package com.servlet;

import com.dao.UserDao;
import com.dao.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DeleteServlet extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        String id = req.getParameter("id");
        System.out.println("删除的用户id为:"+id);
        /*获取到的id是一个引用数据类型即对象,需要变成基本数据类型作为参数传输*/
        int userId = Integer.parseInt(id);
        /*调用dao层,返回值是一个整形数字*/
        UserDao ud = new UserDaoImpl();
        /*delete方法的参数为int id,所以必须把从jsp页面获取到的id转换成基本数据类型*/
        if(ud.delete(userId)){
     
            /*站内转发:请求转发到searchAll的servlet*/
            req.getRequestDispatcher("searchAll").forward(req, resp);
        }else{
     
            /*站外转发:重定向到首页*/
            resp.sendRedirect("error.jsp");
        }

    }
}

更新UpdateServlet

package com.servlet;

import com.dao.UserDao;
import com.dao.UserDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UpdateServlet extends HttpServlet {
     
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     
        String id = req.getParameter("id");
        int userId = Integer.parseInt(id);

        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        String sex = req.getParameter("sex");
        String home = req.getParameter("home");
        String info = req.getParameter("info");

        UserDao ud = new UserDaoImpl();

        if(ud.update(userId, name, pwd, sex, home, info)){
     
            req.getRequestDispatcher("searchAll").forward(req, resp);
        }else{
     
            resp.sendRedirect("error.jsp");
        }
    }
}

9.在web.xml里注册servlet

注意:设置好的名字,这是访问servlet的入口,建议复制


<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <filter>
        <filter-name>EncodingFilterfilter-name>
        <filter-class>com.filter.EncodingFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>EncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    <servlet>
        <servlet-name>loginservlet-name>
        <servlet-class>com.servlet.LoginServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>loginservlet-name>
        <url-pattern>/loginurl-pattern>
    servlet-mapping>
    <servlet>
        <servlet-name>searchAllservlet-name>
        <servlet-class>com.servlet.SearchAllServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>searchAllservlet-name>
        <url-pattern>/searchAllurl-pattern>
    servlet-mapping>
    <servlet>
        <servlet-name>deleteservlet-name>
        <servlet-class>com.servlet.DeleteServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>deleteservlet-name>
        <url-pattern>/deleteurl-pattern>
    servlet-mapping>
    <servlet>
        <servlet-name>updateservlet-name>
        <servlet-class>com.servlet.UpdateServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>updateservlet-name>
        <url-pattern>/updateurl-pattern>
    servlet-mapping>
    <servlet>
        <servlet-name>registerservlet-name>
        <servlet-class>com.servlet.RegisterServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>registerservlet-name>
        <url-pattern>/registerurl-pattern>
    servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>login.jspwelcome-file>
    welcome-file-list>

web-app>

10.jsp页面

登录login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录title>
head>
<body>

    <form action="login" method="post" style="margin: 0 auto;">
        账号:<input type="text" name="name"><br><br>
        密码: <input type="password" name="pwd"><br><br>
        
        <br>
    form>
    <a href="register.jsp">新用户注册a>
body>
html>

注册register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册title>
head>
<body>
<%--action后面跟的就是要访问的servlet路径--%>
<form action="register" method="post" style="padding-top:-700px;">
    输入用户名:<input name="name" type="text"><br><br>
    输入密码:<input name="pwd" type="password"><br><br>
    选择性别:<br><br>
    选择家乡:
    <select name="home">
        <option value="上海">上海option>
        <option value="北京" selected>北京option>
        <option value="纽约">纽约option>
    select><br>
    填写个人信息:<br>