cookie+mybatis+servlet實現(xiàn)免登錄時長兩天半的整體流程
前言
應(yīng)用主要用到的技術(shù)有session、cookie、轉(zhuǎn)發(fā)、重定向、filter、和servlet,最重要的還是具體的來運用它們在前端頁面真正的搭建出一個應(yīng)用,通過這個練習(xí),對我們所學(xué)的web知識做一個整合。
流程
整體流程就是瀏覽器(客戶端)向服務(wù)器端發(fā)送請求,服務(wù)器端servlet調(diào)用mybatis對數(shù)據(jù)庫進行查詢及操作,返回結(jié)果

大概框架
在這里先把簡單的架子搭起來,測試能不能實現(xiàn)前后端互通。比如前端登錄之后經(jīng)過服務(wù)器調(diào)用查詢數(shù)據(jù)庫,先把架子搭起來,再添加其他的操作。這樣更能使得框架結(jié)構(gòu)清晰
----------值得注意的是,要把各種依賴或者配置的版本整合起來,這里大概配置如下:jdk1.8、tomcat9、webservlet4.0
數(shù)據(jù)庫實現(xiàn):
我比較習(xí)慣從后端往前端做,先把表設(shè)計出來,這里因為只做一個簡單的十天免登錄,所以用戶表只設(shè)置了兩個字段。
create table tbl_user(
username varchar(22),
password varchar(22)
);
insert into tbl_user values ('zhangsan','775033');這里得介紹一個東西,什么東西呢?三層架構(gòu)?。?!**
三層架構(gòu):
不用想的太復(fù)雜,其實就是在開發(fā)中,隨著信息量的增大,如果按照以前的格式代碼全寫一塊,過于冗余,而且不便于維護,這個時候就跳出了三層架構(gòu)的方法,簡單來說就是把復(fù)制不同功能的代碼分成不同階級。每一部分各司其職。
表示層(controller):主要對用戶的請求接受,以及數(shù)據(jù)的返回,為客戶端提供應(yīng)用程序的訪問。
業(yè)務(wù)邏輯層(service):主要負責(zé)對數(shù)據(jù)層的操作。也就是說把一些數(shù)據(jù)層的操作進行組合。
數(shù)據(jù)訪問層(dao/mapper):主要看數(shù)據(jù)層里面有沒有包含邏輯處理,實際上它的各個函數(shù)主要完成各個對數(shù)據(jù)文件的操作。而不必管其他操作。

介紹完上邊之后,我們就可以開始搭建三層架構(gòu)的框子了?。?!
三層架構(gòu)架子

這里的pojo是實體類,也就是JavaBean
項目創(chuàng)建—導(dǎo)入依賴
相信大家都會創(chuàng)建項目了,這里我創(chuàng)建了一個叫做session的模塊,用于項目的實現(xiàn)
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>servlet-test01</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- 添加測試依賴-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- 添加mybatis依賴-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- 添加servlet依賴-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 添加MySQL依賴-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
<!-- 添加jsp依賴-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
<!-- 添加el表達式依賴-->
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.0</version>
</dependency>
<!-- 添加jstl標簽庫依賴-->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
</project>接下來就是從底層做起,先從數(shù)據(jù)訪問層開始
mybatis配置文件創(chuàng)建:
SqlMapperConfig.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>
<!--導(dǎo)入數(shù)據(jù)源-->
<properties resource="jdbc.properties">
</properties>
<typeAliases>
<!--設(shè)置實體類別名-->
<typeAlias type="com.bipt.pojo.User" alias="user"></typeAlias>
<package name="com.bipt.pojo"/>
</typeAliases>
<!--配置環(huán)境-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/><!--事物管理器-->
<dataSource type="POOLED"><!---->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--注冊mapper文件-->
<mappers>
<mapper resource="com/bipt/mapper/UserMapper.xml"/>
<package name="com.bipt.mapper.UserMapper"/>
</mappers>
</configuration>jdbc.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/tbl_student?serverTimezone=UTC jdbc.username=root jdbc.password=775033
構(gòu)造usermapper:
<?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.bipt.mapper.UserMapper">數(shù)據(jù)訪問層的映射文件:
<?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.bipt.mapper.UserMapper">
<select id="select" resultType="user">
select username,password from tbl_user
where username=#{username} and password=#{password};
</select>
<insert id="addUser">
insert into tbl_user values ('${username}','${password}');
</insert>
</mapper>注意該映射文件是在mapper同級目錄下的,名字和mapper的實體類名字相同

