返回顶部
首页 > 资讯 > 数据库 >整合Mybatis、Servlet、Mysql、Axios、Filter、Session写一个入门级项目:非常适合初接触JavaWeb的小白白来进阶
  • 642
分享到

整合Mybatis、Servlet、Mysql、Axios、Filter、Session写一个入门级项目:非常适合初接触JavaWeb的小白白来进阶

mybatisservletmysql后端 2023-08-16 18:08:16 642人浏览 独家记忆
摘要

文章目录 写在前言写作收获&目的目录结构 1 依赖配置1.1 创建一个Web项目1.2 Pom.xml 2 配置Mybatis2.1 Mybatis-config.xml2.2 UserMapper.xml2.3 UserM

写在前言

写作收获&目的

​ 本篇文章结构大体还是和上篇文章 Mybatis+Servlet+Mysql 整合的一个小项目一致,但增加了axiOS、Filter、session。

数据库层面涉及到了增、查、改,一个代码量不算多的小项目,但十分有助于初学者的学习

​ 博主在编写项目的同时,发现自己对Axios、Filter的理解并不好,通过本项目,打扎实了自己的基础。

开发此小项目之前,我对同学说,我异步请求用的很少,殊不知自己一直在用异步请求,反而同步请求用的很少很少了。

​ 在编写项目之时,被axios post传参困扰了很久很久,最后终于通过查询CSDN找到了自己想要的答案。

目录结构

image-20220920211841428

image-20220920211743849

1 依赖配置

1.1 创建一个WEB项目

不会的可以看这篇文章【Tomcat】贰-Tomcat集成到Idea

1.2 Pom.xml

还是和往常一样分析一下需要用到哪些依赖。

上文中提到了mybatis、Lombok、Mysql、Servlet、Junit,这篇文章也用到了,引入的Filter是Servlet里面的,Axios的引入方式又非Pom.xml。至于JSON,本篇文章没有用到,所以本文章的依赖有:

  • Mybatis
  • Lombok
  • mysql
  • Servlet
  • Junit

友情提示:不要引错了,否则有些类不能使用

      junit    junit    4.11    test            javax.servlet      javax.servlet-api      3.1.0      provided          org.mybatis    mybatis    3.5.7          mysql    mysql-connector-java    8.0.30          com.alibaba    fastjson    1.2.75          org.projectlombok    lombok    1.18.24  

2 配置Mybatis

上文漏掉的,mybatis-config.xml需要放在resource文件夹下。

mybatis-config配置,主要包括两个点:

  • 数据库配置:数据库名称、JDBC、数据库用户名和密码
  • Mapper:让Mybatis找到Mapper.xml

2.1 Mybatis-config.xml

                                                                                                                                            

2.2 UserMapper.xml

这里的xml文件只是起到了一个绑定接口的作用。如果没有本文件,那么Mybatis是找不到UserMapper的,也就意味着SQl语句不能被执行。

2.3 UserMapper.interface

package com.you.web.Mapper;import com.you.web.Dept.User;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;import java.util.List;public interface UserMapper {    @Select("select * from user where user_name = #{user_name} and user_pwd = #{user_pwd}")    public User selectUserByInfo(@Param("user_name") String user_name, @Param("user_pwd") String user_pwd);    @Select("select * from user")    public List queryAllUsers();    @Insert("insert into user values(null,#{user_name},#{user_pwd},#{user_emil})")    public boolean reGISterUser(@Param("user_name") String user_name,@Param("user_pwd") String user_pwd,@Param("user_emil") String user_emil);        @Select("select * from user where user_name = #{user_name}")    public User selectUserByUsername(@Param("user_name") String user_name);    @Update("update user set user_pwd = #{user_pwd} where user_name = #{user_name}")    public boolean reviseUserByInfo(@Param("user_name") String user_name, @Param("user_pwd") String user_pwd);}

3 配置Tomcat

参考本人的文章 【Tomcat】贰-Tomcat集成到Idea

4 Servlet类

4.1 ForgetServlet

处理忘记密码业务

package com.you.web.Servlet;import com.you.web.Dept.User;import com.you.web.Mapper.UserMapper;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.Http.httpservlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;@WebServlet(urlPatterns = "/ForgetServlet")public class ForgetServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String username = req.getParameter("username");        String passWord = req.getParameter("password");                String resource = "mybatis-config.xml";        InputStream inputStream = null;        inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        SqlSession sqlSession = sqlSessionFactory.openSession();                UserMapper mapper = sqlSession.getMapper(UserMapper.class);        boolean user = mapper.reviseUserByInfo(username, password);        resp.setContentType("text/html;charset=UTF-8");        PrintWriter writer = resp.getWriter();        if(user)        {            //提交            sqlSession.commit();            writer.write("true");        }else{            writer.write("false");        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doGet(req,resp);    }}

4.2 LoginServlet

处理登录业务的

package com.you.web.Servlet;import com.you.web.Dept.User;import com.you.web.Mapper.UserMapper;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;@WebServlet("/loginServlet")public class LoginServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String username = req.getParameter("username");        String password = req.getParameter("password");                String resource = "mybatis-config.xml";        InputStream inputStream = null;        inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        SqlSession sqlSession = sqlSessionFactory.openSession();                UserMapper mapper = sqlSession.getMapper(UserMapper.class);        User user = mapper.selectUserByInfo(username, password);        resp.setContentType("text/html;charset=UTF-8");        PrintWriter writer = resp.getWriter();        if(user != null)        {                        HttpSession session = req.getSession();                        session.setAttribute("username",username);            session.setAttribute("password",password);            writer.write("true");        }else{            writer.write("false");        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doGet(req,resp);    }}

