gpt4 book ai didi

spring-mvc - 在 Spring Boot 应用程序中使用 JSP 和 Thymeleaf View

转载 作者:行者123 更新时间:2023-12-03 14:25:24 25 4
gpt4 key购买 nike

网站和网络上有几个类似的问题,但我一直无法像我尝试的那样在我的示例中使它们起作用。

我是第一次使用 Spring Boot,但我一直在尝试通过 InternalResourceViewResolver 包含 JSP View 。 .我已经让 Thymeleaf View 起作用了。

应用程序.java

@SpringBootApplication
@ComponentScan("controller")
@EnableWebSecurity
@Configuration
public class Application extends WebSecurityConfigurerAdapter {
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}

@Bean
public ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setPrefix("classpath:/templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
resolver.setCacheable(false);
resolver.setOrder(1);
return resolver;
}

//intended for the .jsp view
@Bean
public InternalResourceViewResolver jspResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("classpath:/templates/jsp/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
resolver.setOrder(2);
return resolver;
}

@Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(new UrlTemplateResolver());
templateEngine.addTemplateResolver(templateResolver());

//IKD if/how I should somehow add jspResolver() here

templateEngine.addDialect(new SpringSecurityDialect());
templateEngine.addDialect(new LayoutDialect(new GroupingStrategy()));
templateEngine.addDialect(new Java8TimeDialect());
return templateEngine;
}

@Bean
@Description("Thymeleaf View Resolver")
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setOrder(0);
return viewResolver;
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/users/**").hasRole("USER")//USER role can access /users/**
.antMatchers("/admin/**").hasRole("ADMIN")//ADMIN role can access /admin/**
.antMatchers("/quests/**").permitAll()// anyone can access /quests/**
.anyRequest().authenticated()//any other request just need authentication
.and()
.formLogin();//enable form login
}

@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.inMemoryAuthentication()
.passwordEncoder(passwordEncoder())
.withUser("tim").password(passwordEncoder().encode("123")).roles("ADMIN")
.and()
.withUser("joe").password(passwordEncoder().encode("234")).roles("USER");
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

}

MainController.java
@Controller
public class MainController {
@GetMapping("/")
ModelAndView index(Principal principal) {
ModelAndView mv = new ModelAndView("home");
if (principal != null) {
mv.addObject("message", principal.getName());
} else {
mv.addObject("message", "anon.");
}

return mv;
}

@GetMapping("/**")
String request(HttpServletRequest request, Model model) {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
ModelAndView mv = new ModelAndView("home");
model.addAttribute("uri", request.getRequestURI())
.addAttribute("user", auth.getName())
.addAttribute("roles", auth.getAuthorities());

return "html"; //<-- whenever I change this to return "jsp/jsp"; it breaks
}

html.html ( thymeleaf )
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<body>
<p>
URI: <h3 th:text="${uri}"></h3>
User: <h3 th:text="${user}"></h3>
Roles: <h3 th:text="${roles}"></h3>
<a href="/admin/">/admin/</a><br/>
<a href="/users/">/users/</a><br/>
<a href="/others/">/others/</a><br/>
<a href="/quests/">/quests/</a><br/><br/>
</p>
<form th:action="@{/logout}" method="post">
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
<input type="submit" value="Logout">
</form>
</body>
</html>

当我尝试使用 JSP 文件很好地完成这项工作时,浏览器只输出

HTTP 状态 500 ?内部服务器错误

在 NetBeans 输出窗口中,gradle 的任务运行正在运行,日志显示在最顶部(整个日志非常广泛):

2018-10-07 18:09:40.070 ERROR 6024 --- [nio-8080-exec-4] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-4] 异常处理模板“jsp/jsp”:模板解析时出错(模板:“类路径资源[templates/jsp/jsp.html]”)

我正在尝试包含的 JSP View
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<body>
<p>URI: ${uri} <br/>
User : ${user} <br/>
roles: ${roles} <br/><br/>
<a href="/admin/">/admin/</a><br/>
<a href="/users/">/users/</a><br/>
<a href="/others/">/others/</a><br/>
<a href="/quests/">/quests/</a><br/><br/>
</p>
<form action="/logout" method="post">
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}"/>
<input type="submit" value="Logout">
</form>
</body>
</html>

最后,我的项目树:

enter image description here

我的假设是应用程序不知道文件 jsp.jsp 文件夹内 模板/jsp ,这就是为什么我的目标是查看解析器,但正如我所说,我很容易出错。

这只是我试图实现和构建的一个例子,所以请随时提出建议,thanx。

最佳答案

只为 jsp 添加一个 View 解析器是行不通的,
我们还需要为 jsp 添加一个模板解析器,并将其连接到 spring 模板引擎。
下面的代码适用于 Spring Boot 2。

package org.jwebshop.webshop.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

import javax.annotation.Resource;

@Configuration
@EnableWebMvc
public class ViewConfiguration implements WebMvcConfigurer {

@Resource
protected ApplicationContext applicationContext;

@Resource
protected SpringTemplateEngine springTemplateEngine;

@Bean
public ThymeleafViewResolver thymeleafViewResolver(){
final ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setViewNames(new String[] {"thyme/*"});
viewResolver.setExcludedViewNames(new String[] {"jsp/*"});
viewResolver.setTemplateEngine(springTemplateEngine);
viewResolver.setCharacterEncoding("UTF-8");
return viewResolver;
}

@Bean
public InternalResourceViewResolver jspViewResolver(){
final InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewNames("jsp/*");
return viewResolver;
}

@Bean
public SpringResourceTemplateResolver thymeleafTemplateResolver(){
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(false);
templateResolver.setOrder(0);
return templateResolver;
}

@Bean
public SpringResourceTemplateResolver jspTemplateResolver(){
final SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".jsp");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setCacheable(false);
templateResolver.setOrder(1);
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/");
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
}
}
package org.jwebshop.webshop.controller.web.thymeleaf;

import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class RootController {

@Secured("ROLE_CUSTOMER")
@GetMapping({"/", "/index"})
public String root() {
return "thyme/index";
}
}
package org.jwebshop.webshop.controller.web.jsp;

import org.jwebshop.webshop.dto.converter.impl.UserDataConverter;
import org.jwebshop.webshop.dto.data.UserData;
import org.jwebshop.webshop.entity.User;
import org.jwebshop.webshop.service.UserService;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;

@Controller
public class LuckyController {

@Resource
protected UserService userService;

@Resource
protected UserDataConverter userDataConverter;

@Secured("ROLE_CUSTOMER")
@GetMapping("/lucky")
public String hello(final Model model, final Authentication auth) {
final User user = userService.findByEmail(auth.getName());
final UserData userData = userDataConverter.convertFrom(user);
model.addAttribute("userData", userData);
return "jsp/lucky";
}
}

Folder structure: 
webapp
|
WEB-INF
|
views
| |
jsp thyme

https://imgur.com/qOTgYZW

关于spring-mvc - 在 Spring Boot 应用程序中使用 JSP 和 Thymeleaf View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com