spring 4.1.6 中通过继承RequestMappingHandlerMapping 实现自定义url访问

新建web项目sp,使用的是spring 4.1.6,实现通过controller类名中除controller之外的字符串和方法名作为访问路径的方式:

例如:TestController 中有方法 public String uuid(){}

方法路径为:http://localhost/sp/service/test@uuid

=======================================================================================

web.xml文件内容如下:

    <!-- 配置spring的mvc -->
    <servlet>
        <servlet-name>controller</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>controller</servlet-name>
        <url-pattern>/service/*</url-pattern>
    </servlet-mapping>


spring-servlet.xml中相关代码如下:

    <bean
        class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
        p:ignoreDefaultModelOnRedirect="true">
        <property name="messageConverters">
            <list>
                <bean
                    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
            </list>
        </property>
    </bean>
    <bean name="handlerMapping" class="cn.ddx.util.MyRequestMappingHandlerMapping">
    </bean>




cn.ddx.util.MyRequestMappingHandlerMapping中代码如下:
package cn.ddx.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition;
import org.springframework.web.servlet.mvc.condition.HeadersRequestCondition;
import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.ProducesRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@RequestMapping
public class MyRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    private boolean useSuffixPatternMatch = true;

    private boolean useTrailingSlashMatch = true;

    private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

    private final List<String> fileExtensions = new ArrayList<String>();
    
    private static RequestMapping requestMapping = (RequestMapping) MyRequestMappingHandlerMapping.class
            .getAnnotation(RequestMapping.class);


    @Override
    protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
        RequestMappingInfo info = null;
        if (requestMapping != null) {
            RequestCondition<?> methodCondition = getCustomMethodCondition(method);
            info = createRequestMappingInfo(requestMapping, methodCondition, method);
            RequestMapping typeAnnotation = AnnotationUtils.findAnnotation(handlerType, RequestMapping.class);
            if (typeAnnotation != null) {
                RequestCondition<?> typeCondition = getCustomTypeCondition(handlerType);
                info = createRequestMappingInfo(typeAnnotation, typeCondition, method).combine(info);
            }
        }
        return info;
    }

    protected RequestMappingInfo createRequestMappingInfo(RequestMapping annotation,
            RequestCondition<?> customCondition, Method method) {
        String className = method.getDeclaringClass().getSimpleName();
        String classNameExceptAction = StringUtils.uncapitalize(className.substring(0, className.length() - 10));
        String[] patterns = resolveEmbeddedValuesInPatterns(annotation.value());
        if ((patterns != null)&& (patterns.length == 0)) {//
            patterns = new String[] { classNameExceptAction + "!" + method.getName() };
        }
        System.out.println(patterns[0]);

    
        return new RequestMappingInfo(
                new PatternsRequestCondition(patterns, getUrlPathHelper(), getPathMatcher(), this.useSuffixPatternMatch,
                        this.useTrailingSlashMatch, this.fileExtensions),
                new RequestMethodsRequestCondition(annotation.method()),
                new ParamsRequestCondition(annotation.params()), new HeadersRequestCondition(annotation.headers()),
                new ConsumesRequestCondition(annotation.consumes(), annotation.headers()), new ProducesRequestCondition(
                        annotation.produces(), annotation.headers(), this.contentNegotiationManager),
                customCondition);
    }

}



测试类TestController.java内容如下:

package cn.ddx.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@RestController
public class TestController {

    public ModelAndView uuid(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "UUID:" + UUID.randomUUID());
        mv.setViewName("/test");
        return mv;
    }

    public ModelAndView random(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "RandomUtils:" + RandomUtils.nextInt(1000, 9999));
        mv.setViewName("/test");
        return mv;
    }
}

页面test内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${msg}
</body>
</html>



启动tomcat之后,控制台显示信息如下:

test@random
test@uuid


访问路径如下:

http://localhost/sp/service/test@uuid

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值