springMVC系列(五)——springMVC拦截器实现接口访问日志

业务需求

记录访问接口的机器信息、ip地址、时间等数据并存储在数据库表中,要求对原代码没有入侵性,机器信息放在请求的中。

1.接口访问日志表mb_accesslog

CREATE TABLE`mb_accesslog`(
 `id` int(11) NOTNULLAUTO_INCREMENT,
 `ip` varchar(20) NOTNULLCOMMENT 'IP',
 `code`varchar(20) NOT NULL COMMENT 'Code',
 `mac` varchar(20) NOTNULLCOMMENT 'Mac',
 `account`varchar(20) NOT NULL COMMENT 'Account',
 `model`varchar(50) DEFAULT NULL COMMENT '机型',
 `accesstime`datetimeNOTNULLCOMMENT '访问时间',
 `resource`varchar(100) NOT NULL COMMENT '访问资源',
 PRIMARYKEY(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1261 DEFAULT CHARSET=utf8;
2.拦截器AccesslogInterceptor,拦截器类必须实现HandlerInterceptorAdapter类,preHandle方法是拦截在访问开始前。

@Component
public classAccesslogInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AccesslogService accesslogService;
 
    public booleanpreHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
           throws Exception {
       Stringip = request.getRemoteAddr();
       Stringcode= (String)request.getAttribute("code");
       Stringmac= (String)request.getAttribute("mac");
       Stringaccount= (String)request.getAttribute("account");
       Dateaccesstime= newDate();
       Stringresource= request.getRequestURI().split("/")[2];
       Accesslogaccesslog= newAccesslog(ip, code, mac, account, null, accesstime, resource);
       accesslogService.insertOne(accesslog);
       return true;
    }
}
3.配置拦截器

     
   
       
       
   
4.编写测试类,通过get访问

@Test
public voidtestPost() throwsIOException {
    Stringurl= "http://localhost:8080/study_ssmvc/bls/test.m3u8";
    Stringparam= "code=1&mac=2&account=12";
    URLrealUrl= newURL(url);
    URLConnectionuc = realUrl.openConnection();
    // 发送POST请求必须设置如下两行
    uc.setDoOutput(true);
    uc.setDoInput(true);
    OutputStreamos = uc.getOutputStream();
    PrintWriterout= newPrintWriter(os);
    out.print(param);
    out.flush();
   // 定义BufferedReader输入流来读取URL的响应
    BufferedReaderin = new BufferedReader(
            new InputStreamReader(uc.getInputStream()));  //这里才开始访问
   String line;
   String result= "";
   while((line= in.readLine()) != null) {
        result += line + "\n";
   }
   System.out.println(result);
}

你可能感兴趣的:(springMVC,springMVC应用解析)