Spring Boot,Thymeleaf和@Controller

我正在玩Spring Boot,有一些我不太了解的东西。我的@Controller应用程序中有2

s,第二个不是真正接听REST调用,而是Thymeleaf跳过请求。

基本上我有:

@Configuration

@ComponentScan

@EnableAutoConfiguration

public class Application {

public static void main(String[] args) throws Throwable {

SpringApplication.run(Application.class, args);

}

}

然后

@Configuration

@EnableWebMvcSecurity

@EnableWebSecurity

@EnableGlobalMethodSecurity(prePostEnabled=true)

public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired

Environment env;

@Override

protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()

.antMatchers("/", "/home").permitAll()

.antMatchers("/webjars/**").permitAll()

.antMatchers("/console/**").permitAll()

.antMatchers("/resources/**").permitAll()

.anyRequest().authenticated();

http.formLogin().loginPage("/login").permitAll().and().logout()

.permitAll();

http.csrf().disable(); // for angularjs ease

http.headers().frameOptions().disable(); //for H2 web console

}

}

@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter {

@Override

public void addViewControllers(ViewControllerRegistry registry) {

registry.addViewController("/home").setViewName("home");

registry.addViewController("/").setViewName("home");

registry.addViewController("/hello").setViewName("hello");

registry.addViewController("/login").setViewName("login");

}

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");

registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");

}

}

和两个控制器。这是可行的,因此它正在从一个简单的AngularJS客户端接听我的电话并做出响应:

@Controller

@RequestMapping("/foo")

public class MyController {

@RequestMapping(method = RequestMethod.GET)

@ResponseBody

@PreAuthorize("hasRole('ROLE_FOO')")

public String getFoo() {

return "foooooo";

}

}

这是生病的控制者,没有回应:

@Controller

@RequestMapping("/sick/1")

public class SickController {

@Autowired

SickRepository sickRepository;

@RequestMapping(method = RequestMethod.GET)

public Sick getSickById() {

return sickRepository.findOne(1);

}

}

显然,稍后我将对其进行更改以从URL中提取ID作为路径变量,但是为了进行调试,我回到了硬编码。

在我/sick/1到达之前,日志不会显示任何内容。到那时,我明白了:

org.thymeleaf.exceptions.TemplateInputException: Error resolving template "sick/1", template might not exist or might not be accessible by any of the configured Template Resolvers

at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:245)

at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104)

但是,为什么它去模板引擎而不是我的控制器..?

回答:

您可能缺少控制器方法@ResponseBody上的注释getSickById

您也可以将@Controller注释替换为,@RestController并且Spring将应用于@ResponseBody该控制器内的所有控制器方法。

以上是 Spring Boot,Thymeleaf和@Controller 的全部内容, 来源链接: utcz.com/qa/420577.html

回到顶部