How to use listener-class in spring boot 2.2.1 RELEASE - spring

Migrating Spring web project into spring boot application with following versions
Spring version:-4.1.7
Spring boot:2.2.1 RELEASE
part of migration i need to remove src/main/web-app folder.In this folder i have two files
dispatcher-servlet.xml
web.xml
dispatcher-servlet
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.data.services" />
<bean id="systemPlaceholderConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" />
<mvc:interceptors>
<bean class="com.data.services.interceptors.RequestLogInterceptor" />
</mvc:interceptors>
</beans>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
metadata-complete="true" version="3.0">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>XERService</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/conf/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jRefreshInterval</param-name>
<param-value>30000</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>xerwebapp.root</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>com.data.services.configuration.ServiceContextListener</listener-class>
</listener>
</web-app>
ServiceContextListener
#WebListener("Service context listener")
public class ServiceContextListener implements ServletContextListener
{
public static final Logger LOG = Logger.getLogger("XERService");
/**
* Context initializer. This method sets the root folder for the log4j
*/
#Override
public void contextInitialized(ServletContextEvent event)
{
}
#Override
public void contextDestroyed(ServletContextEvent event)
{
try
{
LoggingPropertyHandler.clear();
if (XFabSiteConfigManager.getInstance().getRequesterConfigInfo() != null)
{
XFabFactory.getXfabInstance().unInitializeRequester();
}
}
catch (Exception exception)
{
LOG.warn("Exception while uninitializing Requestor", exception);
}
}
}
RequestLogInterceptor
#Component
public class equestLogInterceptor extends HandlerInterceptorAdapter
{
/**
* Method to add the Audit user in the log
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
String auditUser = request.getHeader(RequestParameterConstants.AUDIT_USER);
if (auditUser == null)
{
auditUser = "";
}
LoggingPropertyHandler.addAuditUserName(auditUser);
return true;
}
}
How can we include following listener in spring boot
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>com.data.services.configuration.ServiceContextListener</listener-class>
</listener>
Is there any simplest mechanism available in spring boot.

You can create the Listener bean like this:
// Register ServletContextListener
#Bean
public ServletListenerRegistrationBean<ServletContextListener> listenerRegistrationBean() {
ServletListenerRegistrationBean<ServletContextListener> bean =
new ServletListenerRegistrationBean<>();
bean.setListener(new MyServletContextListener());
return bean;
}

Related

WARNING: No mapping found for HTTP request with URI in DispatcherServlet with name 'SpringRest'

I am trying to hit the url but I am 404 error & in console I am getting warning as WARNING: No mapping found for HTTP request with URI [/spring-mvc/hello] in DispatcherServlet with name 'SpringRest'
I am not sure about the web.xml settings. My code is like below.
Any help would be appreaciated. Thanks in Advance..
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>SpringRest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringRest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
TestController.java
package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wocs.services.common.ServiceException;
import com.wocs.services.order.iface.OrderServiceIface;
import com.wocs.services.order.model.hiera.OrderHiera;
#RestController
public class TestController {
#RequestMapping("/hello")
public String hello() throws ServiceException
{
return "Hello............";
}
}
SpringRest-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd" >
<mvc:annotation-driven/>
<context:annotation-config></context:annotation-config>
<context:component-scan base-package = "com.wocs" />
<import resource="classpath:/beanfactory/service-bean-config.xml" />
</beans>
It might be the #RequestMapping("/hello") as you're NOT defining what type of method is used to receive the request.
Try this
#GetMapping(value="/hello", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<String> hello() throws ServiceException
{
return new ResponseEntity<>("Hello............", HttpStatus.OK);
}
You can modify your Controller class like this and tell me if it works
#Controller
public class TestController {
#GetMapping("/hello")
public String hello() throws ServiceException
{
return "Hello............";
}
}
if this doesn't work you can try
#Controller
public class TestController {
#RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "application/json")
public String hello() throws ServiceException
{
return "Hello............";
}
}
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>SpringRest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SpringRest</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
check that your web.xml file and SpringRest-servlet.xml file is in webapp/WEB-INF folder, also check that your controller java class is in src/main/java and not in src/main/test , most of the time improper directory structure causes the problem. Let me know if it still does not work.
Add this to your web.xml file:-
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/SpringRest-servlet.xml</param-value>
</context-param>
<listener>
<listener class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

The requested resource is not available error in spring mvc project

I got an error as follows :
Status report
message: /SBC/loginform.html
description :The requested resource is not available.
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/Views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>OpticareVisionHouse</display-name>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/forms/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/resources/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
</web-app>
-------------------------------------------------
LoginController.java
#Controller
#RequestMapping("loginform.html")
public class LoginController {
#Autowired
public LoginService loginService;
#RequestMapping(method = RequestMethod.GET)
public String showForm(Map model) {
LoginForm loginForm = new LoginForm();
model.put("loginForm", loginForm);
System.out.print("controller calls1");
return "loginform";
}
#RequestMapping(method = RequestMethod.POST)
public String processForm(#Valid LoginForm loginForm, BindingResult result,
Map model) {
System.out.print("controller calls2");
if (result.hasErrors()) {
return "loginform";
}
/*
String userName = "UserName";
String password = "password";
loginForm = (LoginForm) model.get("loginForm");
if (!loginForm.getUserName().equals(userName)
|| !loginForm.getPassword().equals(password)) {
return "loginform";
}
*/
boolean userExists = loginService.checkLogin(loginForm.getUserName(),
loginForm.getPassword());
if(userExists){
model.put("loginForm", loginForm);
return "loginsuccess";
}else{
result.rejectValue("userName","invaliduser");
return "loginform";
}
}
------------------------------------------------
index.jsp
<% response.sendRedirect("loginform.html"); %>
------------------------------------------------
index.jsp is there at webContent.
loginform.jsp is at webContent->web-Inf ->Views
Your dispatcherServlet is mapping urls like: /forms/* to the spring servlet.
You are requesting a url like: /SBC/loginform.html
This request will never go to the spring servlet. You have to access: /{your app context}/forms/loginform.html in order to go to the spring url mapped. Your app context seems to be "SBC", so it will be something like: /SBC/forms/loginform.html
Another way is change the Servlet mapping to:
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
This way, every request on your app context /SBC/* will be routed to the spring servlet.
With this configuration, you should be able to access your controller with: /SBC/loginform.html

Cannot perform correctly spring-mvc mapping

I'm developing spring-mvc web-application and I faced some mapping problems:
My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>pages/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
My controller:
#Controller
public class MainController {
#Autowired
UserService userService;
#Autowired
PhotosService photosService;
#RequestMapping(method=RequestMethod.GET)
public String loadIndex(Model model)
{
model.addAttribute("firstName", "WWWALTER");
return "index";
}
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String save( #ModelAttribute("document") PhotosEntity photosEntity,
#RequestParam("file") MultipartFile file) {
Blob blob = null;
try {
blob = new SerialBlob(file.getBytes());
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// PhotosEntity photosEntity = new PhotosEntity();
photosEntity.setContent(blob);
photosEntity.setFilename(file.getOriginalFilename());
photosService.saveFile(photosEntity);
return "index";
}
Also I have a application name in tomcat 7 -"c2". So should I map with "c2/" prefix?
Can you please help me create correct mapping?
I want to add an attribute in first method and retrieve it in jsp page:
#RequestMapping(method=RequestMethod.GET)
public String loadIndex(Model model)
{
model.addAttribute("firstName", "WWWALTER");
return "index";
}
- but this method isn't invoked.
You can retrieve the attribute like this: ${firstName} from your jsp-page.
Also try changing #RequestMapping(method=RequestMethod.GET) to #RequestMapping(value = "/", method=RequestMethod.GET)
It sounds so stupid. But I just forgot to put
<mvc:annotation-driven />
in servlet context file. Sorry!

Spring: How to define database config?

I try to execute simple request to MySql database via jdbcTemplate but I have an error when framework load and parse xml file whicj define my datasource:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_training"/>
<property name="username" value="root"/>
<property name="password" value="pass"/>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SpringTrainingTemplate</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml /WEB-INF/jdbc-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and Controller that invoke it:
#Controller
public class HomeController {
#Autowired
private ExampleService exampleService;
#RequestMapping(value = "/details", method = RequestMethod.GET)
public String details(Model model) {
ApplicationContext context = new ClassPathXmlApplicationContext("jdbc-config.xml");
ExampleDao dao = (ExampleDao) context.getBean("ExampleDao");
List<Application> list = dao.getAllApplications();
model.addAttribute("application", list.get(0).getName());
model.addAttribute("descriptionOfApplication", list.get(0).getDescription());
return "details";
}
}
public class ExampleDao {
private String request = "select * from application";
private JdbcTemplate jdbcTemplate;
#Autowired
private DataSource dataSource;
public ExampleDao(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Application> getAllApplications() {
List<Application> applications = this.jdbcTemplate.query(request, new RowMapper<Application>() {
#Override
public Application mapRow(ResultSet rs, int i) throws SQLException {
Application application = new Application();
application.setName(rs.getString("name"));
application.setType(rs.getString("type"));
application.setDescription(rs.getString("description"));
application.setDownloads(rs.getInt("downloads"));
return application;
}
});
return applications;
}
}
Whe I run it and input http://localhost:8080/details I have got an 500 exception with stacktrace with this message:
root cause
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [jdbc-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [jdbc-config.xml] cannot be opened because it does not exist
Can you explain me how to configure jdbc connection in rigth way or if my approach is correct where I should look for a solution of my issue? All help would be appreciated. Thanks.
Spring cannot find your jdbc-config.xml configuration file.
You can put it in your classpath instead of the WEB-INF folder and load it in your web.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml,classpath:jdbc-config.xml</param-value>
</context-param>
A good practice is to create folders main and resources in your src folder and to add them in the classpath. Then you can put the spring config file in the src/resources folder.
class path resource [jdbc-config.xml] cannot be opened because it does
not exist
Is the file name correct, where is it located? the file specifying the db connection is not where you said it should be - on the classpath.

Setting up Vaadin and Spring 3 - Autowiring fails (annotations)

I'm having some trouble using the #Autowire annotation of spring 3 in a vaadin application.
I have made a tiny test project with just a button which executes a method in an autowired service class.
I'm getting a NullPointerException when I click the button, because the service is never injected.
I have annotated the service with #Service("calculationService")
This is my application class:
package vaadinBaas;
// imports
public class MyVaadinApplication extends Application {
private Window window;
private CalculationService calculationService;
#Autowired
public void setCalculationService(CalculationService calculationService) {
this.calculationService = calculationService;
}
#Override
public void init() {
window = new Window("Show me the magic");
setMainWindow(window);
Button button = new Button("Click Me");
button.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
window.addComponent(new Label(String.valueOf(calculationService.multiply(10, 10))));
}
});
window.addComponent(button);
}
}
This is my spring application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ct="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<ct:component-scan base-package="vaadinBaas" />
<ct:annotation-config />
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"/>
</beans>
And finally my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Vaadin Web Application</display-name>
<context-param>
<description>Vaadin production mode</description>
<param-name>productionMode</param-name>
<param-value>false</param-value>
</context-param>
<servlet>
<servlet-name>Vaadin Application Servlet</servlet-name>
<servlet-class>com.vaadin.terminal.gwt.server.ApplicationServlet</servlet-class>
<init-param>
<param-name>application</param-name>
<param-value>vaadinBaas.MyVaadinApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Vaadin Application Servlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
</web-app>
Am I missing something obvious here?
Try annotating MyVaadinApplication with Component annotation. Since MyVaadinApplication is not considered as spring managed class the Autowire didnt work for you. Also you need to load the bean definition xml using ClassPathXmlApplicationContext and try calling getBean(MyVaadinApplication.class) so that all the autowiring happens automatically

Resources