Spring boot with javaFx - java

I'm working on a java desktop app using spring boot and javaFx.
it's a crud app so I'm working with mysql database
I want the controllers to be both spring boot and javaFx controllers, and for that I used setControllerFactory().
here is my application
Application:
package com.gi.quizui;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(QuizApplication.class, args);
}
}
QuizApplication:
package com.gi.quizui;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.stage.Stage;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ConfigurableApplicationContext;
public class QuizApplication extends Application {
private ConfigurableApplicationContext applicationContext;
#Override
public void init() {
applicationContext = new SpringApplicationBuilder(com.gi.quizui.Application.class).run();
}
#Override
public void start(Stage stage) {
applicationContext.publishEvent(new StageReadyEvent(stage));
}
#Override
public void stop() {
applicationContext.close();
Platform.exit();
}
class StageReadyEvent extends ApplicationEvent {
public StageReadyEvent(Stage stage) {
super(stage);
}
public ConfigurableApplicationContext getAppContext() {
return applicationContext;
}
public Stage getStage() {
return ((Stage) getSource());
}
}
}
and stage initializer:
package com.gi.quizui;
import com.gi.quizui.QuizApplication.StageReadyEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import java.io.IOException;
#Component
public class StageInitializer implements ApplicationListener<StageReadyEvent> {
#Value("classpath:fxml/quiz.fxml")
private Resource quizResource;
public StageInitializer(#Value("${spring.application.ui.title}") String applicationTitle) {
this.applicationTitle = applicationTitle;
}
private String applicationTitle;
#Override
public void onApplicationEvent(StageReadyEvent event) {
Stage stage = event.getStage();
ConfigurableApplicationContext springContext = event.getAppContext();
try {
FXMLLoader fxmlLoader = new FXMLLoader(quizResource.getURL());
fxmlLoader.setControllerFactory(springContext::getBean);
Parent parent = fxmlLoader.load();
stage.setScene(new Scene(parent, 800, 600));
stage.setTitle(applicationTitle);
stage.show();
} catch (IOException e) {
throw new RuntimeException();
}
}
}
I keep getting this error : (edit)
Exception in Application start method
2021-01-16 15:37:15.286 INFO 8652 --- [lication Thread] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2021-01-16 15:37:15.320 INFO 8652 --- [lication Thread] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2021-01-16 15:37:15.343 INFO 8652 --- [lication Thread] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.lang.RuntimeException: javafx.fxml.LoadException:
/C:/Users/FacilOrdi/IdeaProjects/quizManagement/target/classes/fxml/quiz.fxml:7
at com.gi.quizui.StageInitializer.onApplicationEvent(StageInitializer.java:40)
at com.gi.quizui.StageInitializer.onApplicationEvent(StageInitializer.java:16)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:426)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:383)
at com.gi.quizui.QuizApplication.start(QuizApplication.java:20)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Caused by: javafx.fxml.LoadException:
/C:/Users/FacilOrdi/IdeaProjects/quizManagement/target/classes/fxml/quiz.fxml:7
at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2625)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2603)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2466)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2435)
at com.gi.quizui.StageInitializer.onApplicationEvent(StageInitializer.java:35)
... 16 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.gi.controllers.QuizController' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1177)
at javafx.fxml.FXMLLoader$ValueElement.processAttribute(FXMLLoader.java:938)
at javafx.fxml.FXMLLoader$InstanceDeclarationElement.processAttribute(FXMLLoader.java:980)
at javafx.fxml.FXMLLoader$Element.processStartElement(FXMLLoader.java:227)
at javafx.fxml.FXMLLoader$ValueElement.processStartElement(FXMLLoader.java:752)
at javafx.fxml.FXMLLoader.processStartElement(FXMLLoader.java:2722)
at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2552)
... 19 more
controller:
package com.gi.controllers;
import org.springframework.stereotype.Component;
#Component
public class QuizController {
}
I don't understand why it is not working, I've found related questions but I don't get how it works. It would be very helpful if there are other alternatives to do this.

