Spring Boot 簡單的請求示例(包括請求體驗證)

1.先作個最簡單的Get請求java

新建一個Controller , 並給他添加註解@RestController 它是@Controller和@ResponseBody的組合註解,告訴Spring我是一個Controller,請求過來的時候,記得掃描我數據庫

ok,在給他添加@RequestMapping註解,爲這個Controler指明路徑json

@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...session

2.POST請求的方法app

正常在接口請求過程當中,中間會有個過濾器,過濾全部請求的內容,同時作一些安全方面的校驗ide

過濾器註冊類測試

@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管理ui

過濾器註冊類中,添加過濾器CustomFilterthis

過濾器的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請求

相關文章
相關標籤/搜索