写点什么

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

作者:游坦之
  • 2022-11-27
    山东
  • 本文字数:24816 字

    阅读完需:约 81 分钟

写在前言

写作收获 &目的

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


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


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


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


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

目录结构


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


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


<dependencies>  <dependency>    <groupId>junit</groupId>    <artifactId>junit</artifactId>    <version>4.11</version>    <scope>test</scope>  </dependency>  <!--引入Servlet-->  <dependency>      <groupId>javax.servlet</groupId>      <artifactId>javax.servlet-api</artifactId>      <version>3.1.0</version>      <scope>provided</scope>  </dependency>  <!--引入Mybatis-->  <dependency>    <groupId>org.mybatis</groupId>    <artifactId>mybatis</artifactId>    <version>3.5.7</version>  </dependency>  <!--引入mysql-->  <dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>8.0.30</version>  </dependency>  <!--引入FastJson:用于JSon和Java类之间的转换-->  <dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson</artifactId>    <version>1.2.75</version>  </dependency>  <!--引入Lombok-->  <dependency>    <groupId>org.projectlombok</groupId>    <artifactId>lombok</artifactId>    <version>1.18.24</version>  </dependency></dependencies>
复制代码

2 配置 Mybatis

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


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


  • 数据库配置:数据库名称、JDBC、数据库用户名和密码

  • Mapper:让 Mybatis 找到 Mapper.xml

2.1 Mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>                <property name="url" value="jdbc:mysql://localhost:3306/us80?useSSL=false&amp;serverTimezone=UTC"/>                <property name="username" value="root"/>                <property name="password" value="200201203332"/>            </dataSource>        </environment>    </environments>
<mappers> <package name="com/you/web/Mapper"/> </mappers></configuration>
复制代码

2.2 UserMapper.xml

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


<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.you.web.Mapper.UserMapper">
</mapper>
复制代码

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<User> 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");

/* 2、连接数据库 */ String resource = "mybatis-config.xml"; InputStream inputStream = null; inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /* 3、执行SQL语句 */ 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");

