您的位置:首页 > 移动开发

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

2017-05-03 22:30 411 查看
新建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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