I'm trying to run elementary spring-4 web-mvc application without xml configuration at all. I've looked spring documentation and examples, but it didn't work for me.
My controller:
package com.nikolay.exam.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class HomeController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
#ResponseBody
public String home() {
return "Hello world!";
}
}
AppConfig:
package com.nikolay.exam.config;
import org.springframework.context.annotation.Configuration;
#Configuration
public class AppConfig {
}
WebConfig:
package com.nikolay.exam.config;
import com.nikolay.exam.controller.HomeController;
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.WebMvcConfigurerAdapter;
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public HomeController homeController() {
return new HomeController();
}
}
And WebInitializer:
package com.nikolay.exam.config;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
root.setConfigLocation("com.nikolay.exam.config");
servletContext.addListener(new ContextLoaderListener(root));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(root));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
But when I run my application on tomcat I receive an error:
14-Feb-2015 11:35:29.825 WARNING [http-nio-8080-exec-1] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/home/] in DispatcherServlet with name 'dispatcher'
14-Feb-2015 11:35:32.766 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory /home/nikolay/apache-tomcat-8.0.9/webapps/manager
14-Feb-2015 11:35:32.904 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory /home/nikolay/apache-tomcat-8.0.9/webapps/manager has finished in 136 ms
14-Feb-2015 11:35:34.888 WARNING [http-nio-8080-exec-3] org.springframework.web.servlet.PageNotFound.noHandlerFound No mapping found for HTTP request with URI [/home/] in DispatcherServlet with name 'dispatcher'
I think it's the way you register your config class that is not correct.
Try using the AnnotationConfigWebApplicationContext#register instead.
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(WebConfig.class);
Probably you need to change
dispatcher.addMapping("/*");
to
dispatcher.addMapping("/");
Related
Main Application Class: (It was going to be using JSP but realized the trouble with Spring Boot):
package com.MBS.Consulting.jsp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
#Configuration
#SpringBootApplication(scanBasePackages="com.MBS.Consulting.jsp")
public class SampleWebJspApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SampleWebJspApplication.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleWebJspApplication.class, args);
}
}
WelcomeController - In sub folder of main class (this controller is accessible):
package com.MBS.Consulting.jsp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class WelcomeController {
#GetMapping("/")
public String index() {
return "static/index";
}
#GetMapping("/Home")
public String welcome() {
return "Welcome/welcome";
}
#GetMapping("/ContactUs")
public String contactUs() {
return"Welcome/contact_Us";
}
#GetMapping("/AboutUs")
public String aboutUs() {
return "Welcome/about_us";
}
}
CustomerController - Does not even show that it is called with AOP. The package name is the same as the last controller. I do need to login using Spring Security to reach this page. It allows me to login and then gives me 404.
package com.MBS.Consulting.jsp.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.MBS.Consulting.jsp.entity.Customers;
import com.MBS.Consulting.jsp.entity.Users;
import com.MBS.Consulting.jsp.services.CustomersService;
#Controller
#RequestMapping("/Customer")
public class CustomerController {
#Autowired
private CustomersService customerService;
#GetMapping("/Home")
public String customerHome() {
return "Customer/Customer_Home";
}
}
Security config:
Not sure if I really need this or not but added it just to make sure that it couldn't be causing the problem.
package com.MBS.Consulting.jsp.config;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.DelegatingPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.Pbkdf2PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
#Configuration
#EnableWebSecurity
public class DemoSecurityConfig {
// add a reference to our security data source
#Autowired
#Qualifier("securityDataSource")
private DataSource securityDataSource;
#Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests((auth) -> {
try {
auth
.antMatchers("/Admin/**").hasRole("ADMIN")
.antMatchers("/Billing/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Contacts/**").hasAnyRole("ADMIN", "EMPLOYEE")
.antMatchers("/Customer/**").hasAnyRole("ADMIN", "CUSTOMER")
.antMatchers("/Order/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Plan/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Services/**").hasAnyRole("ADMIN", "CUSTOMER", "EMPLOYEE")
.antMatchers("/Welcome", "/Login").permitAll()
.and()
.formLogin()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling()
.accessDeniedPage("/access-denied");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
)
.httpBasic();
return http.build();
}
}
Project structure:
I hope the image shows up due just to show the project structure and that I believe the controllers are in the correct location to not be a problem for Spring Boot.
In the logs for console I get no information at all when visit CustomerController, but I do get a 404 Error. The web address I visit is http://localhost:8080/Customer/Home to try to call CustomerController. I am unsure what will cause this and if someone could explain what I did wrong.
I did search on it and I was going to try and configure the dispatcher servlet but it should of been auto configured. I believe if it reaching one it should be able to reach the other if it is the same folder. Also I understand the it needs to be in the sub folder of the main class. Finally I checked to see if it was the mapped right since I used folders in the template folder.
While mappings were correct and the project structure is correct it was unable to reach controllers due to spring security. The security FilterChain in the screen shot is missing two asterisks on the permit all controllers.
this:
.antMatchers("/","/Welcome", "/Login").permitAll()
should be:
.antMatchers("/**","/Welcome/**", "/Login/**").permitAll()
I have a Spring boot maven project with SymetricDS. When I start the application in embedded mode, even if I have a Tomcat with Spring boot, it is looking for Jetty.
SymmetricWebServer node = new SymmetricWebServer("server.properties");
<dependency>
<groupId>org.jumpmind.symmetric</groupId>
<artifactId>symmetric-server</artifactId>
<version>3.5.19</version>
</dependency>
Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/eclipse/jetty/server/bio/SocketConnector
Why is this? Why are the dependencies not downloaded with symetric-server?
The maven dependency on Jetty is "provided" because symmetric-server can be built to be a war that can be deployed to any number of web servers. Here is the essence of how I would embed SymmetricDS in Spring Boot using Spring Boot's provided web container.
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.web.ServerSymmetricEngine;
import org.jumpmind.symmetric.web.SymmetricEngineHolder;
import org.jumpmind.symmetric.web.SymmetricServlet;
import org.jumpmind.symmetric.web.WebConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.ServletContext;
import javax.sql.DataSource;
import java.util.Properties;
#Configuration
public class SymDSModule implements ApplicationListener<ApplicationReadyEvent> {
#Autowired
ServletContext servletContext;
#Autowired
DataSource dataSource;
#Autowired
ApplicationContext applicationContext;
#Override
final public void onApplicationEvent(ApplicationReadyEvent event) {
SymmetricEngineHolder holder = new SymmetricEngineHolder();
Properties properties = new Properties();
properties.put(ParameterConstants.DATA_LOADER_IGNORE_MISSING_TABLES, "true");
properties.put(ParameterConstants.TRIGGER_CREATE_BEFORE_INITIAL_LOAD, "false");
properties.put(ParameterConstants.AUTO_RELOAD_ENABLED, "true");
properties.put(ParameterConstants.AUTO_REGISTER_ENABLED, "true");
ServerSymmetricEngine serverEngine = new ServerSymmetricEngine(dataSource, applicationContext, properties, false, holder);
holder.getEngines().put(properties.getProperty(ParameterConstants.EXTERNAL_ID), serverEngine);
holder.setAutoStart(false);
servletContext.setAttribute(WebConstants.ATTR_ENGINE_HOLDER, holder);
serverEngine.setup();
serverEngine.start();
}
#Bean
public ServletRegistrationBean<SymmetricServlet> symServlet() {
ServletRegistrationBean<SymmetricServlet> bean = new ServletRegistrationBean<>(new SymmetricServlet(), "/sync");
bean.setLoadOnStartup(1);
return bean;
}
}
I'm new to Spring Boot and currently stuck. I followed this (https://github.com/AppDirect/service-integration-sdk/wiki) Tutorial, as I want to implement an application that integrates itself into AppDirect. In the log I can see that the endpoints get created and mapped:
2018-10-29 16:32:48.898 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/v1/integration/processEvent],methods=[GET],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<com.appdirect.sdk.appmarket.events.APIResult> com.appdirect.sdk.appmarket.events.AppmarketEventController.processEvent(javax.servlet.http.HttpServletRequest,java.lang.String)
But when I try to access the endpoint (http://localhost:8080/api/v1/integration/processEvent) with Browser or Http-Requester I get the following response:
{timestamp":"2018-10-29T08:50:13.252+0000","status":403,"error":"Forbidden","message":"Access Denied","path":"/api/v1/integration/processEvent"}
My application.yml looks like this:
connector.allowed.credentials: very-secure:password
server:
use-forward-headers: true
tomcat:
remote_ip_header: x-forwarded-for
endpoints:
enabled: true
info:
enabled: true
sensitive: false
health:
enabled: true
sensitive: false
time-to-live: 5000
info:
build:
name: #project.name#
description: #project.description#
version: #project.version#
This is my Application.java:
package de.....;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.http.MediaType;
import org.springframework.http.converter.FormHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
public class Application extends WebMvcConfigurerAdapter {
public static void main(String... args) {
SpringApplication.run(RootConfiguration.class, args);
}
/**
* Hack to make Spring Boot #Controller annotated classed to recognize the 'x-www-form-urlencoded' media type
*
* #param converters
*/
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FormHttpMessageConverter converter = new FormHttpMessageConverter();
MediaType mediaType = new MediaType("application", "x-www-form-urlencoded", Charset.forName("UTF-8"));
converter.setSupportedMediaTypes(Collections.singletonList(mediaType));
converters.add(converter);
super.configureMessageConverters(converters);
}
}
And this is the RootConfiguration.java:
package de.....;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.appdirect.sdk.ConnectorSdkConfiguration;
import com.appdirect.sdk.appmarket.DeveloperSpecificAppmarketCredentialsSupplier;
import com.appdirect.sdk.credentials.StringBackedCredentialsSupplier;
import de.....;
#Configuration
#Import({
ConnectorSdkConfiguration.class,
EventHandlersConfiguration.class
})
#EnableAutoConfiguration
public class RootConfiguration {
#Bean
public DeveloperSpecificAppmarketCredentialsSupplier environmentCredentialsSupplier(#Value("${connector.allowed.credentials}") String allowedCredentials) {
return new StringBackedCredentialsSupplier(allowedCredentials);
}
}
Any help is appreciated as intensive googleing didn't help.
Thanks in advance.
Adding the following class and registering it in Application.java solved my problem:
package de.......;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
#Order(1)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.authorizeRequests().antMatchers("/").permitAll();
}
}
I am working on Spring Project and am I am trying to prevent URL Parameters for Session Tracking programmatically. This is my code
import org.auctions.Config.MvcConfig;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import web.SessionListenerWithMetrics;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.SessionTrackingMode;
import java.util.EnumSet;
public class SecurityWebApplicationInitializer implements ServletContextInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(MvcConfig.class);
servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
servletContext.addListener(SessionListenerWithMetrics.class);
rootContext.setServletContext(servletContext);
ServletRegistration.Dynamic dispatcher =
servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
**My question** is, are there any other approaches to do this programmatically. I am not sure if this a proper way,
Can someone help me to put this line of code in the right place
servletContext.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE));
If you change your mind about having to be programmatically, in application.properties:
server.servlet.session.tracking-modes=cookie
Done.
You could specify the session tracking mode in web.xml
<web-app>
....other stuff
<session-config>
<tracking-mode>COOKIE</tracking-mode>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
This will disable url rewriting by the server
When I try to go to link http://localhost:8080/ I get "HTTP Status 404", I use Tomcat 7.0.47, and I get the following error : The requested resource is not available.
WebConfig.Java
package config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#EnableWebMvc
#Configuration
#ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/static/js/**")
.addResourceLocations("/resources/static/js/");
registry.addResourceHandler("/resources/static/css/**")
.addResourceLocations("/resources/static/css/");
registry.addResourceHandler("/resources/static/views/**")
.addResourceLocations("/resources/static/views/");
registry.addResourceHandler("/resources/static/**")
.addResourceLocations("/resources/static/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("/webjars/");
}
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebAppInitalizer.Java
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class WebAppInitializer implements WebApplicationInitializer {
private static final String CONFIG_LOCATION = "config";
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
System.out.println("***** Initializing Application for " + servletContext.getServerInfo() + " *****");
// Create ApplicationContext
AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
applicationContext.setConfigLocation(CONFIG_LOCATION);
// Add the servlet mapping manually and make it initialize automatically
DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("mvc-dispatcher", dispatcherServlet);
servlet.addMapping("/");
servlet.setAsyncSupported(true);
servlet.setLoadOnStartup(1);
}
}
MainController.Java
package controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class MainController {
#RequestMapping("/")
public String homepage(){
return "homepage";
}
}
My project has the following structure :
try to add this #AnnotationDrivenConfig on top of WebConfig and change this #ComponentScan with this #ComponentScan("controller")
Try to add some text into your requestMapping example:
#RequestMapping("/homePage")
and then go to http://localhost:8080/homePage