一个适合小白的Javaweb基础项目(IDEA)

项目技术

使用Servlet、JDBC、Tomcat、Maven和IDEA完成最基础的增删改查。

主要功能

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

整体架构

一个适合小白的Javaweb基础项目(IDEA)_第1张图片

1.新建mysql表

-- 创建一个新的数据库object
CREATE DATABASE `object`

-- 创建user表
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 CHARSET=utf8;

-- 查看表结构
SELECT * FROM `user` WHERE 1<>1;

-- 插入数据
INSERT INTO `user` VALUE ('1', 'xiaoming', '123456', '男', '上海', 'ABCD');
INSERT INTO `user` VALUE ('2', 'maqiag', '23333', '男', '杭州', '1234');
INSERT INTO `user` VALUE ('3', 'xiaohong', '999999', '女', '北京', '9876');
INSERT INTO `user` VALUE ('4', 'mawang', '66666', '男', '广州', 'QWER');
INSERT INTO `user` VALUE ('5', 'xiaoyu', '55555', '女', '成都', '9876');
INSERT INTO `user` VALUE ('6', 'mafeng', '77777', '男', '武汉', '996');

2.IDEA新建maven项目

一个适合小白的Javaweb基础项目(IDEA)_第2张图片

这里选择设置好的maven环境,选择自己的maven位置。
一个适合小白的Javaweb基础项目(IDEA)_第3张图片在src下建立项目包结构
一个适合小白的Javaweb基础项目(IDEA)_第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>javawebartifactId>
    <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>
            <scope>testscope>
        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方法,二者没区别。

package com.entiy;

import lombok.Data;

/**
 * User实体类
 */
@Data
public class User {
    private int id;
    private String name;
    private String pwd;
    private String sex;
    private String home;
    private String info;
}

