Spring MVC xml based config to annotation - java

I am new at Spring and trying to xml based config to annotation basic. I read this tutorial amd coded. It works perfect with xml based config.
MVC Spring CRUD Tutorial
And now I converted all xml based config to annotation but I have a problem. I ried almost everything what I read but I didn't solve this problem.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.ulotrix.spring.controller.PersonController.setPersonService(com.ulotrix.spring.service.PersonService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ulotrix.spring.service.PersonService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
AppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan({ "com.ulotrix.spring.controller" })
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.ulotrix.spring.model");
builder.addProperties(getHibernationProperties());
return builder.buildSessionFactory();
}
private Properties getHibernationProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/deneme_db2");
ds.setUsername("root");
ds.setPassword("xxx");
return ds;
}
#Bean
public HibernateTransactionManager txManger() {
return new HibernateTransactionManager(sessionFactory());
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringMVCInitializer.java
public class SpringMvcInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(AppConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
PersonController.java
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required = true)
#Qualifier(value = "personService")
public void setPersonService(PersonService ps) {
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value = "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p) {
if(p.getId() == 0) {
this.personService.addPerson(p);
}else {
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
#RequestMapping(value = "/remove/{id}")
public String removePerson(#PathVariable("id") int id) {
this.personService.removePerson(id);
return "redirect:/persons";
}
#RequestMapping(value = "/edit/{id}")
public String editPerson(#PathVariable("id") int id, Model model) {
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}

The PersonService is defined in package com.ulotrix.spring.services, so change #ComponentScan({ "com.ulotrix.spring.controller" }) to #ComponentScan({ "com.ulotrix.spring" }) thanks to which spring can discover all the beans defined inside package spring.

Related

Configuration Spring MVC without web.xml

I'm trying to send requests to my RestController, but it's not working, i have
#RestController
#RequestMapping(
value = "/cursos",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public class CursoRestController {
#Autowired
private CursoService cursoService;
#GetMapping
#ResponseStatus(HttpStatus.OK)
public List<Curso> listAll() {
System.out.println("Test");
return cursoService.findAll();
}
#PostMapping
public ResponseEntity<Void> save(#RequestBody Curso curso) {
cursoService.save(curso);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(curso.getId()).toUri();
return ResponseEntity.created(location).build();
}
I'm using Postman to send request, and when i send some request i get 400 error code, with no message or something to tell to me, what's happing, BUT when i try to open the same URL on the browser, I GET THE RESPONSE, i don't if i configured something wrong, i'm using theses classes to config my project
SpringRootConfig
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("br.com.gabriel.restful")
public class SpringRootConfig {
}
SpringInitConfig
public class SpringInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringRootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
SpringJpaConfig
#Configuration
public class SpringJpaConfig {
#Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUrl("jdbc:postgresql://localhost:5432/wildbuild");
ds.setUsername("postgres");
ds.setPassword("admin");
return ds;
}
#Bean
public EntityManagerFactory entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setPackagesToScan("br.com.gabriel.restful.domain");
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setJpaProperties(jpaProperties());
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public JpaTransactionManager jpaTransactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory());
manager.setJpaDialect(new HibernateJpaDialect());
return manager;
}
private Properties jpaProperties(){
Properties props = new Properties();
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "update");
return props;
}
}
My project have this structure:
project structure

Circular dependency while embedding jbpm 7.9 in spring boot 2.0.4