In order to be aware of classes which have annotations such as #Component, etc., Spring Boot needs to scan through part of the classpath at startup time. By default it will scan the package containing the class you pass to SpringApplicationBuilder (Application in your case) and all subpackages.
So with the way you have things set up, it will scan com.gi.quizui and all subpackages.
Your QuizController class is not in a sub-package of com.gi.quizui; it is in com.gi.controllers. Consequently it won't be found.
The recommendation in the Spring Boot documentation is actually to have the Application class in the highest-level package that contains classes or resources, which is likely com.gi in your case. If you move that class to that package, it should fix the issue.
Alternatively, you can override the default behavior using the #ComponentScan annotation:
package com.gi.quizui;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan ;
#SpringBootApplication
#ComponentScan(basePackages={"com.gi.quizui","com.gi.controllers"})
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(QuizApplication.class, args);
}
}
A typesafe alternative is to use the basePackageClasses parameter instead of basePackages:
package com.gi.quizui;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan ;
import com.gi.controllers.QuizController ;
#SpringBootApplication
#ComponentScan(basePackageClasses={Application.class, QuizController.class})
public class Application {
public static void main(String[] args) {
javafx.application.Application.launch(QuizApplication.class, args);
}
}

Related

Spring boot , i18n error, wrong implementation of LocaleResolver is choosen

I am developing a spring boot based application that supports internationalisation
My env:
Jdk11
Spring boot 2.7.0
Spring Security
Here is my web mvc conf
WebMvcConf.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
#Configuration
public class WebMvcConf implements WebMvcConfigurer {
public static final Locale idnLocale = Locale.forLanguageTag("id-ID");
#Bean
public LocaleResolver defaultLocaleResolver(){
var resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(idnLocale);
return resolver;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor(){
var interceptor = new LocaleChangeInterceptor();
interceptor.setIgnoreInvalidLocale(false);
interceptor.setParamName("lang");
return interceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
}
And here is my security config:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
#Configuration
#EnableWebSecurity
public class SecurityConf{
#Bean
public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.cors()//enable cors
.and()
.csrf().disable()//disable csrf
.sessionManagement(session->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))//stateless session (Rest)
.authorizeHttpRequests(authz->authz
.antMatchers(HttpMethod.GET,"/").permitAll()
.antMatchers(HttpMethod.POST,"/users/login","users/register","users/forgot-password").permitAll()
.antMatchers(HttpMethod.PATCH,"/users/password").permitAll()
.anyRequest().authenticated());//authorize any request except ignored endpoint above
return httpSecurity.build();
}
}
Here is the structure of the message properties:
Here is my application.yml content:
Here is the content of messages_en.properties:
rest.welcome.ok=Welcome to ABC Backend Service, have fun!!!
rest.users.login.ok=Successfully Logged in
#Error Message
rest.500.err=Internal Server Error
rest.422.err=Constraint Violation Error
rest.400.err=Invalid request body
rest.required-req-body-missing.err=Required request body is missing
Here is content of messages.properties:
rest.welcome.ok=Selamat Datang di Service ABC, selamat bersenang-senang!!!
rest.users.login.ok=Login sukses
#Error message
rest.500.err=Kesalahan Internal di sistem
rest.422.err=Error pelanggaran constraint
rest.400.err=Kesalahan pada request body
rest.required-req-body-missing.err=Request body (payload) yang dibutuhkan tidak ditemukan
Here is my test to test the message source:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.MessageSource;
import java.util.Locale;
#SpringBootTest
public class MessageSourceTest {
#Autowired
private MessageSource messageSource;
#BeforeEach
void init(){
}
#Test
public void message_provided_should_correctly_localized(){
String msgEnglish = messageSource.getMessage("rest.500.err",null, new Locale("en"));
String msgIndo = messageSource.getMessage("rest.500.err",null,Locale.forLanguageTag("id-ID"));
Assertions.assertEquals("Internal Server Error",msgEnglish);
Assertions.assertEquals("Kesalahan Internal di sistem",msgIndo);
}
}
And the test is pass:
But when I try to hit a mvc rest controller and add query parameter lang=en , I always got an error response saying Cannot change HTTP accept header - use a different locale resolution strategy
So I debug the LocaleChangeInterceptor and found that spring boot provide a wrong implementation of the LocaleResolver, they provide AcceptHeaderResolver, which what I want is the SessionLocaleResolver as I state it in my WebMvcConf class. See following picture:
Anyone knows what is wrong and how to fix it?any response will be appreciated

