SpringBoot Controller找不到视图路径

由于版本差异,用SpringBoot 1.4.X以上版本开发时找不到@Controller定义的URL,于是在启动类加注解@ComponentScan("com.controller")即可,括号里表示Controller所在包名。

@SpringBootApplication
@ComponentScan("com.controller")
public class Application {


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

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在 Spring Boot ,你可以使用拦截器(Interceptor)来拦截控制器方法的返回对象,并对其进行处理。拦截器可以在控制器方法执行之后、视图渲染之前对返回对象进行操作。 首先,创建一个实现 HandlerInterceptor 接口的拦截器类,它包含三个方法:preHandle、postHandle 和 afterCompletion。在这些方法,你可以对返回对象进行处理。 ```java @Component public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; // 返回 true 表示继续执行后续的拦截器或控制器方法,返回 false 表示断后续的执行 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 在视图渲染之前对返回对象进行处理 if (modelAndView != null) { modelAndView.addObject("customAttribute", "customValue"); } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // 执行一些清理操作 } } ``` 接下来,在配置类(通常使用 @Configuration 注解标记)注册拦截器。 ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } } ``` 在上述示例,我们创建了一个为 MyInterceptor 的拦截器,并将其应用于所有请求路径上。需要注意的是,我们使用了 @Autowired 注解将拦截器注入到配置类。 当控制器方法执行完毕,但视图渲染之前,拦截器的 postHandle 方法将被调用。在该方法,你可以对返回对象进行处理,例如向 ModelAndView 对象添加自定义属性。 注意:拦截器可以用于修改返回对象,但不能直接修改返回的数据。如果你需要修改响应数据,可以考虑使用过滤器(Filter)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

就这样把你征服

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值