I'm trying to embed jbpm 7.9 in a spring boot project, I've followed the instruction from the [official documentation][1], But instead of using xml configuration as in the document I'm using Spring Java Configuration class. The configuration class is as shown
#Configuration
public class JBPMConfiguration {
#Bean
public PropertiesFactoryBean roleProperties() {
PropertiesFactoryBean bean = new PropertiesFactoryBean();
bean.setLocation(new ClassPathResource("roles.properties"));
return bean;
}
#Bean
public JBossUserGroupCallbackImpl userGroupCallback(Properties roleProperties) {
return new JBossUserGroupCallbackImpl(roleProperties);
}
#Bean
public ClearBPMSecurityIdentityProvider identityProvider() {
return new ClearBPMSecurityIdentityProvider();
}
#Bean
public SpringRuntimeManagerFactoryImpl runtimeManagerFactory(JtaTransactionManager transactionManager,
JBossUserGroupCallbackImpl userGroupCallback) {
SpringRuntimeManagerFactoryImpl springRuntimeManagerFactoryImpl = new SpringRuntimeManagerFactoryImpl();
springRuntimeManagerFactoryImpl.setTransactionManager(transactionManager);
springRuntimeManagerFactoryImpl.setUserGroupCallback(userGroupCallback);
return springRuntimeManagerFactoryImpl;
}
#Bean
public TransactionalCommandService transactionCmdService(EntityManagerFactory entityManagerFactory) {
return new TransactionalCommandService(entityManagerFactory);
}
#Bean(destroyMethod = "close")
public TaskServiceFactoryBean taskService(EntityManagerFactory entityManagerFactory,
JtaTransactionManager transactionManager, UserGroupCallback userGroupCallback) {
TaskServiceFactoryBean taskServiceFactoryBean = new TaskServiceFactoryBean();
taskServiceFactoryBean.setEntityManagerFactory(entityManagerFactory);
taskServiceFactoryBean.setTransactionManager(transactionManager);
taskServiceFactoryBean.setUserGroupCallback(userGroupCallback);
TaskLifeCycleEventListener taskLifeCycleEventListener = new JPATaskLifeCycleEventListener(true);
List<TaskLifeCycleEventListener> list = new ArrayList<>();
list.add(taskLifeCycleEventListener);
taskServiceFactoryBean.setListeners(list);
return taskServiceFactoryBean;
}
#Bean
public BPMN2DataServiceImpl definitionService() {
return new BPMN2DataServiceImpl();
}
#Bean
public RuntimeDataServiceImpl runtimeDataService(TransactionalCommandService transactionCmdService,
ClearBPMSecurityIdentityProvider identityProvider, TaskServiceFactoryBean taskService) throws Exception {
RuntimeDataServiceImpl runtimeDataServiceImpl = new RuntimeDataServiceImpl();
runtimeDataServiceImpl.setCommandService(transactionCmdService);
runtimeDataServiceImpl.setIdentityProvider(identityProvider);
runtimeDataServiceImpl.setTaskService((TaskService) taskService.getObject());
return runtimeDataServiceImpl;
}
#Bean(initMethod = "onInit")
#DependsOn("entityManagerFactory")
public KModuleDeploymentService deploymentService(DefinitionService definitionService,
EntityManagerFactory entityManagerFactory, RuntimeManagerFactory runtimeManagerFactory,
IdentityProvider identityProvider, RuntimeDataService runtimeDataService) {
KModuleDeploymentService kModuleDeploymentService = new KModuleDeploymentService();
kModuleDeploymentService.setBpmn2Service(definitionService);
kModuleDeploymentService.setEmf(entityManagerFactory);
kModuleDeploymentService.setManagerFactory(runtimeManagerFactory);
kModuleDeploymentService.setIdentityProvider(identityProvider);
kModuleDeploymentService.setRuntimeDataService(runtimeDataService);
return kModuleDeploymentService;
}
#Bean
#DependsOn(value = { "deploymentService" })
public ProcessServiceImpl processService(RuntimeDataService runtimeDataService,
DeploymentService deploymentService) {
ProcessServiceImpl processService = new ProcessServiceImpl();
processService.setDataService(runtimeDataService);
processService.setDeploymentService(deploymentService);
return processService;
}
#Bean
#DependsOn(value = { "deploymentService" })
public UserTaskServiceImpl userTaskService(RuntimeDataService runtimeDataService,
DeploymentService deploymentService) {
UserTaskServiceImpl userTaskService = new UserTaskServiceImpl();
userTaskService.setDataService(runtimeDataService);
userTaskService.setDeploymentService(deploymentService);
return userTaskService;
}
#Bean
#DependsOn(value = { "deploymentServices"})
public MethodInvokingFactoryBean data(RuntimeDataService runtimeDataService, DeploymentService deploymentService) {
MethodInvokingFactoryBean methodInvokingFactoryBean = new MethodInvokingFactoryBean();
methodInvokingFactoryBean.setTargetObject(deploymentService);
methodInvokingFactoryBean.setTargetMethod("addListener");
ArrayList<RuntimeDataService> arrayList = new ArrayList<>();
arrayList.add(runtimeDataService);
methodInvokingFactoryBean.setArguments(arrayList);
return methodInvokingFactoryBean;
}
}
The server is not starting, I'm getting the below error, Please help
***************************
APPLICATION FAILED TO START
***************************
Description:
The dependencies of some of the beans in the application context form a cycle:
userGroupCallback defined in class path resource [tv/clearhub/bpm/configuration/JBPMConfiguration.class]
┌─────┐
| taskService defined in class path resource [tv/clearhub/bpm/configuration/JBPMConfiguration.class]
↑ ↓
| data defined in class path resource [tv/clearhub/bpm/configuration/JBPMConfiguration.class]
↑ ↓
| runtimeDataService defined in class path resource [tv/clearhub/bpm/configuration/JBPMConfiguration.class]
└─────┘
Please remove all #DependsOn and (initMethod = "onInit").
My demo works fine, but they are no arguments for processService as runtimeDataService and deploymentService are in the same class, same to other metheds.
Check this source code: https://github.com/kiegroup/jbpm/blob/master/jbpm-services/jbpm-kie-services/src/main/java/org/jbpm/kie/services/impl/utils/DefaultKieServiceConfigurator.java
org.jbpm.kie.services.impl.utils.DefaultKieServiceConfigurator.java#configureServices