JavaFX access error, not sure what's causing it [duplicate]

This question already has answers here:
can not access a member of class org.springframework.aop.TruePointcut with modifiers public
(3 answers)
Closed 10 months ago.
This is my code (I removed a lot of graphics logic as to see if it would run a most basic file)
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class Client extends Application {
public static String host = "127.0.0.1";
public BufferedReader fromServer;
public PrintWriter toServer;
public Scanner consoleInput = new Scanner(System.in);
public Client() {
}
public static void main(String[] args) {
launch(args);
}
public void start(Stage displayStage) {
try {
System.out.println("HELLO");
} catch (Exception e) {
System.err.println("Client connection error!");
e.printStackTrace();
}
}
}
but the error messages are really bizarre and I'm not sure what exactly it means; it mentions a public access but afaik, public means anything can access it and I don't use reflection but its throwing errors regarding reflection and I'm really stumpted as to what could be causing this error.
Exception in Application constructor
Exception in thread "main" java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:568)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1071)
Caused by: java.lang.RuntimeException: Unable to construct Application instance: class eHillsClient.Client
at javafx.graphics#18/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:891)
at javafx.graphics#18/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:196)
at java.base/java.lang.Thread.run(Thread.java:833)
Caused by: java.lang.IllegalAccessException: class com.sun.javafx.application.LauncherImpl (in module javafx.graphics) cannot access a member of class eHillsClient.Client with modifiers "public"
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:392)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:674)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:489)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480)
at javafx.graphics#18/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:803)
at javafx.graphics#18/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:484)
at javafx.graphics#18/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:457)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#18/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:456)
at javafx.graphics#18/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics#18/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#18/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
... 1 more
Make Client class public because a main class in JavaFX Applicaions must have a public access modifier to be picked by getConstructor() method in Application class.In normal cases it wouldn't cause an error but your main class will not be an entry point to the program(in JavaFx Applicaions the entry points is Applicaion class).
You can further read here

Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Application