當(dāng)然,你也可以把UserMapper和UserMapper.xml都放在mapper層,不過這樣的話就得手動的添加文件build。不推薦
創(chuàng)建mapper層接口
我們把配置文件弄好了之后,就開始構(gòu)建mapper層的接口創(chuàng)建方法訪問數(shù)據(jù)庫:
package com.bipt.mapper;
import com.bipt.pojo.User;
import org.apache.ibatis.annotations.Param;
/**
* @author 不止于夢想
* @date 2022/10/3 18:53
*/
public interface UserMapper {
//驗證登錄的用戶是否存在
User select(@Param("username") String username,
@Param("password") String password);
//添加用戶
int addUser(@Param("username") String username,
@Param("password") String password);
}應(yīng)該注意到UserMapper 的方法和UserMapper.xml中的select中的id相同,這就是動態(tài)代理的方式,通過配置文件映射創(chuàng)建對象,并調(diào)用方法
三層架構(gòu)的service層
編程一個理念是面向接口編程,如果要想實現(xiàn)方法,就創(chuàng)建該接口的實現(xiàn)類?。。?/strong>
在這里我們創(chuàng)建service接口,并創(chuàng)建實現(xiàn)類用以實現(xiàn)接口方法。
UserService:
package com.bipt.service;
import com.bipt.pojo.User;
/**
* @author 不止于夢想
* @date 2022/10/3 20:04
*/
public interface UserService {
/**
* 登錄方法
*/
User login(String username,String password);
/**
* 注冊方法
*/
int register(String username,String password);
}implUserService:
package com.bipt.service.implService;
import com.bipt.mapper.UserMapper;
import com.bipt.pojo.User;
import com.bipt.service.UserService;
import com.bipt.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
/**
* @author 不止于夢想
* @date 2022/10/3 20:16
*/
public class ImplUserService implements UserService {
SqlSessionFactory sessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
@Override
public User login(String username,String password) {
SqlSession session =sessionFactory .openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.select(username, password);
return user;
}
@Override
public int register(String username,String password) {
SqlSession session =sessionFactory .openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int flag = mapper.addUser(username,password);
return flag;
}
}controller層
現(xiàn)在在controller層還是一些servlet實現(xiàn)對各種操作的控制
執(zhí)行登錄控制的loginServlet:
```package com.bipt.controller;
import com.bipt.pojo.User;
import com.bipt.service.implService.ImplUserService;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
/**
* 用戶登錄的servlet
* @author 不止于夢想
* @date 2022/10/3 18:26
*/
//@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
private ImplUserService implUserService = new ImplUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取用戶名信息
String username = req.getParameter("username");
//獲取密碼
String password = req.getParameter("password");
//獲取記住狀態(tài)
String remember = req.getParameter("remember");
//獲取訪問的項目路徑
String contextPath = req.getContextPath();
//查詢客戶是否存在
User user = implUserService.login(username,password);
System.out.println(user.getName());
System.out.println(user.getPassword());
//判斷用戶是否為真
if(user != null){
//判斷用戶是否勾選了記住我選項
if("1".equals(remember)){
//為真,則創(chuàng)建cookie
Cookie cookie1 = new Cookie("username",username);
Cookie cookie2 = new Cookie("password",password);
//設(shè)置cookie的存活時長,設(shè)置為兩天半
//cookie中無法設(shè)置double數(shù)據(jù),那么兩天半等于多少秒呢--21600秒,我們直接設(shè)置秒數(shù)
// cookie1.setMaxAge(60*60*24*2.5);這樣是不行的
cookie1.setMaxAge(21600);
cookie2.setMaxAge(21600);
//綁定路徑--任意路徑訪問均可
cookie1.setPath("/");
cookie2.setPath("/");
//發(fā)送cookie到客戶端
resp.addCookie(cookie1);
resp.addCookie(cookie2);
}
//把對象存儲到session域中,便于過濾器使用
HttpSession session = req.getSession();
session.setAttribute("user",user);
//表示成功,跳轉(zhuǎn)到歡迎頁面
resp.sendRedirect(""+contextPath+"/index.html");
}else{
req.getRequestDispatcher(""+contextPath+"/login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
***執(zhí)行注冊控制的loginServlet:***
```java
package com.bipt.controller;
import com.bipt.service.implService.ImplUserService;
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.Writer;
/**
* @author 不止于夢想
* @date 2022/10/5 13:42
*/
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
private ImplUserService implUserService = new ImplUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//獲取數(shù)據(jù)
String username = req.getParameter("username");
String password = req.getParameter("password");
//獲取訪問的項目路徑
String contextPath = req.getContextPath();
//添加用戶,返回1表示添加成功,返回登錄界面,返回0表示失敗,返回注冊界面
int flag = implUserService.register(username,password);
if("1".equals(flag)){
resp.sendRedirect(contextPath+"/login.jsp");
}else{
resp.sendRedirect(contextPath+"/register.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}為了防止在我們沒有登錄的情況下,就訪問了其他資源,我創(chuàng)建了一個utils工具包,配置了一個過濾器
package com.bipt.utils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @author 不止于夢想
* @date 2022/10/5 22:03
*/
@WebFilter(filterName = "loginFilter",urlPatterns = "*.html")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
HttpSession session = httpServletRequest.getSession();
// String uri = ((HttpServletRequest) req).getRequestURI();
// int startPos = uri.lastIndexOf(".");
// String result = uri.substring(startPos);
Object user = session.getAttribute("user");
if(user==null){
httpServletRequest.getRequestDispatcher(
httpServletRequest.getContextPath()+"/login.jsp").forward(req,resp);
return;
} else filterChain.doFilter(req,resp);//否則則繼續(xù)執(zhí)行
}
}
配置filter過濾器之后,設(shè)置一個checkloginServlet,對用戶是否登錄進行查證,已經(jīng)登錄則放行,沒有登錄則跳轉(zhuǎn)登錄界面。
package com.bipt.controller;
import com.bipt.pojo.User;
import com.bipt.service.implService.ImplUserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
*
* 實現(xiàn)登錄檢查
* @author 不止于夢想
* @date 2022/10/5 19:37
*/
@WebServlet("/logCheckServlet")
public class LogCheckServlet extends HttpServlet {
private ImplUserService implUserService = new ImplUserService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username=null;
String password=null;
Cookie[] cookies = req.getCookies();
for (Cookie cookie:cookies) {
if("username".equals(cookie.getName())){
username = cookie.getValue();
}else if("password".equals(cookie.getName())){
password = cookie.getValue();
}
}
/**
* 判斷username和password的值是否為空,如果不為空,則查詢數(shù)據(jù)庫,查到則轉(zhuǎn)發(fā)到歡迎界面
*/
if(username != null &&password != null){
//調(diào)用查詢語句
User user = implUserService.login(username,password);
if(user!=null){
resp.sendRedirect(req.getContextPath()+"index.html");
}
else {
resp.sendRedirect(req.getContextPath()+"/login.jsp");
}
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
到此這篇關(guān)于cookie+mybatis+servlet實現(xiàn)免登錄時長兩天半的文章就介紹到這了,更多相關(guān)mybatis免登錄時長內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java使用IOC控制反轉(zhuǎn)的三種設(shè)計模式詳解
這篇文章主要為大家詳細介紹了Java使用IOC控制反轉(zhuǎn)的三種設(shè)計模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
SpringMVC實現(xiàn)Controller的三種方式總結(jié)
這篇文章主要介紹了SpringMVC實現(xiàn)Controller的三種方式總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
JAVA利用HttpClient進行POST請求(HTTPS)實例
下面小編就為大家?guī)硪黄狫AVA利用HttpClient進行POST請求(HTTPS)實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起 小編過來看看吧2016-11-11
SpringBoot使用ShardingSphere-Proxy的實現(xiàn)示例
ShardingSphere-Proxy是一個獨立的數(shù)據(jù)庫代理層,可以與SpringBoot集成,本文介紹了SpringBoot使用ShardingSphere-Proxy的實現(xiàn)示例,具有一定的參考價值,感興趣的可以了解一下2025-02-02
解決springboot項目上傳文件出現(xiàn)臨時文件目錄為空的問題
這篇文章主要介紹了解決springboot項目上傳文件出現(xiàn)臨時文件目錄為空的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
使Java的JButton文字隱藏功能的實現(xiàn)(不隱藏按鈕的前提)
這篇文章主要介紹了使Java的JButton文字隱藏功能的實現(xiàn)(不隱藏按鈕的前提),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01
Windows10系統(tǒng)下JDK1.8的下載安裝及環(huán)境變量配置的教程
這篇文章主要介紹了Windows10系統(tǒng)下JDK1.8的下載安裝及環(huán)境變量配置的教程,本文圖文并茂給大家介紹的非常詳細,對大家的工作或?qū)W習(xí)具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
spring boot 實現(xiàn)配置多個DispatcherServlet最簡單方式
這篇文章主要介紹了spring boot 實現(xiàn)配置多個DispatcherServlet最簡單方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01