/* 2、连接数据库 */ String resource = "mybatis-config.xml"; InputStream inputStream = null; inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /* 3、执行SQL语句 */ 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) { /* 1、获取Session对象 */ HttpSession session = req.getSession(); /* 2、设置Session对象 */ 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");

/* 2、连接数据库 */ String resource = "mybatis-config.xml"; InputStream inputStream = null; inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /* 3、执行SQL语句 */ 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 { /* 1、获取携带的用户名、密码、邮箱 */ String username = req.getParameter("username"); System.out.println("获取的用户名是:"+username);
/* 2、连接数据库 */ String resource = "mybatis-config.xml"; InputStream inputStream = null; inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); /* 3、执行SQL语句 */ 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("放行前"); /* 1、获取Session对象 */ HttpServletRequest httpRequest = (HttpServletRequest)request; HttpSession session = httpRequest.getSession(); /* 2、根据名字获取Session */ 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@ToString
public 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 和该页面都一样,可以换成自己喜欢的


<!DOCTYPE html><html lang="zh-CN">
<head> <meta charset="utf-8"> <title>太空题材404错误页面演示_dowebok</title>
</head>
<body> <div class="mars"></div>
<img src="images/meteor.svg" class="meteor"> <p class="title">很抱歉</p> <p class="subtitle">您输入的用户名或密码错误,请重新登录</p> <div align="center"> <a class="btn-back">3秒后将自动跳转到登录页面</a> </div> <img src="astronaut.svg" class="astronaut"> <img src="images/spaceship.svg" class="spaceship"></body><script language="javascript" type="text/javascript">
// 3秒以后再跳转
setTimeout("javascript:location.href='http://localhost:8080/JavaWeb_Demo_08_war/login.html'", 3000);
</script><style> @keyframes floating { from { transform: translateY(0px); }
65% { transform: translateY(15px); }
to { transform: translateY(0px); } }
html { height: 100%; }
body { background-image: url("../images/star.svg"), linear-gradient(to bottom, #05007A, #4D007D); height: 100%; margin: 0; background-attachment: fixed; overflow: hidden; }
.mars { left: 0; right: 0; bottom: 0; position: absolute; height: 27vmin; background: url("../images/mars.svg") no-repeat bottom center; background-size: cover; }
.logo-404 { position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0; top: 16vmin; width: 30vmin; }
@media (max-width: 480px) and (min-width: 320px) { .logo-404 { top: 45vmin; } }
.meteor { position: absolute; right: 2vmin; top: 16vmin; }
.title { position: relative; z-index: 2; color: white; font-family: "Nunito", sans-serif; font-weight: 600; text-align: center; font-size: 5vmin; margin-top: 31vmin; }
@media (max-width: 480px) and (min-width: 320px) { .title { margin-top: 65vmin; } }
.subtitle { position: relative; z-index: 2; color: white; font-family: "Nunito", sans-serif; font-weight: 400; text-align: center; font-size: 3.5vmin; margin-top: -1vmin; margin-bottom: 9vmin; }
.btn-back { position: relative; z-index: 2; border: 1px solid white; color: white; height: 5vmin; padding: 12px; font-family: "Nunito", sans-serif; text-decoration: none; border-radius: 5px; }
.btn-back:hover { background: white; color: #4D007D; }
@media (max-width: 480px) and (min-width: 320px) { .btn-back { font-size: 3.5vmin; } }
.astronaut { position: absolute; z-index: 1; top: 18vmin; left: 10vmin; height: 30vmin; animation: floating 3s infinite ease-in-out; }
@media (max-width: 480px) and (min-width: 320px) { .astronaut { top: 2vmin; } }
.spaceship { position: absolute; z-index: 1; bottom: 15vmin; right: 24vmin; }
@media (max-width: 480px) and (min-width: 320px) { .spaceship { width: 45vmin; bottom: 18vmin; } }</style></html>
复制代码

6.2 home.html

主页


<!DOCTYPE html><html><head>    <style>        body        {            background:url(https://cdn.jsdelivr.net/gh/yw2667899/pic/img/93401075_p0.jpg);            background-size: cover;        }    </style>    <!--自定义背景图:把上面url()的链接换成你的图片链接,必须是公开图片,可以使用 图床 -->    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    <title>简约导航</title>    <meta name="viewport"          content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0" />    <meta content="telephone=no,email=no" name="format-detection">    <meta content="yes" name="apple-mobile-web-app-capable">    <meta name="apple-mobile-web-app-status-bar-style" content="black" />    <meta name="apple-touch-fullscreen" content="yes" />    <meta name="keywords" content="网址导航" />    <meta name="description" content="一个简单美观可自定义的网址导航" />    <link rel="shortcut icon" href="favicon.ico">    <!-- 注意!为了优化演示站访问速度下方两行引用的是CDN上的CSS文件地址,请修改为自己的样式文件地址 -->    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/appexplore/jianavi/css/style.css" />    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/appexplore/jianavi/css/yidong.css" />    <!-- 本项目开源地址:https://github.com/appexplore/jianavi 请勿完全抄袭源码,请勿声明自己是原创 --></head>
<body>
<!-- 搜索栏start --><div class="baidu baidu-2"> <form name="f" action="https://www.baidu.com/s" target="_blank"> <div class="Select-box-2" id="baidu"> <ul> <li class="this_s">百 度</li> <li class="miji_s">多 吉</li> <li class="bing_s">必 应</li> <li class="google_s">谷 歌</li> <li class="baidu_s">百 度</li> </ul> </div> <div class="in5"> <input name="wd" id="kw-2" maxlength="100" autocomplete="off" type="text"> <div class="qingkong" id="qingkong" title="清空">x</div> </div> <input value="搜 索" id="su-2" type="submit"> </form> <ul class="keylist"></ul></div><!-- 搜索栏end -->
<!-- 内容start --><div class="body"> <div class="content"> <div class="jianjie"> <div class="jj-list"> <div class="jj-list-tit">学习 · 生活</div> <!-- 这里当然可以取你想要的名字啦,下面那几个也是一样的 --> <ul class="jj-list-con"> <li><a href="https://www.taobao.com/" class="link-3" target="_blank" rel="nofollow">淘宝</a></li> <!-- 添加网站:herf=""里面改成要添加的网址,中间夹的汉字改成你想要的名字 --> <li><a href="https://www.jd.com/" class="link-3" target="_blank" rel="nofollow">京东</a></li> <li><a href="https://guiderank-app.com/" class="link-3" target="_blank" rel="nofollow">盖得排行</a></li> <li><a href="http://123.sogou.com/shwz/yinhang.html" class="link-3" target="_blank" rel="nofollow">银行</a></li> <li><a href="https://www.amap.com/" class="link-3" target="_blank" rel="nofollow">地图</a></li> <li><a href="https://translate.google.cn/" class="link-3" target="_blank" rel="nofollow">翻译</a> </li> <li><a href="https://hao.qq.com/qita/youxiang.html" class="link-3" target="_blank" rel="nofollow">邮箱</a></li> <li><a href="https://www.runoob.com/" class="link-3" target="_blank" rel="nofollow">菜鸟教程</a> </li> <li><a href="https://www.icourse163.org/" class="link-3" target="_blank" rel="nofollow">MOOC</a> </li> </ul> </div> <div class="jj-list"> <div class="jj-list-tit">常用 · 社区</div> <ul class="jj-list-con"> <li><a href="https://wx.qq.com/" class="link-3" target="_blank" rel="nofollow">微信</a></li> <li><a href="https://weibo.com/" class="link-3" target="_blank" rel="nofollow">微博</a></li> <li><a href="https://www.zhihu.com/" class="link-3" target="_blank" rel="nofollow">知乎</a></li> <li><a href="https://tieba.baidu.com/" class="link-3" target="_blank" rel="nofollow">贴吧</a></li> <li><a href="http://www.soomal.com/" class="link-3" target="_blank" rel="nofollow">Soomal</a> </li> <li><a href="https://topbook.cc/overview" class="link-3" target="_blank" rel="nofollow">Topbook</a></li> <li><a href="https://github.com/" class="link-3" target="_blank" rel="nofollow">GitHub</a></li> <li><a href="https://www.douban.com/" class="link-3" target="_blank" rel="nofollow">豆瓣</a></li> <li><a href="https://www.v2ex.com/" class="link-3" target="_blank" rel="nofollow">V2EX</a></li> </ul> </div> <div class="jj-list"> <div class="jj-list-tit">影音 · 娱乐</div> <ul class="jj-list-con"> <li><a href="https://www.iqiyi.com/" class="link-3" target="_blank" rel="nofollow">爱奇艺</a></li> <li><a href="https://v.qq.com/" class="link-3" target="_blank" rel="nofollow">腾讯视频</a></li> <li><a href="https://www.bilibili.com/" class="link-3" target="_blank" rel="nofollow">哔哩哔哩</a> </li> <li><a href="https://www.mgtv.com/" class="link-3" target="_blank" rel="nofollow">芒果TV</a></li> <li><a href="https://www.youku.com/" class="link-3" target="_blank" rel="nofollow">优酷</a></li> <li><a href="https://music.163.com/" class="link-3" target="_blank" rel="nofollow">音乐</a></li> <li><a href="https://dianying.fm/" class="link-3" target="_blank" rel="nofollow">电影FM</a></li> <li><a href="https://www.dikotv.com/" class="link-3" target="_blank" rel="nofollow">顶空影视</a> </li> <li><a href="http://www.zzzfun.com/" class="link-3" target="_blank" rel="nofollow">ZzzFun</a> </li> </ul> </div> <div class="jj-list"> <div class="jj-list-tit">发现 · 世界</div> <ul class="jj-list-con"> <li><a href="https://news.ifeng.com/" class="link-3" target="_blank" rel="nofollow">凤凰资讯</a> </li> <li><a href="https://ef.zhiweidata.com/#!/index" class="link-3" target="_blank" rel="nofollow">知微事见</a></li> <li><a href="https://sspai.com/" class="link-3" target="_blank" rel="nofollow">少数派</a></li> <li><a href="https://jikipedia.com/" class="link-3" target="_blank" rel="nofollow">小鸡词典</a></li> <li><a href="https://jandan.net/" class="link-3" target="_blank" rel="nofollow">煎蛋</a></li> <li><a href="https://youquhome.com/" class="link-3" target="_blank" rel="nofollow">有趣网址</a></li> <li><a href="https://zhuxiao.wiki/" class="link-3" target="_blank" rel="nofollow">注销指南</a> </li> <li><a href="https://houxu.app/" class="link-3" target="_blank" rel="nofollow">后续</a></li> <li><a href="https://ac.scmor.com/" class="link-3" target="_blank" rel="nofollow">思谋学术</a></li> </ul> </div> <div class="jj-list"> <div class="jj-list-tit">在线 · 工具</div> <ul class="jj-list-con"> <li><a href="https://www.photopea.com/" class="link-3" target="_blank" rel="nofollow">在线修图</a></li> <li><a href="https://cowtransfer.com/" class="link-3" target="_blank" rel="nofollow">收发文件</a> </li> <li><a href="https://cli.im/" class="link-3" target="_blank" rel="nofollow">二维码</a></li> <li><a href="https://www.linshiyouxiang.net" class="link-3" target="_blank" rel="nofollow">临时邮箱</a></li> <li><a href="https://www.materialtools.com/" class="link-3" target="_blank" rel="nofollow">临时短信</a></li> <li><a href="https://convertio.co/zh/" class="link-3" target="_blank" rel="nofollow">格式转换</a> </li> <li><a href="http://www.hiwenku.com/" class="link-3" target="_blank" rel="nofollow">文档下载</a> </li> <li><a href="https://weibomiaopai.com/" class="link-3" target="_blank" rel="nofollow">视频下载</a> </li> <li><a href="https://www.eggvod.cn/music/" class="link-3" target="_blank" rel="nofollow">音乐下载</a> </li> </ul> </div> <div class="jj-list"> <div class="jj-list-tit">搜索 · 资源</div> <ul class="jj-list-con"> <li><a href="https://www.cupfox.com/" class="link-3" target="_blank" rel="nofollow">茶杯狐</a></li> <li><a href="https://www.dy2018.com/" class="link-3" target="_blank" rel="nofollow">电影天堂</a></li> <li><a href="https://www.coolist.net/" class="link-3" target="_blank" rel="nofollow">酷软清单</a> </li> <li><a href="https://minapp.com/" class="link-3" target="_blank" rel="nofollow">知晓程序</a></li> <li><a href="https://zhengbanxianmian.com/" class="link-3" target="_blank" rel="nofollow">软件限免</a></li> <li><a href="https://www.soukuzhan.com/" class="link-3" target="_blank" rel="nofollow">搜酷站</a></li> <li><a href="https://www.jiumodiary.com/" class="link-3" target="_blank" rel="nofollow">电子书</a> </li> <li><a href="https://pan.appts.cn/" class="link-3" target="_blank" rel="nofollow">常用软件</a> </li> <li><a href="http://www.zimuku.la/" class="link-3" target="_blank" rel="nofollow">字幕库</a></li> </ul> </div> </div> <!-- 内容end -->
<!-- 底部版权start --> <!-- 开源不易,请保留下方本项目开源地址 --> <!-- 如果您不愿意保留下方本项目开源地址,请打赏并留言您的网址 >> https://afdian.net/@appts -->
<div class="footer1">Copyright © 2021 <a href="https://www.appts.cn/" style="color:#ffffff;" target="_blank" rel="nofollow">软件探索 </a> <!-- 请保留下方开源地址--> <a href="https://github.com/appexplore/jianavi" style="color:#ffffff;" target="_blank" rel="nofollow">开源 </a> </div> </div>
<div class="footer">Copyright © 2021 <a href="https://www.appts.cn/" style="color:#ffffff;" target="_blank" rel="nofollow">软件探索 </a> <!-- 请保留下方开源地址--> <a href="https://github.com/appexplore/jianavi" style="color:#ffffff;" target="_blank" rel="nofollow">开源 </a> </div> <!-- 底部版权end --></div>
<!-- 注意!为了优化演示站访问速度下方两行引用的是CDN上的js文件地址,请修改为自己的样式文件地址 --><script type="text/javascript" src="https://cdn.jsdelivr.net/gh/appexplore/jianavi/js/jquery.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/gh/appexplore/jianavi/js/js.min.js"></script></body>
</html>
复制代码

6.3 Login.html

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


<!DOCTYPE html><html><head>    <meta charset="utf-8">    <meta name="viewport"          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">    <title>登录</title>    <link rel="stylesheet" href="css/normalize.css">    <link rel="stylesheet" href="css/login.css">    <link rel="stylesheet" href="css/sign-up-login.css">    <link rel="stylesheet" type="text/css" href="css/font-awesome.4.6.0.css">    <link rel="stylesheet" href="css/inputEffect.css"/>    <link rel="stylesheet" href="css/verifyCode.css"/>    <link rel="stylesheet" href="css/tooltips.css"/>    <link rel="stylesheet" href="css/spop.min.css"/>    <script src="js/jquery-1.10.2.js"></script>    <script src="js/snow.js"></script>    <script src="js/jquery.pure.tooltips.js"></script>    <script src="js/verifyCode.js"></script>    <script src="js/spop.min.js">    </script>    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>    <script>        (function () {            // trim polyfill : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim            if (!String.prototype.trim) {                (function () {                    // Make sure we trim BOM and NBSP                    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;                    String.prototype.trim = function () {                        return this.replace(rtrim, '');                    };                })();            }
[].slice.call(document.querySelectorAll('input.input__field')).forEach(function (inputEl) { // in case the input is already filled.. if (inputEl.value.trim() !== '') { classie.add(inputEl.parentNode, 'input--filled'); }
// events: inputEl.addEventListener('focus', onInputFocus); inputEl.addEventListener('blur', onInputBlur); });
function onInputFocus(ev) { classie.add(ev.target.parentNode, 'input--filled'); }
function onInputBlur(ev) { if (ev.target.value.trim() === '') { classie.remove(ev.target.parentNode, 'input--filled'); } } })();
$(function () { $('#login #login-password').focus(function () { $('.login-owl').addClass('password'); }).blur(function () { $('.login-owl').removeClass('password'); }); $('#login #register-password').focus(function () { $('.register-owl').addClass('password'); }).blur(function () { $('.register-owl').removeClass('password'); }); $('#login #register-repassword').focus(function () { $('.register-owl').addClass('password'); }).blur(function () { $('.register-owl').removeClass('password'); }); $('#login #forget-password').focus(function () { $('.forget-owl').addClass('password'); }).blur(function () { $('.forget-owl').removeClass('password'); }); });
function goto_register() { $("#register-username").val(""); $("#register-password").val(""); $("#register-repassword").val(""); $("#register-code").val(""); $("#tab-2").prop("checked", true); }
function goto_login() { $("#login-username").val(""); $("#login-password").val(""); $("#tab-1").prop("checked", true); }
function goto_forget() { $("#forget-username").val(""); $("#forget-password").val(""); $("#forget-code").val(""); $("#tab-3").prop("checked", true); }
function login() { var username = $("#login-username").val(), password = $("#login-password").val(), verifycode = $("#login-verify-code").val(), validatecode = null; var paramData = {username:username,password,password}; axios({ method: "POST", //请求的方式 url: 'http://localhost:8080/JavaWeb_Demo_08_war/loginServlet', //请求的路径 params: paramData }).then(res=>{ if(res.data) { window.location.href = 'http://localhost:8080/JavaWeb_Demo_08_war/home.html'; }else{ window.location.href = 'http://localhost:8080/JavaWeb_Demo_08_war/error.html'; } }) }
//注册 function register() { var username = $("#register-username").val(), password = $("#register-password").val(), repassword = $("#register-repassword").val(), code = $("#register-code").val(), flag = false, validatecode = null; console.log("拿到的用户名是:" + username); var paramData = {username: username}; axios({ method: "POST", //请求的方式 url: 'http://localhost:8080/JavaWeb_Demo_08_war/userServlet', //请求的路径 params: paramData }).then(resp => { let results = resp.data; if (results == true) { //若可以注册,则访问注册是Servlet var paramData = {username: username,password:password}; axios({ method: "POST", //请求的方式 url: 'http://localhost:8080/JavaWeb_Demo_08_war/RegisterServlet', //请求的路径 params: paramData }).then(resp=>{ if(resp.data) { window.location.href = 'http://localhost:8080/JavaWeb_Demo_08_war/registerSuccess.html'; } }) } else {
} }) }
//重置密码 function forget() { var username = $("#forget-username").val(), password = $("#forget-password").val(), code = $("#forget-code").val(), flag = false, validatecode = null; /* 1、设置参数 */ var paramData = {'username':username,'password':password}; /* 2、发送axios请求 */ axios({ method: "POST", //请求的方式 url: 'http://localhost:8080/JavaWeb_Demo_08_war/ForgetServlet', //请求的路径 params: paramData }).then(res=>{ if(res.data) { /* 1、如果修改成功了,就让其跳转到登录页面 */ window.location.href = 'http://localhost:8080/JavaWeb_Demo_08_war/success.html'; }else{ /* 2、自己写着玩吧 */ } })
}
/* 以下为我自己写的代码 */ /* 填完用户名的时候,查询数据库 */ $(function () { $('#register-username').blur(function () { /* 查询数据库 */ var username = $("#register-username").val(); console.log("拿到的用户名是:" + username); var paramData = {username: username}; axios({ method: "POST", //请求的方式 url: 'http://localhost:8080/JavaWeb_Demo_08_war/userServlet', //请求的路径 params: paramData }).then(resp => { let results = resp.data; if (results == true) {
} else { alert("用户名已存在,请更换一个")
} })

}) })

</script> <style type="text/css"> html { width: 100%; height: 100%; }
body {
background-repeat: no-repeat;
background-position: center center #2D0F0F;
background-color: #00BDDC;
background-image: url(images/snow.jpg);
background-size: 100% 100%;
}
.snow-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 100001; }
</style></head><body>
<div class="snow-container"></div>
<div id="login"> <input id="tab-1" type="radio" name="tab" class="sign-in hidden" checked/> <input id="tab-2" type="radio" name="tab" class="sign-up hidden"/> <input id="tab-3" type="radio" name="tab" class="sign-out hidden"/> <div class="wrapper">
<div class="login sign-in-htm"> <form class="container offset1 loginform">
<div id="owl-login" class="login-owl"> <div class="hand"></div> <div class="hand hand-r"></div> <div class="arms"> <div class="arm"></div> <div class="arm arm-r"></div> </div> </div> <div class="pad input-container"> <section class="content"><span class="input input--hideo"><input class="input__field input__field--hideo" value="admin" type="text" id="login-username" autocomplete="off" placeholder="请输入用户名" tabindex="1" maxlength="15"/><label class="input__label input__label--hideo" for="login-username"><i class="fa fa-fw fa-user icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span> <span class="input input--hideo"><input class="input__field input__field--hideo" type="password" id="login-password" placeholder="请输入密码" tabindex="2" maxlength="15"/><label class="input__label input__label--hideo" for="login-password"><i class="fa fa-fw fa-lock icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span> <span class="input input--hideo input--verify_code"><input class="input__field input__field--hideo" type="text" id="login-verify-code" autocomplete="off" placeholder="请输入验证码" tabindex="3" maxlength="4"/><label class="input__label input__label--hideo" for="login-verify-code"><i class="fa fa-fw fa-bell-o icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span> <canvas class="verify-code-canvas" id="login-verify-code-canvas"></canvas> </section> </div> <div class="form-actions"> <a tabindex="4" class="btn pull-left btn-link text-muted" onclick="goto_forget()">忘记密码?</a> <a tabindex="5" class="btn btn-link text-muted" onclick="goto_register()">注册</a> <input class="btn btn-primary" type="button" tabindex="3" onclick="login()" value="登录" style="color:white;"/> </div> </form> </div>
<div class="login sign-out-htm"> <form action="#" method="post" class="container offset1 loginform">
<div id="owl-login" class="forget-owl"> <div class="hand"></div> <div class="hand hand-r"></div> <div class="arms"> <div class="arm"></div> <div class="arm arm-r"></div> </div> </div> <div class="pad input-container"> <section class="content"><span class="input input--hideo"><input class="input__field input__field--hideo" type="text" id="forget-username" autocomplete="off" placeholder="请输入用户名"/><label class="input__label input__label--hideo" for="forget-username"><i class="fa fa-fw fa-user icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label>
</span> <span class="input input--hideo"><input class="input__field input__field--hideo" type="password" id="forget-password" placeholder="请重置密码"/><label class="input__label input__label--hideo" for="forget-password"><i class="fa fa-fw fa-lock icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span> </section> </div> <div class="form-actions"> <a class="btn pull-left btn-link text-muted" onclick="goto_login()">返回登录</a> <input class="btn btn-primary" type="button" onclick="forget()" value="重置密码" style="color:white;"/> </div> </form> </div>
<div class="login sign-up-htm"> <form action="#" method="post" class="container offset1 loginform">
<div id="owl-login" class="register-owl"> <div class="hand"></div> <div class="hand hand-r"></div> <div class="arms"> <div class="arm"></div> <div class="arm arm-r"></div> </div> </div> <div class="pad input-container"> <section class="content"><span class="input input--hideo"><input class="input__field input__field--hideo" type="text" id="register-username" autocomplete="off" placeholder="请输入用户名" maxlength="15"/><label class="input__label input__label--hideo" for="register-username"><i class="fa fa-fw fa-user icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span> <span class="input input--hideo"><input class="input__field input__field--hideo" type="password" id="register-password" placeholder="请输入密码" maxlength="15"/><label class="input__label input__label--hideo" for="register-password"><i class="fa fa-fw fa-lock icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span> <span class="input input--hideo"><input class="input__field input__field--hideo" type="password" id="register-repassword" placeholder="请确认密码" maxlength="15"/><label class="input__label input__label--hideo" for="register-repassword"><i class="fa fa-fw fa-lock icon icon--hideo"></i><span class="input__label-content input__label-content--hideo"></span></label></span>
</section> </div> <div class="form-actions"> <a class="btn pull-left btn-link text-muted" onclick="goto_login()">返回登录</a> <input class="btn btn-primary" type="button" onclick="register()" value="注册" style="color:white;"/> </div> </form> </div> </div></div></body></html>
复制代码

6.4 registerSuccess.html

注册成功跳转的页面


<!DOCTYPE html><html lang="zh-CN">
<head> <meta charset="utf-8"> <title>太空题材404错误页面演示_dowebok</title>
</head>
<body> <div class="mars"></div>
<img src="images/meteor.svg" class="meteor"> <p class="title">恭喜您呐!</p> <p class="subtitle">注册成功了呢!</p> <div align="center"> <a class="btn-back">3秒后将自动跳转到登录页面</a> </div> <img src="astronaut.svg" class="astronaut"> <img src="images/spaceship.svg" class="spaceship"></body><script language="javascript" type="text/javascript">
// 3秒以后再跳转
setTimeout("javascript:location.href='http://localhost:8080/JavaWeb_Demo_08_war/login.html'", 3000);
</script><style> @keyframes floating { from { transform: translateY(0px); }
65% { transform: translateY(15px); }
to { transform: translateY(0px); } }
html { height: 100%; }
body { background-image: url("../images/star.svg"), linear-gradient(to bottom, #05007A, #4D007D); height: 100%; margin: 0; background-attachment: fixed; overflow: hidden; }
.mars { left: 0; right: 0; bottom: 0; position: absolute; height: 27vmin; background: url("../images/mars.svg") no-repeat bottom center; background-size: cover; }
.logo-404 { position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0; top: 16vmin; width: 30vmin; }
@media (max-width: 480px) and (min-width: 320px) { .logo-404 { top: 45vmin; } }
.meteor { position: absolute; right: 2vmin; top: 16vmin; }
.title { position: relative; z-index: 2; color: white; font-family: "Nunito", sans-serif; font-weight: 600; text-align: center; font-size: 5vmin; margin-top: 31vmin; }
@media (max-width: 480px) and (min-width: 320px) { .title { margin-top: 65vmin; } }
.subtitle { position: relative; z-index: 2; color: white; font-family: "Nunito", sans-serif; font-weight: 400; text-align: center; font-size: 3.5vmin; margin-top: -1vmin; margin-bottom: 9vmin; }
.btn-back { position: relative; z-index: 2; border: 1px solid white; color: white; height: 5vmin; padding: 12px; font-family: "Nunito", sans-serif; text-decoration: none; border-radius: 5px; }
.btn-back:hover { background: white; color: #4D007D; }
@media (max-width: 480px) and (min-width: 320px) { .btn-back { font-size: 3.5vmin; } }
.astronaut { position: absolute; z-index: 1; top: 18vmin; left: 10vmin; height: 30vmin; animation: floating 3s infinite ease-in-out; }
@media (max-width: 480px) and (min-width: 320px) { .astronaut { top: 2vmin; } }
.spaceship { position: absolute; z-index: 1; bottom: 15vmin; right: 24vmin; }
@media (max-width: 480px) and (min-width: 320px) { .spaceship { width: 45vmin; bottom: 18vmin; } }</style></html>
复制代码

6.5 CSS 和 JS

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

7 效果图

7.1 登录成功

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

7.3 用户名已存在

7.4 注册成功

7.5 修改密码成功

7.6 未登录直接访问主页

8 静态页面资源

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

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

用户头像

游坦之

关注

还未添加个人签名 2022-10-14 加入

还未添加个人简介

评论

发布
暂无评论
整合Mybatis、Servlet、Mysql、Axios、Filter、Session写一个入门级项目:非常适合初接触JavaWeb的小白白来进阶_MySQL_游坦之_InfoQ写作社区