当前位置: 首页 > 知识库问答 >
问题:

JSP应用程序中集成vaadin视图的问题

鲜于玮
2023-03-14

当我已经使用JSP作为登录/注册表单时,我在Spring MVC应用程序中使用vaadin。我有问题,可能WebSecurity没有为我的vaadin视图提供POST方法。我想在成功验证用户后返回一个组件的vaadin视图。我不知道问题出在哪里。

将JSP与vaadin集成可能很奇怪,但我认为这很简单

配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig  extends WebSecurityConfigurerAdapter {

private UserDetailsServiceImpl userDetailsService;
private AppUserRepo appUserRepo;


@Autowired
public WebSecurityConfig(UserDetailsServiceImpl userDetailsService, AppUserRepo appUserRepo) {
    this.userDetailsService = userDetailsService;
    this.appUserRepo = appUserRepo;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/admin").hasRole("ADMIN")
            .antMatchers("/user").hasAnyRole("ADMIN", "USER")
            .antMatchers("/upload").hasRole("ADMIN")
            .antMatchers("/gallery").hasRole("ADMIN")
            .and()
            .csrf().disable()
            .formLogin().loginPage("/login").permitAll()
            .and()
            .logout().permitAll();
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers(
            // Vaadin Flow static resources //
            "/VAADIN/**",

            // the standard favicon URI
            "/favicon.ico",

            // the robots exclusion standard
            "/robots.txt",

            // web application manifest //
            "/manifest.webmanifest",
            "/sw.js",
            "/offline-page.html",

            // (development mode) static resources //
            "/frontend/**",

            // (development mode) webjars //
            "/webjars/**",

            // (production mode) static resources //
            "/frontend-es5/**", "/frontend-es6/**");
}

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

@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
    return authenticationManager();
}

@EventListener(ApplicationReadyEvent.class)
public void get(){
    AppUser appUserUser = new AppUser("jan", passwordEncoder().encode("jan"),"ROLE_USER");
    AppUser appUserAdmin = new AppUser("admin", passwordEncoder().encode("admin"),"ROLE_ADMIN");
    appUserRepo.save(appUserUser);
    appUserRepo.save(appUserAdmin);
}
}

控制器:

@Controller
public class UserFormController {
@Autowired
private RegistrationService registrationService;

@Autowired
private SecurityService securityService;

@Autowired
private UserValidator userValidator;

@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
    model.addAttribute("userForm", new AppUser());

    return "/registration.jsp";
}

@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") AppUser userForm, BindingResult bindingResult, Model model) {
    userValidator.validate(userForm, bindingResult);

    if (bindingResult.hasErrors()) {
        return "/registration.jsp";
    }

   registrationService.save(userForm);
   securityService.autoLogin(userForm.getUsername(), userForm.getPassword());

    return "redirect:/welcome.jsp";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
    if (error != null)
        model.addAttribute("error", "Your username and password is invalid.");

    if (logout != null)
        model.addAttribute("message", "You have been logged out successfully.");

    return "/login.jsp";
}

@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
    return "upload";
}
}

瓦丁视图:

@Route("upload")
public class UploadGui extends VerticalLayout{

private ImageUploader imageUploader;
private ByteConverter byteConverter;

@Autowired
public UploadGui(ImageUploader imageUploader, ByteConverter byteConverter) {
    this.byteConverter = byteConverter;
    this.imageUploader = imageUploader;

    MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();
    Upload upload = new Upload(buffer);

    upload.addSucceededListener(event -> {
        byteConverter.byteArrayToFile(buffer.getOutputBuffer(event.getFileName()), event);
        imageUploader.uploadFile(new File(event.getFileName()));
    });

    add(upload);
}
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<c:set var="contextPath" value="${pageContext.request.contextPath}"/>

<!DOCTYPE html>
<html lang="en">
  <head>
      <meta charset="utf-8">
      <title>Log in with your account</title>

      <link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
      <link href="${contextPath}/resources/css/common.css" rel="stylesheet">
  </head>

  <body>

    <div class="container">
      <form method="POST" action="${contextPath}/login" class="form-signin">
        <h2 class="form-heading">Log in</h2>

        <div class="form-group ${error != null ? 'has-error' : ''}">
            <span>${message}</span>
            <input name="username" type="text" class="form-control" placeholder="Username"
                   autofocus="true"/>
            <input name="password" type="password" class="form-control" placeholder="Password"/>
            <span>${error}</span>
            <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