一个适合小白的Javaweb基础项目(IDEA)_第5张图片

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/object?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
    static String userName = "root";
    static String password = "123456";

    static Connection connection = null;
    static ResultSet resultSet = null;
    static PreparedStatement preparedStatement = null;

    /**
     * 连接数据库
     */
    public static void init() {
        try {
            //1.加载驱动获得驱动管理器
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.连接数据库
            connection = DriverManager.getConnection(url, userName, password);
            System.out.println("连接数据库成功!");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("连接数据库失败!");
        }
    }

    /**
     * 查询数据(传递参数)
     *
     * @param sql
     * @param args
     */
    public static ResultSet searchSql(String sql, Object[] args) {
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            resultSet = preparedStatement.executeQuery();
            System.out.println("查询成功!");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询失败!");
        }
        return resultSet;
    }

    /**
     * 增删改查数据(传递参数)
     *
     * @param sql
     * @param args
     */
    public static int addUpdateDelete(String sql, Object[] args) {
        int i = 0;
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int j = 0; j < args.length; j++) {
                preparedStatement.setObject(j + 1, args[j]);
            }
            i = preparedStatement.executeUpdate();
            System.out.println("增删改成功!");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("增删改失败!");
        }
        return i;
    }

    /**
     * 查询全部信息(不传参)
     *
     * @param sql
     */
    public static ResultSet getUsers(String sql) {
        try {
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            System.out.println("查询成功!");
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("查询失败!");
        }
        return resultSet;
    }

    /**
     * 关闭流
     */
    public static void close() {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (connection != null) {
                connection.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;

    /**
     * 根据前台的账号密码判断能否登录成功
     *
     * @param name
     * @param pwd
     * @return flag
     */
    public boolean login(String name, String pwd) {
        try {
            //连接数据库
            DBCoon.init();
            sql = "select * from user where name= ? and pwd = ?";
            //使用预编译SQL传递参数
            Object[] args = {name, pwd};
            ResultSet resultSet = DBCoon.searchSql(sql, args);
            //遍历数据库里的账号密码与从jsp传来的账号密码作对比
            while (resultSet.next()) {
                if (resultSet.getString("name").equals(name) && resultSet.getString("pwd").equals(pwd)) {
                    flag = true;
                    System.out.println("登录成功!");
                }
            }
        } catch (Exception e) {
            System.out.println("登录失败!");
            e.printStackTrace();
        } finally {
            //关闭流
            DBCoon.close();
        }
        return flag;
    }

    /**
     * 获取前台的注册信息,封装成user对象
     *
     * @param user
     * @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.addUpdateDelete(sql, args);
            if (i > 0) {
                flag = true;
                System.out.println("注册成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("注册失败!");
        } finally {
            //关闭流
            DBCoon.close();
        }
        return flag;
    }

    /**
     * 返回所有的用户信息
     *
     * @return
     */
    public List<User> searchAll() {
        List<User> list = new ArrayList<User>();
        try {
            //连接数据库
            DBCoon.init();
            sql = "select * from user";
            //进行查询
            ResultSet users = DBCoon.getUsers(sql);
            System.out.println("成功获取所有用户!");
            while (users.next()) {
                User user = new User();
                user.setId(users.getInt("id"));
                user.setName(users.getString("name"));
                user.setPwd(users.getString("pwd"));
                user.setSex(users.getString("sex"));
                user.setHome(users.getString("home"));
                user.setInfo(users.getString("info"));
                list.add(user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("获取失败!");
        } finally {
            //关闭流
            DBCoon.close();
        }
        return list;
    }

    /**
     * 根据获取到的内容更新用户信息
     *
     * @param id
     * @param name
     * @param pwd
     * @param sex
     * @param home
     * @param info
     * @return flag
     */
    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.addUpdateDelete(sql, args);
            if (i > 0) {
                flag = true;
                System.out.println("数据更新成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("数据更新失败!");
        } finally {
            //关闭流
            DBCoon.close();
        }
        return flag;
    }

    /**
     * 根据前台传递的id删除用户
     *
     * @param id
     * @return flag
     */
    public boolean delete(int id) {
        try {
            //连接数据库
            DBCoon.init();
            sql = "delete from user where id = ?";
            Object[] args = {id};
            //进行增删改
            int i = DBCoon.addUpdateDelete(sql, args);
            if (i > 0) {
                flag = true;
                System.out.println("删除成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("删除失败!");
        } finally {
            //关闭流
            DBCoon.close();
        }
        return flag;
    }
}

8.servlet

注意:
1.这里用到了请求转发和重定向;
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 {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getParameter获取前台输入框的值即input框里的值
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        UserDao userDao = new UserDaoImpl();
        if (userDao.login(name, pwd)) {
            //存在用户返回登陆成功
            System.out.println("用户"+name+"登陆成功!");
            //前台返回成功
            request.setAttribute("msg","用户"+name+"登陆成功!");
            //使用请求转发,路径加不加/都行
            request.getRequestDispatcher("success.jsp").forward(request,response);
        } else {
            //如果失败则使用重定向到错误页面
            response.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 {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getParameter获取前台输入框的值即input框里的值
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String sex = request.getParameter("sex");
        String home = request.getParameter("home");
        String info = request.getParameter("info");
        //实例化一个对象,用来组装以上属性
        User user = new User();
        user.setName(name);
        user.setPwd(pwd);
        user.setSex(sex);
        user.setHome(home);
        user.setInfo(info);
        UserDao userDao = new UserDaoImpl();
        if (userDao.register(user)){
            //注册成功返回
            System.out.println("用户"+name+"注册成功!");
            request.setAttribute("msg","用户"+name+"注册成功!");
            request.getRequestDispatcher("success.jsp").forward(request, response);
        }else {
            //如果失败则使用重定向到错误页面
            response.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 {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        UserDao userDao = new UserDaoImpl();
        List<User> list = userDao.searchAll();
        request.setAttribute("users", list);
        System.out.println("查询所有用户成功!");
        request.getRequestDispatcher("/showAll.jsp").forward(request, response);
    }
}

删除DeleteServlet

package com.servlet;

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

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

/**
 * 删除用户
 */
public class DeleteServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getParameter获取前台输入框的值即input框里的值
        String id = request.getParameter("id");
        System.out.println("删除的用户id为:" + id);
        //获取到的id是一个引用数据类型即对象,需要变成基本数据类型作为参数传输
        int userId = Integer.parseInt(id);
        UserDao userDao = new UserDaoImpl();
        //进行删除操作,同时判断是否成功
        if (userDao.delete(userId)) {
            //站内转发:请求转发到searchAll的servlet
            request.getRequestDispatcher("searchAll").forward(request, response);
        } else {
            //如果失败则使用重定向到错误页面
            response.sendRedirect("error.jsp");
        }
    }

}

更新UpdateServlet

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 UpdateServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //request.getParameter获取前台输入框的值即input框里的值
        String id = request.getParameter("id");
        //获取到的id是一个引用数据类型即对象,需要变成基本数据类型作为参数传输
        int userId = Integer.parseInt(id);
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        String sex = request.getParameter("sex");
        String home = request.getParameter("home");
        String info = request.getParameter("info");
        UserDao userDao = new UserDaoImpl();
        //进行更新操作,同时判断是否成功
        if(userDao.update(userId, name, pwd, sex, home, info)){
            request.getRequestDispatcher("searchAll").forward(request, response);
        }else{
            //如果失败则使用重定向到错误页面
            response.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页面

注意:下列JSP页面的风格可根据自己喜欢设计。

登录login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    登录



welcome

账号:

密码:



新用户注册

一个适合小白的Javaweb基础项目(IDEA)_第6张图片
注册register.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    注册


<%--action后面跟的就是要访问的servlet路径--%>

Register

账 号:
密 码:
性 别:
家 乡:
个人信息:


一个适合小白的Javaweb基础项目(IDEA)_第7张图片操作成功success.jsp

注意:
1.el表达式取值
2.href访问servlet

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    成功


<%--使用el表达式获取request域里的属性--%>
${msg}

<%--href后面可以跟要跳转的jsp文件,也可以跟要访问的servlet路径,这里访问了servlet则web.xml里必须有这个路径--%> 查看所有用户

一个适合小白的Javaweb基础项目(IDEA)_第8张图片
操作失败error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    错误


操作错误

返回首页

显示所有用户信息showAll.jsp

注意:
1.jstl表达式需要导入核心配置文件core
2.${users}获取名为users的对象
3.使用c标签的foreach遍历对象users,遍历后的别名为U
4.通过a标签href属性访问servlet并使用?id传递参数

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    所有用户信息




        
ID 姓名 性别 密码 家乡 备注 操作
删除

一个适合小白的Javaweb基础项目(IDEA)_第9张图片

总结

这是javaweb最基础的操作,整个项目使用了MVC三层架构模式,controller即servlet直接调用了model层的dao方法,因为只有一个表,不需要多表查询,所以没有用到service层。项目整体的逻辑还是非常清晰的,如果大家有遇到不懂的建议先百度解决,有些坑迟早都是要踩的。

你可能感兴趣的:(项目,web,java,mysql)