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;} }