I'm trying to execute a .jar file which I produced from a JavaFX project (i already set the VM Options in Intellij with module path and modules to include) but I keep getting this error
Exception in thread "main" java.lang.NoClassDefFoundError: javafx/application/Application
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1010)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:855)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:753)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:676)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:634)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
at main.Launcher.main(Launcher.java:5)
Caused by: java.lang.ClassNotFoundException: javafx.application.Application
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
... 10 more
I also have a Launcher class, which Main method just does Main.main(args), where Main is the class that extends Application.
What can i do more?
This is the main class of my project
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.io.IOException;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("/fxml/InserimentoPorta.fxml"));
primaryStage.setTitle("EP Miner");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}catch (IOException e){
System.out.println(e.getMessage());
System.exit(-1);
}
}
public static void main(String[] args) {
launch(args);
}
}
And there are 3 controllers, one for each of my fxml file (i'm not posting the controllers code because the question would be too long and i don't think it's necessary to solve this problem)

SpringBoot Swagger2 rest API documentation is not loading

I am just trying out to get the documentation for my small REST API written in in spring with swagger2 inclusion. When i try to access my swagger page the following error is shown in browser console.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Sep 25 21:09:08 IST 2017
There was an unexpected error (type=Not Found, status=404).
No message available
My code snippets are below mentioned.
package com.example.demo;
import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
#RestController
#RequestMapping(value="/rooms")
#Api(value="rooms", tags=("rooms"))
public class RoomController {
#Autowired
private RoomRepositery roomRepo;
#RequestMapping(method = RequestMethod.GET)
#ApiOperation(value="Get All Rooms", notes="Get all rooms in the system", nickname="getRooms")
public List<Room> findAll(#RequestParam(name="roomNumber", required=false)String roomNumber){
if(StringUtils.isNotEmpty(roomNumber)) {
return Collections.singletonList(roomRepo.findByRoomNumber(roomNumber));
}
return (List<Room>) this.roomRepo.findAll();
}
}
App class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.any;
#SpringBootApplication
#EnableSwagger2
public class RoomServiceApp {
#Bean
public Docket api(){
return new Docket(DocumentationType.SWAGGER_2).groupName("Room").select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo"))
.paths(any()).build().apiInfo(new ApiInfo("Room Services",
"A set of services to provide data access to rooms", "1.0.0", null,
new Contact("Frank Moley", "https://twitter.com/fpmoles", null),null, null));
}
public static void main(String[] args) {
SpringApplication.run(RoomServiceApp.class, args);
}
}
I am not able to found what i am missing here. Can any one help me out?
Thanks
You have to use http://localhost:9090/swagger-ui.html for swagger UI and http://localhost:9090/v2/api-docs?group=Room for JSON API.
I used the same code and find attached screenshot.
refer to this project for more details.
Request mapping at method level should have URI path like below for findAll method. Consumes and produces also required if there is input passed to method and output returned from method.
The reason is empty mapping value at method level will result in 'host:port/contextPath/' for which swagger will return 404.
#RequestMapping(method = { RequestMethod.GET }, value = "/roomList", consumes = {
MediaType.ALL}, produces = { MediaType.ALL})

Unknown Command -Spring MVC

package de.gdv.sp.configuration;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.captcha.botdetect.web.servlet.CaptchaServlet;
#Configuration
public class CaptchaConfiguration {
#Bean(name = "captchaServlet")
public ServletRegistrationBean captchaServlet() {
return new ServletRegistrationBean(new CaptchaServlet(), "/kontakt");
}
}
I am trying to implement BotDetect Captcha in our Spring MVC/Boot project.When I tried to create servlet with annotations( without web.xml) I always get the following screen:screenshot of http://localhost:8080/kontakt
Moreover when I write the HTML code of this captcha, I get the following result.Botdetect Captcha does not show picture
<botDetect:captcha id="exampleCaptcha"/>
<div class="validationDiv">
<input id="captchaCode" type="text" name="captchaCode"
value="${basicExample.captchaCode}"/>
<input type="submit" name="submit" value="Submit" />
<span class="correct">${basicExample.captchaCorrect}</span>
<span class="incorrect">${basicExample.captchaIncorrect}</span>
</div>
How can I solve this problem?
[BotDetect Captcha website][3]
You can try either:
extend WebApplicationInitializer
package de.gdv.sp.configuration;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.captcha.botdetect.web.servlet.CaptchaServlet;
#Configuration
public class CaptchaConfiguration extends WebApplicationInitializer {
#Bean(name = "captchaServlet")
public ServletRegistrationBean captchaServlet() {
return new ServletRegistrationBean(new CaptchaServlet(), "/kontakt");
}
}
move your bean definition into a class that extends WebApplicationInitializer.
#Configuration
public class WebXMLReplacement extends WebApplicationInitializer {
//other configurations
#Bean(name = "captchaServlet")
public ServletRegistrationBean captchaServlet() {
return new ServletRegistrationBean(new CaptchaServlet(), "/kontakt");
}
}
There is Standard way to Register your custom servlet in Spring MVC application. You need to Create Initializer Class by implementing WebApplicationInitializer.
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import com.captcha.botdetect.web.servlet.CaptchaServlet;
public class MyServletInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext)
throws ServletException {
Dynamic myServlet = servletContext.addServlet("kontakt", CaptchaServlet.class);
myServlet.addMapping("/kontakt");
}
}
You could use this approach to register DispatcherServlet
manually.Similarly, you can register listeners and filters by creating a new implementation
of WebApplicationInitializer.

Categories

Resources