NPE Spring Webflow with Apache Tiles 3

I have a spring project with MVC and Webflow.
I'm getting a NPE when trying to render a tiles definition specified as a view of a view-state in a webflow.
My WebflowConfig :
#Configuration
public class WebFlowConfig extends AbstractFlowConfiguration {
#Autowired
private List<ViewResolver> viewResolvers;
#Bean
public FlowExecutor flowExecutor() {
return getFlowExecutorBuilder(flowRegistry())
.addFlowExecutionListener(new SecurityFlowExecutionListener(), "*")
.build();
}
#Bean
public FlowDefinitionRegistry flowRegistry() {
return getFlowDefinitionRegistryBuilder(flowBuilderServices())
.setBasePath("/WEB-INF/flows")
.addFlowLocationPattern("/*.xml").build();
}
#Bean
public FlowBuilderServices flowBuilderServices() {
return getFlowBuilderServicesBuilder()
.setViewFactoryCreator(mvcViewFactoryCreator())
.setDevelopmentMode(true)
.build();
}
#Bean
public MvcViewFactoryCreator mvcViewFactoryCreator() {
MvcViewFactoryCreator factoryCreator = new MvcViewFactoryCreator();
factoryCreator.setViewResolvers(viewResolvers);
factoryCreator.setUseSpringBeanBinding(true);
return factoryCreator;
}
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
My WebMvcConfig:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "py.com.bbva.guepardo")
#Import(WebFlowConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(viewResolver());
}
#Bean
public ViewResolver viewResolver(){
TilesViewResolver viewResolver = new TilesViewResolver();
viewResolver.setOrder(2);
viewResolver.setViewClass(TilesView.class);
return viewResolver;
}
#Bean
#Autowired
public FlowHandlerMapping flowHandlerMapping(WebFlowConfig webFlowConfig) {
FlowHandlerMapping handlerMapping = new FlowHandlerMapping();
handlerMapping.setOrder(-1);
handlerMapping.setFlowRegistry(webFlowConfig.flowRegistry());
return handlerMapping;
}
#Bean
#Autowired
public FlowHandlerAdapter flowHandlerAdapter(WebFlowConfig webFlowConfig) {
FlowHandlerAdapter handlerAdapter = new FlowHandlerAdapter();
handlerAdapter.setFlowExecutor(webFlowConfig.flowExecutor());
handlerAdapter.setSaveOutputToFlashScopeOnRedirect(true);
return handlerAdapter;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer tilesConfigurer = new TilesConfigurer();
tilesConfigurer.setDefinitions(new String[] { "/WEB-INF/layouts/*.xml", "/WEB-INF/views/**/views.xml" });
tilesConfigurer.setCheckRefresh(true);
return tilesConfigurer;
}
The webflow that i'm trying to start has a simple view-state pointing to a tiles definition :
<view-state id="home" view="default_login" >
</view-state>
That same definition its working with a #RequestMapping restful web service in a #Controller class, so the mvc view render works, but it's not working from a webflow definition. Any ideas?
Console error log :
Caused by: org.springframework.webflow.execution.FlowExecutionException: Exception thrown in state 'home' of flow 'home'
at org.springframework.webflow.engine.impl.FlowExecutionImpl.wrap(FlowExecutionImpl.java:573)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:263)
at org.springframework.webflow.executor.FlowExecutorImpl.resumeExecution(FlowExecutorImpl.java:169)
at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:253)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
... 69 more
Caused by: java.lang.IllegalStateException: Exception occurred rendering view null
at org.springframework.webflow.mvc.view.AbstractMvcView.render(AbstractMvcView.java:200)
at org.springframework.webflow.engine.ViewState.render(ViewState.java:293)
at org.springframework.webflow.engine.ViewState.refresh(ViewState.java:242)
at org.springframework.webflow.engine.ViewState.resume(ViewState.java:220)
at org.springframework.webflow.engine.Flow.resume(Flow.java:537)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.resume(FlowExecutionImpl.java:259)
... 74 more
Caused by: java.lang.NullPointerException
at org.springframework.webflow.mvc.servlet.ServletMvcView.doRender(ServletMvcView.java:55)
at org.springframework.webflow.mvc.view.AbstractMvcView.render(AbstractMvcView.java:196)
... 79 more

Getting correct instance using #Autowired

