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

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 {
    @Autowired
    private 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
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry){
         // 访问地址为http://localhost:端口/123/静态资源名称
         // registry.addResourceHandler("/123/**").addResourceLocations("classPath:/123/");
         // 访问地址为http://localhost:端口/静态资源名称
         registry.addResourceHandler("/**").addResourceLocations("classPath:/");
    }

    /**
     * 处理中文乱码问题
     * @param converters
     */
    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        //设置对象转换器,底层使用Jackson将Java对象转为json
        messageConverter.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();

    @Override
    public 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;
    }
}
  • 14
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

twx95

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值