![](/img/trans.png)
[英]Spring Boot & Thymeleaf,passing variables to the controller
[英]Spring Boot, Thymeleaf and @Controller
我正在玩Spring Boot並且有一些我不太了解的東西。 我的應用程序中有2個@Controller
,而第二個並沒有真正接受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)
但為什么它會轉到模板引擎而不是我的控制器..?
您可能在getSickById
控制器方法上缺少@ResponseBody
注釋。
您也可以用@RestController
替換@Controller
注釋,Spring會將@ResponseBody
應用於該控制器中的所有控制器方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.