springmvc中获取全部接口信息

  • springmvc中的RequestMappingHandlerMapping类中提供了方法来获取所有接口信息(@controller、@request注解下的方法),难点为RequestMappingHandlerMapping类的获取。
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@Controller
@RequestMapping("url/")

public class UrlController {

	@Autowired
	private RequestMappingHandlerMapping requestMappingHandlerMapping;
	@Autowired
	private HttpServletRequest request;

	
	
	/**
	 * 获取当前项目中的全部接口
	 * */
	@RequestMapping(value = "getAllUrl")
	@ResponseBody
	public String getAllUrl() {
		StringBuilder sb = new StringBuilder();
		sb.append("URL").append("--").append("Class").append("--").append("Function").append('\n');

		Map map = requestMappingHandlerMapping.getHandlerMethods();
		int i=1;
		for (Map.Entry m : map.entrySet()) {
			RequestMappingInfo info = m.getKey();
			HandlerMethod method = m.getValue();
			sb.append(i+":").append(info.getPatternsCondition()).append("--");
			sb.append(method.getMethod().getDeclaringClass()).append("--");
			sb.append(method.getMethod().getName()).append('\n');
			i++;
		}

		System.out.println(sb);
		
		return sb.toString();

	}
	/*
	 * 获取当前访问url
	 * */
	@RequestMapping(value = "getUrl")
	@ResponseBody
	public String getUrl() {
		String url = "";
		String scheme = request.getScheme();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String servletPath = request.getServletPath();
		
		url = scheme +"://" + serverName +":" +serverPort+servletPath;
		if (request.getQueryString() != null){
			url += "?" + request.getQueryString();
		}
		
		System.out.println(url);
		
		return url;
	}
}
  •  

你可能感兴趣的:(web开发)