Spring MVC如何定义一个抽象控制器呢?
下文笔者讲述Spring MVC中定义抽象控制器的方法分享,如下所示
抽象控制器的功能
抽象控制器的功能: 用于制作一个通用的控制器 抽象控制器上,无需加入Controller注解(此注解放入到实现类上) 具体的实现逻辑,在实现类子类上
抽象控制器
package com.java265.web.controller; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.java265.web.generator.bo.ResultGenerator; public abstract class AbstractResultController { private final Logger logger = LoggerFactory.getLogger(getClass()); abstract ResultGenerator GetResultGenerator(); abstract String GetViewName(); abstract Validator GetValidator(); @RequestMapping(value = "/{q:.+}", method = RequestMethod.GET) final ModelAndView getModelAndView(@PathVariable("q") String q) { logger.debug("getModelAndView : [q] : {}", q); ModelAndView model = new ModelAndView(); Map<String, Object> results = GetResultGenerator().getResultForController(q); model.addObject("data", results); model.setViewName(GetViewName()); logger.debug("getModelAndView : [model] : {}", model); return model; } }具体实现类
package com.java265.web.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.java265.web.generator.bo.ResultGenerator; @Controller @RequestMapping("/test") public class ResultControllerHosting extends AbstractResultController { private static final String VIEW_NAME = "test"; @Autowired @Qualifier("resultGeneratorHosting") ResultGenerator resultGenerator; @Override ResultGenerator GetResultGenerator() { return resultGenerator; } @Override String GetViewName() { return VIEW_NAME; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。