Yat*_*oel 6 spring spring-mvc http-request-parameters
我的Spring MVC Web应用程序中有很多控制器,并且有一个参数mandatoryParam可以说它必须存在于Web应用程序的所有请求中.
现在我想让我的web层和服务层中的所有方法都可以使用该param值.如何有效地处理这种情况?
目前我正在以这种方式处理它:
@ControllerAdvice("net.myproject.mypackage")
public class MyControllerAdvice {
    @ModelAttribute
    public void myMethod(@RequestParam String mandatoryParam) {
        // Use your mandatoryParam
    }
}
myMethod()将为net.myproject.mypackage包中任何控制器的每个请求调用.(在Spring 4.0之前,您无法定义一个包.@ControllerAdvice应用于所有控制器).
有关方法的更多详细信息,请参见Spring Reference@ModelAttribute.
感谢阿列克谢带路。
他的解决方案是:
我想添加一个警告和一个更完整的示例:
警告:如果没有为 @ModelAttribute 注释提供名称,请参阅 ModelAttribute.name() 的 JavaDoc(最好不要使代码混乱):
默认模型属性名称是根据非限定类名称从声明的属性类型(即方法参数类型或方法返回类型)推断出来的:例如,类“mypackage.OrderAddress”的“orderAddress”,或类“orderAddressList”的“orderAddressList” “列表<mypackage.OrderAddress>”。
完整的例子:
@ControllerAdvice
public class ParentInjector {
    @ModelAttribute
    public void injectParent(@PathVariable long parentId, Model model) {
        model.addAttribute("parentDTO", new ParentDTO(parentId, "A faked parent"));
    }
}
@RestController
@RequestMapping("/api/parents/{parentId:[0-9]+}/childs")
public class ChildResource {
    @GetMapping("/{childId:[0-9]+}")
    public ChildDTO getOne(@ModelAttribute ParentDTO parent, long childId) {
        return new ChildDTO(parent, childId, "A faked child");
    }
}
要继续关于警告,请求声明参数“@ModelAttribute ParentDTO Parent”:模型属性的名称不是变量名称(“parent”),也不是原始的“parentId”,而是首字母降低的类名: “parentDTO”,所以我们必须小心使用 model.addAttribute("parentDTO"...)
编辑:一个更简单、更不易出错且更完整的示例:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@RestController
public @interface ProjectDependantRestController {
    /**
     * The value may indicate a suggestion for a logical component name,
     * to be turned into a Spring bean in case of an autodetected component.
     *
     * @return the suggested component name, if any
     */
    String value() default "";
}
@ControllerAdvice(annotations = ParentDependantRestController.class)
public class ParentInjector {
    @ModelAttribute
    public ParentDTO injectParent(@PathVariable long parentId) {
        return new ParentDTO(parentId, "A faked parent");
    }
}
@ParentDependantRestController
@RequestMapping("/api/parents/{parentId:[0-9]+}/childs")
public class ChildResource {
    @GetMapping("/{childId:[0-9]+}")
    public ChildDTO getOne(@ModelAttribute ParentDTO parent, long childId) {
        return new ChildDTO(parent, childId, "A faked child");
    }
}
| 归档时间: | 
 | 
| 查看次数: | 2840 次 | 
| 最近记录: |