Spring Boot 简单的请求示例(包括请求体验证)
1.先做个最简单的Get请求
新建一个Controller , 并给他添加注解@RestController 它是@Controller和@ResponseBody的组合注解,告诉Spring我是一个Controller,请求过来的时候,记得扫描我
ok,在给他添加@RequestMapping注解,为这个Controler指明路径
@RestController
@RequestMapping("/Demo")
public class DemoController { @ResponseBody
@RequestMapping(value = "/sayHello",method = RequestMethod.GET)
public Map<String,Object> sayHello(){
Map<String,Object> res = new HashMap<String,Object>();
res.put("message", "hello world");
return res;
}
}
写个Get方法,返回一个Map
右击启动类 run...
2.POST请求的方法
正常在接口请求过程中,中间会有个过滤器,过滤所有请求的内容,同时做一些安全方面的校验
过滤器注册类
@Configuration
public class WebConfig { @Bean
@SuppressWarnings({ "unchecked", "rawtypes" })
public FilterRegistrationBean someFilterRegistration1() {
//新建过滤器注册类
FilterRegistrationBean registration = new FilterRegistrationBean();
//添加出事话过滤器
registration.setFilter( new CustomFilter());
// 设置过滤器的URL模式
registration.addUrlPatterns("/*");
return registration;
} }
@Configuration自动配置,由Spring管理
过滤器注册类中,添加过滤器CustomFilter
过滤器的URL模式设置为过滤所有请求
/**
* 初始化过滤器
* @ClassName: CustomFilter
* @author Mr.Chengjq
* @date 2018年10月16日
* @Description: TODO
*/
@WebFilter(filterName = "sessionFilter",urlPatterns = {"/*"})
public class CustomFilter implements Filter { private GeneralConfiguration generalConfiguration; @Override
public void destroy() {
// TODO Auto-generated method stub } @SuppressWarnings("unused")
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession(false);
String uri = request.getRequestURI();
//是否需要过滤
if(!isNeedFilter(uri)){
filterChain.doFilter(request, response);
return;
}
MutableHttpServletRequest requestWrapper = null;
if(request instanceof HttpServletRequest) {
requestWrapper = new MutableHttpServletRequest((HttpServletRequest) request);
}
String body = getRequestbody(requestWrapper);
//验证 start
//验证方式 1.token验证(头部加 token:xxx) 2.秘钥验证(暂定MD5验证 参数 timestamp:xxx key:MD5(xxx+orange))
if(requestWrapper.getHeader("valdateType").equals("1")){
String token = requestWrapper.getHeader("token");
System.out.println("token = "+token);
}else if(requestWrapper.getHeader("valdateType").equals("2")){
String timestamp = requestWrapper.getHeader("timestamp");
String key = requestWrapper.getHeader("key");
//验证
}else{
//返回验证方式失败信息
throw new BaseException("验证失败");
}
//end
requestWrapper.putHeader("userId", "1111");
if(requestWrapper == null) {
filterChain.doFilter(request, response);
} else {
filterChain.doFilter(requestWrapper, response);
} } private String getRequestbody(HttpServletRequest request) {
String param= null;
try {
BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr); JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
param= jsonObject.toJSONString();
} catch (Exception e) {
e.printStackTrace();
}
return param;
} public boolean isNeedFilter(String uri) {
boolean res = true;
String url = generalConfiguration.getUrl();
String[] list = url.split(",");
for(int i = 0 ; i<list.length;i++){
if(uri.indexOf(list[i])!=-1){
res = false;
break;
}
}
return res;
} private class MutableHttpServletRequest extends HttpServletRequestWrapper { private final Map<String, String> customHeaders;
private byte[] body; public MutableHttpServletRequest(HttpServletRequest request) {
super(request);
this.customHeaders = new HashMap<String, String>();
body = getRequestbody(request).getBytes(Charset.forName("UTF-8"));
} public void putHeader(String name, String value) {
this.customHeaders.put(name, value);
} @Override
public String getHeader(String name) {
// check the custom headers first
String headerValue = customHeaders.get(name); if (headerValue != null) {
return headerValue;
}
// else return from into the original wrapped object
return ((HttpServletRequest) getRequest()).getHeader(name); } @Override
public Enumeration<String> getHeaders(String name) { if (customHeaders.containsKey(name)) {
return new Enumeration<String>() {
boolean hasNext = true; @Override
public boolean hasMoreElements() {
return hasNext;
} @Override
public String nextElement() {
hasNext = false;
return customHeaders.get(name);
}
};
}
return super.getHeaders(name);
} @Override
public Enumeration<String> getHeaderNames() {
// create a set of the custom header names
Set<String> set = new HashSet<String>(customHeaders.keySet()); // now add the headers from the wrapped request object
Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
while (e.hasMoreElements()) {
// add the names of the request headers into the list
String n = e.nextElement();
set.add(n);
} // create an enumeration from the set and return
return Collections.enumeration(set);
} @Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
} @Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() { @Override
public int read() throws IOException {
return bais.read();
} @Override
public boolean isFinished() {
// TODO Auto-generated method stub
return false;
} @Override
public boolean isReady() {
// TODO Auto-generated method stub
return false;
} @Override
public void setReadListener(ReadListener readListener) {
// TODO Auto-generated method stub }
};
} } @Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
//初始化bean 获取公共参数配置
ServletContext servletContext = arg0.getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
generalConfiguration = (GeneralConfiguration) ctx.getBean("generalConfiguration");
}
在doFilter方法里具体写过滤的内容以及验证
isNeedFilter方法确认是否要过滤,如果不需要过滤,配置文件里配置不需要过滤的请求名,
/**
* 公共参数配置类
* @ClassName: GeneralConfiguration
* @author Mr.Chengjq
* @date 2018年10月16日
* @Description: TODO
*/
@PropertySource("classpath:conf/generalConfiguration.properties")
@ConfigurationProperties(prefix = "general")
@Configuration
public class GeneralConfiguration { //请求地址
private String url; public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} }
这里添加参数配置类,获取generalConfiguration.properties配置文件,以general开头,当然还可以以@Value的方式
这里就不需要过滤了,直接在配置文件写明不需要处理下面请求的地址,直接进入Controlle方法
general.url = /sayHello,/sayHello2
sayHello2 方法如下,请求数据库的信息
@ResponseBody
@RequestMapping(value = "/sayHello2",method = RequestMethod.POST)
public ResponseMsg sayHello2(@RequestHeader("userId") String userId,@RequestBody RequestMsg requestMsg){
System.out.println(userId);
JSONObject jsonobject = JSONObject.fromObject(requestMsg.getRoot());
System.out.println("jsonobject = "+jsonobject);
//Map<String,Object> res = new HashMap<String,Object>();
PageResult<UserBaseDTO> res = null;
List<UserBaseDTO> list = null;
UserBaseDTO ubt = new UserBaseDTO();
try {
StringBuffer logOut = new StringBuffer();
logOut.append("\n");
logOut.append("cjq2测试");
logOut.append("\n"); LOGGER.debug(logOut.toString());
Pagination page = new Pagination();
page.setPage(1);
page.setRows(10);;
res = iUserbaseService.pageUserBase(ubt, page);
list = res.getList(); } catch (Exception e) {
// TODO: handle exception
throw new BaseException("数据错误");
//LOGGER.error(e.getMessage());
}
return new ResponseMsg(requestMsg.getRoute(), GeneralConstant.SUCCESS, "查询成功", res);
}
在正常开发过程中,对请求参数提和返回参数体会有统一的格式和加密方式,例如上面的的RequestMsg和ResponseMsg
ok 这样就完成了简单的GET和POST请求
Spring Boot 简单的请求示例(包括请求体验证)的更多相关文章
- Spring Boot全局支持CORS(跨源请求)
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet. ...
- 玩转spring boot——简单登录认证
前言 在一个web项目中,某些页面是可以匿名访问的,但有些页面则不能.spring mvc提供了HandlerInterceptor接口来应对,只需要重写preHandle方法便可以实现此功能.那么使 ...
- Spring Boot Ftp Client 客户端示例支持断点续传
本章介绍 Spring Boot 整合 Ftpclient 的示例,支持断点续传 本项目源码下载 1 新建 Spring Boot Maven 示例工程项目 注意:是用来 IDEA 开发工具 File ...
- Spring Boot实现一个监听用户请求的拦截器
项目中需要监听用户具体的请求操作,便通过一个拦截器来监听,并继续相应的日志记录 项目构建与Spring Boot,Spring Boot实现一个拦截器很容易. Spring Boot的核心启动类继承W ...
- Spring Boot使用AOP在控制台打印请求、响应信息
AOP称为面向切面编程,在程序开发中主要用来解决一些系统层面上的问题,比如日志,事务,权限等. AOP简介 AOP全称Aspect Oriented Programming,面向切面,AOP主要实现的 ...
- spring Boot使用AOP统一处理Web请求日志记录
1.使用spring boot实现一个拦截器 1.引入依赖: <dependency> <groupId>org.springframework.boot</grou ...
- spring boot使用AOP统一处理web请求
为了保证服务的高可用,及时发现问题,迅速解决问题,为应用添加log是必不可少的. 但是随着项目的增大,方法增多,每个方法加单独加日志处理会有很多冗余 那在SpringBoot项目中如何统一的处理Web ...
- Spring Boot 2.x 综合示例-整合thymeleaf、mybatis、shiro、logging、cache开发一个文章发布管理系统
一.概述 经过HelloWorld示例(Spring Boot 2.x 快速入门(上)HelloWorld示例)( Spring Boot 2.x 快速入门(下)HelloWorld示例详解)两篇的学 ...
- RabbitMQ(三):RabbitMQ与Spring Boot简单整合
RabbitMQ是目前非常热门的一款消息中间件,不管是互联网大厂还是中小企业都在大量使用.Spring Boot的兴起,极大地简化了Spring的开发,本文将使用Spring Boot与RabbitM ...
随机推荐
- leetcode130
struct POS { int x; int y; POS(int newx, int newy): x(newx), y(newy) {} }; class Solution { public: ...
- angular ng-bind-html
使用ng-bind-html 可以在页面上展示html内容,让html内容加进去后不是一代码形式出现,而是以页面形式展现 需要先引入angular-sanitize.min.js,这个可以在githu ...
- [ilink32 Error] Fatal: Unable to open file 'RM_COMMON.OBJ'
[ilink32 Error] Fatal: Unable to open file 'RM_COMMON.OBJ' [ilink32 Error] Fatal: Unable to open fil ...
- Application HookMainWindow
//H Filebool __fastcall AppHookFunc(TMessage &Message); //cpp file void __fastcall TForm2::FormC ...
- hibernate-list
Hibernate多表关联查询类: 1. sql查询两个或两个以上的字段,默认情况下,list中封装的是Object[],长度与所查询的字段数一致.这种方式获取的数据只能通过index下标获取. su ...
- UI5-文档-4.35-Responsiveness
在这一步中,我们将改进应用程序的响应能力.SAPUI5应用程序可以在手机.平板电脑和桌面设备上运行,我们可以对应用程序进行配置,以便为每个场景充分利用屏幕空间.幸运的是,SAPUI5控件类似于sap. ...
- Object-c 构造、析构函数
一.构造函数 在OC中凡是已init开头的函数我们都称之为构造函数,在声明构造函数的时候,不带参数的一般直接声明为“-(id)init”,带参数的一般声明为“-(id)initWith...”. @i ...
- scala-学习 2
列表操作 List() 或者是 Nil 空list scala> val a = List() a:List[Nothing] = List() print(a.length) a.length ...
- hive sql split 分隔符
Hive字符串分割函数 split(str, regex) - Splits str around occurances that match regexTime taken: 0.769 secon ...
- Autopilot Pattern Redis
https://github.com/autopilotpattern/redis Architecture 正在运行的群集包括以下组件: Redis :我们使用的是Redis 3.2. Redis ...