我的HandlerMapping

时间:2016-07-20 06:55:56

标签: java spring spring-mvc

我试图实现自己的HandlerMapping。它注册良好,但是当我尝试处理请求时,它给了我404,甚至没有通过handleRequest()捕获它。这就是它的样子: MyHandlerMapping:

package com.szymon.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;

public class MyHandlerMapping extends AbstractUrlHandlerMapping {

    private List<String> mappings = new ArrayList<String>();

    @Override
    public void initApplicationContext() throws BeansException {
        super.initApplicationContext();
        mappings.add("/test");
        mappings.add("/home");
        mappings.add("/index");
        registerHandlers();
    }

    protected void registerHandlers() {
        mappings.stream().forEach(elem -> {
            registerHandler(elem, "myController");
        });
    }
}

我的控制器:

package com.szymon.config;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

public class MyController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ModelAndView modelAndView = new ModelAndView("bar");
        modelAndView.addObject("test", "test");
        System.out.println("test");
        System.out.println("test");
        System.out.println("test");
        return modelAndView;
    }
}

因为我正在使用Spring Boot:

package com.szymon;

import com.szymon.config.MyController;
import com.szymon.config.MyHandlerMapping;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public MyController myController() {
        return new MyController();
    }

    @Bean
    public MyHandlerMapping myHandlerMapping() {
        return new MyHandlerMapping();
    }
}

知道为什么它不起作用吗?

1 个答案:

答案 0 :(得分:0)

解决方案是在bean定义中调用AbstractHandlerMapping的setOrder方法。