springboot基本使用八(mbatisplus+filter实现登录功能)

news/2024/4/25 20:18:19

mybatisplus依赖:

<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.2</version>
</dependency>

mysql依赖:

<dependency><groupId>com.mysql</groupId><artifactId>mysql-connector-j</artifactId><scope>runtime</scope>
</dependency>

 lombox依赖:

<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional>
</dependency>

数据库表数据:


SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (`id` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '唯一标识',`nickname` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '用户名称'
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('843232', '李哪吒');
INSERT INTO `user` VALUES ('994343', '杨戬');SET FOREIGN_KEY_CHECKS = 1;

前端:

    html:

<div class="whole"><ul class="user_login"><li><label>id:</label><input type="text" name="id"  /></li><li><label>姓名:</label><input type="text" name="nickname" class="name" /><span          class="prompt_mes"></span></li><li><span class="bnt_login">登录</span></li></ul></div>

    css:

 <style>*{margin: 0;padding: 0;}ul{list-style: none;}.whole{margin: 0 auto;height: 200px;width: 500px;border: 1px solid #000000;}.user_login li{height: 50px;margin: 10px 0;position: relative;}label{display: inline-block;width: 180px;text-align: right;}input{height: 30px;outline: none;padding-left: 5px;}.prompt_mes{position: absolute;top: 5px;left: 360px;font-size: 14px;color: red;}.bnt_login{background: red;position: absolute;left: 50%;transform: translateX(-50%);bottom: 0;padding: 10px 20px;color: white;cursor: pointer;border-radius: 5px;}</style>

      js:

<script>$(function () {$(".bnt_login").on("click",function () {var name = $(".name").val();if(name.trim() == ""){$(".name").siblings(".prompt_mes").html("用户名不能为空");return;}$.ajax({url:"/user/login",type:"GET",data:{"nickname":$(".name").val().trim()},success:function (data) {window.location.href="/success.html";},error:function (error) {$(".name").siblings(".prompt_mes").html(error.responseText.replace(/"/g, ''));}})});});</script>

       整体前端代码:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登录</title><script type="application/javascript" src="js/jquery.js"></script><style>*{margin: 0;padding: 0;}ul{list-style: none;}.whole{margin: 0 auto;height: 200px;width: 500px;border: 1px solid #000000;}.user_login li{height: 50px;margin: 10px 0;position: relative;}label{display: inline-block;width: 180px;text-align: right;}input{height: 30px;outline: none;padding-left: 5px;}.prompt_mes{position: absolute;top: 5px;left: 360px;font-size: 14px;color: red;}.bnt_login{background: red;position: absolute;left: 50%;transform: translateX(-50%);bottom: 0;padding: 10px 20px;color: white;cursor: pointer;border-radius: 5px;}</style><script>$(function () {$(".bnt_login").on("click",function () {var name = $(".name").val();if(name.trim() == ""){$(".name").siblings(".prompt_mes").html("用户名不能为空");return;}$.ajax({url:"/user/login",type:"GET",data:{"nickname":$(".name").val().trim()},success:function (data) {window.location.href="/success.html";},error:function (error) {$(".name").siblings(".prompt_mes").html(error.responseText.replace(/"/g, ''));}})});});</script>
</head>
<body><div class="whole"><ul class="user_login"><li><label>id:</label><input type="text" name="id"  /></li><li><label>姓名:</label><input type="text" name="nickname" class="name" /><span class="prompt_mes"></span></li><li><span class="bnt_login">登录</span></li></ul></div>
</body>
</html>

后端:

       启动类:

@SpringBootApplication
@ServletComponentScan
public class HellordApplication {public static void main(String[] args) {SpringApplication.run(HellordApplication.class, args);}}

      注意:一定要加上@ServletComponentScan注解,通过这个注解扫描filter,不然filter不生效

实体类:

@Data
public class User {private String id;private String nickname;
}

     mapper层:

@Mapper
public interface UserMapper extends BaseMapper<User> {
}

       service层:

public interface UserService extends IService<User> {
}

      service层实现类:

@Service
public class UserServiceImple extends ServiceImpl<UserMapper, User> implements UserService {
}

     controller层:

@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/login")public String login(String nickname, HttpServletRequest request, HttpServletResponse response){LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>();lambdaQueryWrapper.eq(nickname != null,User::getNickname,nickname);User user = userService.getOne(lambdaQueryWrapper);//System.err.println(user);if(user == null){response.setStatus(400);return "用户名不正确";}request.getSession().setAttribute("id",user.getId());return "成功";}
}

      处理中午乱码:

@Configuration
public class WebReourcesConfig extends WebMvcConfigurationSupport {/*** 设置静态资源映射* @param registry*/@Overrideprotected void addResourceHandlers(ResourceHandlerRegistry registry){// 访问地址为http://localhost:端口/123/静态资源名称// registry.addResourceHandler("/123/**").addResourceLocations("classPath:/123/");// 访问地址为http://localhost:端口/静态资源名称registry.addResourceHandler("/**").addResourceLocations("classPath:/");}/*** 处理中文乱码问题* @param converters*/@Overrideprotected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {//创建消息转换器对象MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();//设置对象转换器,底层使用Jackson将Java对象转为jsonmessageConverter.setObjectMapper(new JacksonObjectMapper());//将上面的消息转换器对象追加到mvc框架的转换器集合中converters.add(0,messageConverter);}}
public class JacksonObjectMapper extends ObjectMapper {public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";public JacksonObjectMapper() {super();//收到未知属性时不报异常this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);//反序列化时,属性不存在的兼容处理this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);SimpleModule simpleModule = new SimpleModule().addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))).addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT))).addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT))).addSerializer(BigInteger.class, ToStringSerializer.instance).addSerializer(Long.class, ToStringSerializer.instance).addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))).addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT))).addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));//注册功能模块 例如,可以添加自定义序列化器和反序列化器this.registerModule(simpleModule);}
}

      filter:

@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) servletRequest;HttpServletResponse response = (HttpServletResponse) servletResponse;// 获取本次请求的地址String requestURI = request.getRequestURI();Object id = request.getSession().getAttribute("id");// 放行路径String[] urls = new String[]{"/user/**","/login.html"};boolean flag = check(urls,requestURI);if(flag){filterChain.doFilter(request,response);return;}if(id != null){ // 表示已经登陆过filterChain.doFilter(request,response);return;}response.sendRedirect("/login.html");}/*** 路径匹配,检查本次请求是否需要放行* @param urls* @param requestURI* @return*/public boolean check(String[] urls,String requestURI){for (String url : urls) {boolean match = PATH_MATCHER.match(url, requestURI);if (match) {return true;}}return false;}
}

https://www.xjx100.cn/news/3366547.html

相关文章

147.【2024Java八股-全网最全-10w字】

100道Java经典面试题 (一)、准备篇1.HR如何筛选简历?2.部门负责人如何筛选简历?3.简历模块布局4.应届生如何找到合适的练手项目?5.深入学习哪些业务模块呢?6.Java程序员的面试过程 (二)、Redis篇1.redis经常使用在哪些场景?2.Redis进行查询的流程是什么?3.什么是缓存穿透…

【Servlet】thymeleaf快速入门

文章目录 一、thymeleaf介绍二、入门案例 一、thymeleaf介绍 Thymeleaf&#xff1a;视图模板技术 在index.html页面上加载java内存中的fruitList数据&#xff0c;这个过程我们称之为渲染&#xff08;render&#xff09;。 thymeleaf是用来帮助我们做视图渲染的一个技术。 二…

C语言 | Leetcode C语言题解之第6题Z字形变换

题目&#xff1a; 题解&#xff1a; char * convert(char * s, int numRows){int n strlen(s), r numRows;if (r 1 || r > n) {return s;}int t r * 2 - 2;char * ans (char *)malloc(sizeof(char) * (n 1));int pos 0;for (int i 0; i < r; i) { // 枚举矩阵的…

数据分析之POWER BI Desktop可视化应用案列

在power bi中导入数据 导入前期建好的模型 简单介绍&#xff08;power bi desktop&#xff09; 将右边字段全部展开 各类数据 所作的模型 在excel中是单向的&#xff0c;power bi 中可以是双向的 右键单击----点击属性 选择两个---在两个方向上应用安全筛选器 变为双向的…

MySQL-linux安装-万能RPM法

一、MySQL的Linux版安装 1、 CentOS7下检查MySQL依赖 1. 检查/tmp临时目录权限&#xff08;必不可少&#xff09; 由于mysql安装过程中&#xff0c;会通过mysql用户在/tmp目录下新建tmp_db文件&#xff0c;所以请给/tmp较大的权限。执行 &#xff1a; chmod -R 777 /tmp2. …

css设置文字铺满盒子

<div>收货人</div>&#xff1a; <div>电话</div>&#xff1a; <div>省市区</div>&#xff1a; width: 100rpx;border: 1px solid rebeccapurple;display: inline-block;text-align-last: justify;

【ARM 嵌入式 C 文件操作系列 20 -- 文件删除函数 remove 详细介绍】

请阅读【嵌入式开发学习必备专栏 】 文章目录 文件删除函数 remove 文件删除函数 remove 在 C 语言中&#xff0c; 可以使用 remove 函数来删除一个文件&#xff0c;但在删除之前 可能想确认该文件是否存在。 可以使用 stat 函数来检查文件是否存在。 以下是如何实现这个功能…

Redis分布式锁的优化

分布式锁 分布式锁&#xff1a;满足分布式系统或集群模式下多进程可见并且互斥的锁。 分布式锁的实现 分布式锁的核心是实现多进程之间互斥&#xff0c;而满足这一点的方式有很多&#xff0c;常见的有三种&#xff1a; MySQLRedisZookeeper互斥利用mysql本身的互斥锁机制利…