4.3 RegisterServlet

处理注册业务

package com.you.web.Servlet;import com.you.web.Dept.User;import com.you.web.Mapper.UserMapper;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;@WebServlet(urlPatterns = "/RegisterServlet")public class RegisterServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String username = req.getParameter("username");        String password = req.getParameter("password");                String resource = "mybatis-config.xml";        InputStream inputStream = null;        inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        SqlSession sqlSession = sqlSessionFactory.openSession();                UserMapper mapper = sqlSession.getMapper(UserMapper.class);        boolean b = mapper.registerUser(username, password, null);        resp.setContentType("text/html;charset=UTF-8");        PrintWriter writer = resp.getWriter();        if(b == true)        {            sqlSession.commit();            writer.write("true");        }else{            writer.write("false");        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doGet(req,resp);    }}

4.4 UserServlet

处理用户名是否存在

package com.you.web.Servlet;import com.mysql.cj.xdevapi.JsonParser;import com.you.web.Dept.User;import com.you.web.Mapper.UserMapper;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.List;import java.util.Map;@WebServlet("/userServlet")public class UserServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {                String username = req.getParameter("username");        System.out.println("获取的用户名是:"+username);                String resource = "mybatis-config.xml";        InputStream inputStream = null;        inputStream = Resources.getResourceAsStream(resource);        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);        SqlSession sqlSession = sqlSessionFactory.openSession();                UserMapper mapper = sqlSession.getMapper(UserMapper.class);        User user = mapper.selectUserByUsername(username);        resp.setContentType("text/html;charset=UTF-8");        PrintWriter writer = resp.getWriter();        if (user!=null)        System.out.println("user的值是:"+user);        if(user == null)        {            writer.write("true");        }else{            writer.write("false");        }    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        this.doGet(req,resp);    }}

5 Filter类和实体类

5.1 HomeFilter

处理未登录不可访问Home页面的业务

package com.you.web.Filter;import com.sun.deploy.net.HttpRequest;import com.sun.deploy.net.HttpResponse;import javax.servlet.*;import javax.servlet.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.io.IOException;@WebFilter("/home.html")public class HomeFilter implements Filter {    @Override    public void init(FilterConfig filterConfig) throws ServletException {    }    @Override    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {        System.out.println("放行前");                HttpServletRequest httpRequest = (HttpServletRequest)request;        HttpSession session = httpRequest.getSession();                Object username = null;        if(session.getAttribute("username")!=null)        {            username = session.getAttribute("username");        }else{            System.out.println("我是空的,爱咋咋地!");        }        Object password = null;        if(session.getAttribute("password")!=null)        {            password = session.getAttribute("password");        }else{            System.out.println("我是空的,爱咋咋地!");        }        if(username!=null&&password!=null)        {            System.out.println("放行!!!");            chain.doFilter(request,response);        }else {            System.out.println("hey,我要跳转");            HttpServletResponse httpResponse = (HttpServletResponse) response;            httpResponse.sendRedirect("http://localhost:8080/javaweb_Demo_08_war/prelogin.html");        }    }    @Override    public void destroy() {    }}

5.2 User

package com.you.web.Dept;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;import lombok.ToString;@Data@NoArgsConstructor@AllArgsConstructor@ToStringpublic class User {    private Integer user_no;    private String user_name;    private String user_pwd;    private String user_emial;}

6 静态页面

6.1 error.html

  • 登录失败跳转到的页面

  • prelogin.html、success.html和该页面都一样,可以换成自己喜欢的

        太空题材404错误页面演示_dowebok    

很抱歉

您输入的用户名或密码错误,请重新登录

6.2 home.html

主页

                简约导航                                                
  • 百 度
  • 多 吉
  • 必 应
  • 谷 歌
  • 百 度
x

    6.3 Login.html

    涵盖了登录、注册、修改密码的页面

                登录                                                                

    6.4 registerSuccess.html

    注册成功跳转的页面

            太空题材404错误页面演示_dowebok    

    恭喜您呐!

    注册成功了呢!

    6.5 CSS和JS

    css和Js文件,请前往8所载资源路径下载,下载后直接复制粘贴进 前言所载的相应的目录文件即可

    7 效果图

    7.1 登录成功

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-097uLsPq-1663680000001)(https://gitee.com/you-tanzhi/pic/raw/master/%E6%88%90%E5%8A%9F%E8%AE%BF%E9%97%AE.gif)]

    7.2 登录成功之后直接访问主页

    在这里插入图片描述

    7.3 用户名已存在

    在这里插入图片描述

    7.4 注册成功

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-46Q5TtIV-1663680000003)(https://gitee.com/you-tanzhi/pic/raw/master/%E6%B3%A8%E5%86%8C%E6%88%90%E5%8A%9F.gif)]

    7.5 修改密码成功

    7.6 未登录直接访问主页

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3Vk4k9wJ-1663680000004)(https://gitee.com/you-tanzhi/pic/raw/master/%E5%B0%9A%E6%9C%AA%E7%99%BB%E5%BD%95.gif)]

    8 静态页面资源

    1. 小飞象 login-register-html 静态资源

    2. 杨鑫 太空题材的404错误页面

    来源地址:https://blog.csdn.net/m0_59792745/article/details/126961965

    您可能感兴趣的文档:

    --结束END--

    本文标题: 整合Mybatis、Servlet、Mysql、Axios、Filter、Session写一个入门级项目:非常适合初接触JavaWeb的小白白来进阶

    本文链接: https://lsjlt.com/news/371944.html(转载时请注明来源链接)

    有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

    猜你喜欢
    软考高级职称资格查询
    编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
    • 官方手机版

    • 微信公众号

    • 商务合作