您的位置:首页 > 编程语言 > Java开发

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

2017-05-16 18:43 489 查看
业务需求

记录访问接口的机器信息、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.配置拦截器

<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/bls/*"/><!-- 如果不配置或/*,将拦截所有的Controller -->
<bean class="com.yoostar.support.interceptor.AccesslogInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: