为什么我的百里香标记标记:文字不起作用

时间:2018-01-30 09:07:22

标签: java spring thymeleaf

在admin.html中,我有标记th:text="${name}"。它不显示控制器的值。为什么呢?

Admin.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Admin page</title>
    </head>
    <body>
        Dear <strong><p th:text="${name}"></p></strong>, Welcome to Admin Page.
        <a href="/logout">Logout</a>
    </body>
</html>

控制器

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@ModelAttribute("userForm") User userForm, Model model) {

    try {            
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        model.addAttribute("name",authentication.getName());

        if (securityService.isAdmin(userForm.getUsername())) {
            return "redirect:/admin";
        }
    } catch (RestException e) {
        model.addAttribute("error", "User with username '"+userForm.getUsername()+"' not found");
    }

    return "redirect:/index";
}

我的 MVC配置

@Configuration
@EnableWebMvc
@ComponentScan({ "ru.dev.avtonomki" })
public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Bean
    public ViewResolver htmlViewResolver() {
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(templateEngine(jspTemplateResolver()));
        resolver.setContentType("text/html");
        resolver.setCharacterEncoding("UTF-8");
        resolver.setOrder(1);
        resolver.setViewNames(ArrayUtil.array("*.html"));
        return resolver;
    }

      private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
            SpringTemplateEngine engine = new SpringTemplateEngine();
            engine.addDialect(new LayoutDialect(new GroupingStrategy()));
            engine.addDialect(new Java8TimeDialect());
            engine.setTemplateResolver(templateResolver);
            return engine;
      }

    private ITemplateResolver htmlTemplateResolver() {
        SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
        resolver.setApplicationContext(applicationContext);
        resolver.setPrefix("/WEB-INF/templates/");
        resolver.setCacheable(false);
        resolver.setTemplateMode(TemplateMode.HTML5);
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

1 个答案:

答案 0 :(得分:1)

因为来自你的&#34; / admin&#34;行动你必须传递名字而不是登录。

parent

或者您可以设置RedirectAttributes