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请求
原文地址:https://www.cnblogs.com/qiyuan880794/p/9829587.html
时间: 2024-10-12 19:19:03