I'm facing some issues when I run and hit my rest service, I saw that my service instance got a #Proxy value. Below you can see the classes that I have:
Initializer class:
public class AllureWebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
createDispatcherServlet(servletContext);
initializeListener(servletContext);
}
private void initializeListener(ServletContext servletContext) {
AnnotationConfigWebApplicationContext rootContext = createContext();
servletContext.addListener(new ContextLoaderListener(rootContext));
}
private void createDispatcherServlet(final ServletContext context) {
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(AllureWebConfig.class);
ServletRegistration.Dynamic dispatcher = context.addServlet(AllureWebConstants.DISPATCHER, new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping(AllureWebConstants.SLASH);
}
private AnnotationConfigWebApplicationContext createContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AllureWebConfig.class);
return context;
}
}
Config class:
#Configuration
#Import(AllureServiceConfig.class)
#ComponentScan(basePackages = {"com.allure.events.web.controller"})
#EnableWebMvc
public class AllureWebConfig extends WebMvcConfigurerAdapter {
#Autowired
private ApplicationContextProvider applicationContextProvider;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(AllureWebConstants.RESOURCES_DOUBLE_WILDCARD)
.addResourceLocations(AllureWebConstants.RESOURCES);
}
#Bean
public ApplicationContextProvider applicationContextProvider() {
return applicationContextProvider;
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource;
messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:META-INF/web/resources/release");
messageSource.setUseCodeAsDefaultMessage(true);
return messageSource;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
converter.setObjectMapper(objectMapper);
converters.add(converter);
super.configureMessageConverters(converters);
}
}
Controller class:
#Controller
public class SupplierEndpoint extends AllureEndpoint {
#Autowired
SupplierService supplierService;
#RequestMapping(value = AllureWebConstants.SUPPLIERS, method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<Supplier> getSuppliers() {
List<Supplier> suppliers = getSuppliersList(supplierService.getSuppliers());
return suppliers;
}
}
Service interface
public interface SupplierService {
public List<SupplierDto> getSuppliers();
}
Service Impl
#Service
public class SupplierServiceImpl implements SupplierService {
#Autowired
private SupplierMapper supplierMapper;
#Autowired
private SupplierDtoHelper supplierHelper;
#Override
#Transactional
public List<SupplierDto> getSuppliers() {
List<Supplier> suppliers = supplierMapper.getSuppliers();
List<SupplierDto> dtos = new ArrayList<SupplierDto>();
for (Supplier supplier : suppliers) {
dtos.add(supplierHelper.convertEntityToDto(supplier));
}
return dtos;
}
}
if I debug, I see that the instance value is :
supplierService - $Proxy28
|
-> h = JdkDynamicAopProxy
Can someone guide me, please?
Regards,
Edgardo Quiroz
It's not an issue when you work with Spring.
Spring Framework uses Proxy to make the different features possible.
Here you have a Transactional Annotation and proxy is been used to implement it.

Spring JavaConfig is not catching PageNotFound?

I am trying to setup a page not found catch in my Spring WebMVCConfig bit its not working..
here is my config:
#Configuration
#EnableWebMvc
#PropertySource("classpath:application.properties")
#Import(DatabaseConfig.class)
#ImportResource("/WEB-INF/spring/applicationContext.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {
private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";
private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);
#Autowired
Environment env;
#Bean
public ViewResolver resolver() {
UrlBasedViewResolver url = new UrlBasedViewResolver();
url.setPrefix("/WEB-INF/view/");
url.setViewClass(JstlView.class);
url.setSuffix(".jsp");
return url;
}
#Bean(name = "messageSource")
public MessageSource configureMessageSource() {
logger.debug("setting up message source");
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver lr = new SessionLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("setting up resource handlers");
registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
logger.debug("configureDefaultServletHandling");
configurer.enable();
}
#Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
public #Bean HandlerExceptionResolver exceptionResolver() {
Properties mappings = new Properties();
mappings.put("org.springframework.web.servlet.PageNotFound", "404");
mappings.put(DataAccessException.class.getName(), "dataAccessFailure");
mappings.put(TransactionException.class.getName(), "dataAccessFailure");
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
resolver.setExceptionMappings(mappings);
return resolver;
}
#Bean
public DefaultAnnotationHandlerMapping mapping() {
DefaultAnnotationHandlerMapping m = new DefaultAnnotationHandlerMapping();
m.setDetectHandlersInAncestorContexts(true);
return m;
}
}
now if I put in a URL that is not mapped I would think it would goto my 404.jsp page?
The way to configure a custom error page (for 404 or any other error code) is in the web.xml...
<error-page>
<error-code>404</error-code>
<location>/my-custom-page-not-found.html</location>
</error-page>
The url can be a static page, a custom jsp or even a Spring controller.
You can use #ExceptionHandler annotated method or #ControllerAdvice class.
Several methods are described in this post of the forum.
Alternatively, you can also refer Spring Docs - Handling exceptions section.

Categories

Resources