            <button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
            <h4 class="text-center"><a href="${contextPath}/registration">Create an account</a></h4>
        </div>
      </form>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="${contextPath}/resources/js/bootstrap.min.js"></script>
  </body>
</html>

属性:

spring.jpa.hibernate.ddl-auto=create
spring.servlet.multipart.enabled=false
spring.jpa.show-sql=true
spring.messages.basename=validation

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.6.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>photouploader</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>photouploader</name>
<description>web uploader for photos</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.cloudinary/cloudinary-core -->
    <dependency>
        <groupId>com.cloudinary</groupId>
        <artifactId>cloudinary-core</artifactId>
        <version>1.22.1</version>
    </dependency>
    <dependency>
        <groupId>com.cloudinary</groupId>
        <artifactId>cloudinary-http44</artifactId>
        <version>RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.vaadin/vaadin-spring-boot-starter -->
    <dependency>
        <groupId>com.vaadin</groupId>
        <artifactId>vaadin-spring-boot-starter</artifactId>
        <version>13.0.11</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.tomcat.embed/tomcat-embed-jasper -->
    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <version>9.0.24</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

当我打开“localhost:8080/upload”时,我得到了日志:

`Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported]`

在浏览器中我看到了

Server connection lost, trying to reconnect...

我认为csrf。disable()只是解决问题,但问题是另一个。

也许你能给我解释一下?

也许是一些网络。xml配置?

共有1个答案

汪坚
2023-03-14

我认为你可能错过了瓦丁内部请求的安全配置。这些用于前端和后端之间的通信。请参阅本教程的isFrameworkInternalRequest部分。

 类似资料:
  • 很抱歉问这个问题。我找了几个小时,但找不到任何帮助。 我想用JSP做一个简单的问答应用程序。我创建了如下2个表 col1:QuizId col2:测验名称col3:问题数 COL1:QtnNum COL2:问题COL3:option1COL4:option2COL5:option3COL6:option4COL7:correctoption 我的要求是在页面末尾添加一个提交按钮。单击submit按

  • 问题内容: 我在RapidMiner中有一个文本分类过程。它从指定的excel ssheet读取测试数据并进行分类。我还有一个小型Java应用程序,它正在运行此过程。现在,我想在应用程序中添加文件输入部分,以便每次我都可以从应用程序(而不是RapidMiner)中指定excel文件。有什么提示吗? 这是代码: 这是错误: 最好的祝福 Armen 问题答案: 我看到两种方法可以做到这一点。 第一个方

  • 我正在facebook上构建自己的社交平台,欢迎对我的web应用程序的架构提出一些建议。 我需要一些从脸书API返回的数据,为了获得这些数据,我需要让我的用户登录脸书(OAuth 2.0)。这是我有点困惑的地方。 我应该从后端调用FacebookAPI(我使用的是Python),然后返回相同的数据作为响应吗? 我应该从前端调用Facebooks API(浏览器的Javascript ),然后将数据

  • 我已经集成了Vaadin 7,将用户界面嵌入到基于Spring Boot的应用程序的一些JSP页面中,如Vaadin Book中所述。 尽管当我调用嵌入它的路径(通过SpringMVC控制器)时,名为“v-my-vaadin-UI”的UI被正确显示,但在与UI交互时,我得到了一个HTTP405错误。 URL上出现错误: http://localhost:8080/v-我的vaadin ui/UID

  • 我试图了解ApacheShiro工作流以及如何将其集成到我的应用程序中。我不明白的是,我如何以及在哪里执行登录,然后发送重定向?或者Shiro会自动执行此操作(因为我在ini文件中指定了域)?我可以发送自定义信息(用户属性)和重定向(通过Servlet响应而不是支持bean)吗? 到目前为止我所了解和拥有的: 将Shiro侦听器和过滤器添加到web。xml文件,以便它能够响应请求: 创建一个shi

  • 我在一个Polymer2.0应用程序中使用了一个vaadin-grid,其中有几个列,几乎所有列都有一个Vaadin-Grid-Sorter。由于我想给用户一个机会来保持其排序首选项,我的问题是: 我可以在代码中设置要排序的列和排序方向吗? 我看了一下网格源代码,但没有找到任何(公共)属性。