需求:
1 实现用springMVC 开发API 接口
2 服务端实现白名单功能,也就是写一个过滤器只允许白名单配置的机器才能访问这个API接口
3 post 请求实现
4 服务端接收json格式的数据请求,并返回 json格式数据结果集
5 客户端实现调用服务端接口
6 这是一个maven 项目
详解:
一 ,pom.xml
4.0.0
ezrWeb
ezr-web-addBrand
war
1.0-SNAPSHOT
ezr-web-addBrand Maven Webapp
http://maven.apache.org
junit
junit
3.8.1
test
javaee
javaee-api
5
org.springframework
spring-core
4.2.2.RELEASE
org.springframework
spring-beans
4.2.2.RELEASE
org.springframework
spring-context
4.2.2.RELEASE
org.springframework
spring-tx
4.1.9.RELEASE
org.springframework
spring-aspects
4.2.1.RELEASE
org.springframework
spring-context-support
4.1.9.RELEASE
org.springframework
spring-jdbc
4.3.2.RELEASE
org.springframework
spring-test
4.1.9.RELEASE
org.springframework
spring-webmvc
4.1.9.RELEASE
org.mybatis
mybatis
3.2.2
org.mybatis
mybatis-spring
1.3.0
org.javassist
javassist
3.17.1-GA
cglib
cglib
2.2.2
mysql
mysql-connector-java
5.1.27
commons-dbcp
commons-dbcp
1.4
javax.servlet
jstl
1.2
javax.servlet
servlet-api
2.5
provided
javax.servlet.jsp
jsp-api
2.2
provided
commons-fileupload
commons-fileupload
1.3.3
org.aspectj
aspectjrt
1.8.8
org.aspectj
aspectjweaver
1.8.8
commons-pool
commons-pool
1.6
commons-io
commons-io
2.1
com.fasterxml.jackson.core
jackson-databind
2.7.4
com.fasterxml.jackson.core
jackson-core
2.7.4
com.fasterxml.jackson.core
jackson-annotations
2.7.4
org.json
json
20180813
com.alibaba
fastjson
1.2.28
org.apache.httpcomponents
httpclient
4.5.6
ezr-web-addBrand
org.apache.maven.plugins
maven-compiler-plugin
1.6
src/main/resources
**/*.properties
**/*.xml
true
src/main/java
**/*.properties
**/*.xml
true
二,web.xml
EzrWebAddBrand
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
FilterIP
ezr.bd.filter.FilterIP
FilteredIP
192.168.XX.xx,192.168.xx.xxx
FilterIP
/*
org.springframework.web.context.ContextLoaderListener
contextConfigLocation
classpath:spring-*.xml
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
SpringMVC
*.do
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
characterEncodingFilter
/*
三,过滤器:
package ezr.bd.filter;
import javax.servlet.*;
import java.io.IOException;
/**
* Created by liucf on 2019/3/7.
* 这是一个针对IP进行过滤的自定义过滤器
* 只允许在web.xml 中配置了的IP允许访问接口
*/
public class FilterIP implements Filter{
protected String fip = ""; //要过滤的IP
protected FilterConfig fcon = null;//过滤器配置对象
/**
* 初始化
* @param config
* @throws ServletException
*/
@Override
public void init(FilterConfig config) throws ServletException {
System.out.println("FilterIP 过滤器初始化");
this.fcon = config;
fip = fcon.getInitParameter("FilteredIP");//和web.xml 的 filter
if (fip == null) {
fip = "";
}
System.out.println("要过滤的IP地址为:" + fip);
}
/**
* 过滤方法
* 只允许在web.xml 中配置了的IP允许访问接口,否则不能访问。
* @param request 请求对象
* @param response 相应对象
* @param chain 过滤对象
* @throws IOException
* @throws ServletException
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("FilterIP 过滤器执行过滤方法");
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
// 得到请求的IP地址 和要过滤的Ip地址进行对比
String ip = request.getRemoteAddr();
System.out.println("fip: "+fip);
System.out.println("ip: "+ip);
if (fip.contains(ip)) {
// 发现配置中允许的ip
chain.doFilter(request, response);
} else{
// 未在web.xml中配置的ip
String path = "error.do";
RequestDispatcher desc = request.getRequestDispatcher(path);
desc.forward(request, response);
}
}
@Override
public void destroy() {
System.out.println("FilterIP 过滤器销毁");
this.fcon = null;
}
}
服务端 只接受 post 请求 和 json参数的API 接口
package ezr.bd.controller;
import com.alibaba.fastjson.JSON;
import ezr.bd.biz.OptBdMonitorShardGrpCompletedBiz;
import ezr.bd.model.CompletedShardGrp;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Created by liucf on 2019/3/11.
*/
@Controller
@RequestMapping("getCompletedShardGrp.do")
public class OptBdMonitorShardGrpCompletedController {
@Autowired
private OptBdMonitorShardGrpCompletedBiz optBdMonitorShardGrpCompletedImpl;
@RequestMapping(params = "listTest",produces = "application/json",method = RequestMethod.POST)
@ResponseBody
public Map getCompletedShardGrpTest(HttpServletRequest request, HttpServletResponse response)throws Exception {
Map responseMap = new HashMap();//用来存接口返回信息
try{
String data= IOUtils.toString(request.getInputStream());//获取传入的json
Map requsetMap = new HashMap();//用来保存接口请求信息
System.out.println("传来的Json是:" + data);
requsetMap = JSON.parseObject(data);//把json转成map
System.out.println("打印requsetMap:"+requsetMap.toString());
String lastCheckTime = requsetMap.get("lastCheckTime").toString();
System.out.println("打印requsetMap lastCheckTime:"+lastCheckTime);
ArrayList list = optBdMonitorShardGrpCompletedImpl.selectCompletedShardGrp();
if (null != list && !list.isEmpty()){
responseMap.put("data", list);
}
//一般做接口开发,都会用到下面两个,一个是code代表你的接口状态,第二是msg,代表接口的情况
responseMap.put("code", "0");//状态码
responseMap.put("msg", "请求成功");//信息描述
}catch (Exception e){
}
return responseMap;
}
@RequestMapping(params = "list",produces = "application/json",method = RequestMethod.POST)
@ResponseBody
public Map getCompletedShardGrp(HttpServletRequest request, HttpServletResponse response)throws Exception {
Map responseMap = new HashMap();//用来存接口返回信息
try{
String data= IOUtils.toString(request.getInputStream());//获取传入的json
Map requsetMap = new HashMap();//用来保存接口请求信息
System.out.println("传来的Json是:" + data);
requsetMap = JSON.parseObject(data);//把json转成map
System.out.println("打印requsetMap:"+requsetMap.toString());
String lastCheckTime = requsetMap.get("lastCheckTime").toString();
System.out.println("打印requsetMap lastCheckTime:"+lastCheckTime);
ArrayList list = optBdMonitorShardGrpCompletedImpl.getCompletedShardGrp(lastCheckTime);
if (null != list && !list.isEmpty()){
responseMap.put("data", list);
}
//一般做接口开发,都会用到下面两个,一个是code代表你的接口状态,第二是msg,代表接口的情况
responseMap.put("code", "0");//状态码
responseMap.put("msg", "请求成功,数据正常");//信息描述
}catch (Exception e){
responseMap.put("data", "");
responseMap.put("code", "1");//状态码
responseMap.put("msg", "请求失败,无数据返回");//信息描述
e.printStackTrace();
}
return responseMap;
}
}
四,客户端请求实例
package ezr.bd.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
@SuppressWarnings("deprecation")
public class HttpClientTest{
/**
* post提交调用方法
* 亲测过
* @param jsonParams post 请求的json 字符串
* @param apiUrl post 请求的 apiUrl
* @return return 回去一个 json 字符串
* @throws UnsupportedEncodingException 抛出异常类型:不支持字符编码
*/
public static String callRemotePostApi(String jsonParams,String apiUrl) throws UnsupportedEncodingException{
System.out.println(jsonParams);
/**创建httpClient实例对象*/
CloseableHttpClient httpClient = HttpClients.createDefault();
/**创建httpPost实例对象*/
HttpPost httpPost = new HttpPost(apiUrl);
httpPost.setEntity(new StringEntity(jsonParams, Charset.forName("utf-8")));
BufferedReader reader = null;
StringBuffer sb = new StringBuffer();
try {
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println(statusCode);
if(statusCode==200){//请求和响应都成功了
/**
* 调用HttpResponse的getEntity()方法可获取HttpEntity对象,
* 该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
*/
HttpEntity entity = response.getEntity();
reader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
String buffer = "";
while ((buffer=reader.readLine())!=null){
sb.append(buffer);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(reader != null){
reader.close();
}
httpPost.releaseConnection();
/**关闭此连接管理器并释放分配的资源*/
httpClient.getConnectionManager().shutdown();
/**无条件地关闭httpClient。关闭基础连接管理器并释放资源*/
HttpClientUtils.closeQuietly(httpClient);
} catch (IOException e){
e.printStackTrace();
}
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
String jsonParams = "{\"lastCheckTime\":\"2019-03-07 21:15:14\"}";
String apiUrl = "http://192.168.XX.XX:8080/getCompletedShardGrp.do?list";
String str = callRemotePostApi(jsonParams,apiUrl);
System.out.println(str);
}
}
五,postman测试:
六,后端客户端测试:
{"lastCheckTime":"2019-03-07 21:15:14"}
200
{"msg":"请求成功,数据正常","code":"0","data":[{"id":"20190307-1","shardingGrpId":"1","lastModifyDate":"2019-03-07 21:15:14.0"},{"id":"20190311-12","shardingGrpId":"1212","lastModifyDate":"2019-03-11 18:05:09.0"},{"id":"20190311-13","shardingGrpId":"1313","lastModifyDate":"2019-03-11 18:06:31.0"}]}
Process finished with exit code 0
七可能遇导的问题
如果不引用如下依赖
com.fasterxml.jackson.core
jackson-databind
2.7.4
com.fasterxml.jackson.core
jackson-core
2.7.4
com.fasterxml.jackson.core
jackson-annotations
2.7.4
org.json
json
20180813
com.alibaba
fastjson
1.2.28
可以会遇到异常:json
Unexpected '<'
也就是html:
Apache Tomcat/7.0.72 - Error report
HTTP Status 406 -
type Status report
message
description
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
Apache Tomcat/7.0.72
The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers
这句话可以 知道 缺少jar导致的
SpringMVC中当在浏览器中输入对应的MappingUrl时,报The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
错误的意思是:说是指定的资源已经找到,但它的MIME类型和客户在Accpet头中所指定的不兼容
@ResponseBody返回json格式的数据,而浏览器接受的是text/html;charset=UTF-8文本类型