I am creating basic REST application. I am getting requested resource not available when trying to run on Tomcat server. I am using Java configuration (no xml) in the project. I have tried all possible solutions available on Stackoverflow, none of them worked for me. I have been trying for almost 2 hours. I need help to solve this error.
HTTP Status 404 - The requested resource (/spring-rest-demo/test/hello) is not available
DemoRestController
//imports
#RestController
#RequestMapping("/test")
public class DemoRestController {
// add code for the "/hello" endpoint
#GetMapping("/hello")
public String sayHello() {
return "Hello World!";
}
}
MySpringMvcDispatcherServletInitializer
//imports
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { DemoAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
DemoAppConfig
//imports
#Configuration
#EnableWebMvc
#ComponentScan("com.springdemo")
public class DemoAppConfig implements WebMvcConfigurer {
}
Related
everyone.
I am trying to create a Spring application, using Hibernate.
The application have not been created with front-end part, only the entities, services, dao and rest controllers.
When I run the application (I am using Eclipse as IDE and WebSphere - I need to use this configuration) and try to access the URL of the app, I receive 404 Not found.
I also ran the application into debug mode with a breakpoint before the returning ResponseEntity of the request and with a print statement for the entity that I am trying to access (a user, for example). Whenever I do this, I try to access the URL, I receive in console application the message that I wanted to print and the entity from the DB. Also, every layer of the application is created in a Maven module.
Any ideas what I am doing wrong?
This is my UserController class:
import x.stm.entity.User;
import x.stm.service.UserService;
#Controller
public class UserController {
#Autowired
private UserService userService;
/*---Add new user---*/
#RequestMapping(path={"/user"}, method = RequestMethod.POST)
public ResponseEntity<?> save(#RequestBody User user) {
userService.addUser(user);
return ResponseEntity.ok().body("User was added" );
}
// ---Get a user by id---
#RequestMapping(path={"/user/{id}"}, method = RequestMethod.GET)
public ResponseEntity<User> get(#PathVariable("id") int id) {
User user = userService.getUserById(id);
System.out.println(user);
return ResponseEntity.ok().body(user);
}
}
And this is application configuration and initializer:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {
"x.stm.rs.controller" })
public class RestApplicationConfig extends WebMvcConfigurerAdapter {
//
}
public class RestApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {HibernateConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { RestApplicationConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
I have a working spring mvc project. I want to log each request through my controllers with using AspectJ. The relevant code:
The Controller: (in package hu.freetime.controller)
#Controller
#RequestMapping("/")
public class BaseControllerImpl {
#RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
return "index";
}
}
The Aspect:
#Aspect
public class ControllerAspectImpl {
Logger logger = LoggerFactory.getLogger(ControllerAspectImpl.class);
#Pointcut("execution(public * hu.freetime.controller.BaseControllerImpl.*(..))")
public void logController() {
}
#Around("logController()")
public void log(final ProceedingJoinPoint pjp) {
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
logger.info("Calling Controller method: " + method.getName() + "()");
try {
pjp.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
}
}
The WebAppInitializer:
public class CashflowWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
The WebConfig class:
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
#ComponentScan(basePackages = { "hu.freetime.controller", "hu.freetime.aspect" })
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Bean
public ControllerAspectImpl getControllerAspect() {
return new ControllerAspectImpl();
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
The problem is, that only one of the two components is working. If I "turn off" the AOP, the MVC works perfect, but when i "turn on", and I want to go to the main page, I get this error:
HTTP Status 404 - .../WEB-INF/views/.jsp
The requested resource is not available.
The strange thing is that it wants to map the ".jsp" instead of "index.jsp", as I wrote in the Controller's index() method. I debugged at runtime, and it did stop at the controller method.
How can I make it work?
Your around advice does not return the result of pjp.proceed(). That is the return value of the advised method and must be returned by the advice! Otherwise you are turning the advised method into a void as well.
public **Object** log(final ProceedingJoinPoint pjp) {
...
try {
**return** pjp.proceed(); <<< !
} catch (Throwable e) {
e.printStackTrace();
}
}
Use below code it will work
#Pointcut("execution(public * hu.freetime.*(..))")
I want to process the request with the controller without any logic inside only to return html page. Here the class with configurations and starter class:
#Configuration
#EnableWebMvc
public class MVCConfig extends WebMvcConfigurerAdapter {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/webapp/");
resolver.setSuffix(".html");
return resolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("NewPage");
}
}
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { MVCConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Apparently that's not enough to do it because when trying to get the page in browser I recieve 404 error.
What do I must to add or change to make it work?
Just to remind you that except the configuration must be complicated,u also need to publish your project as a war and deploy to Tomcat or whatever.
(how to package project as a war,such as maven,use the command "package")
Hope that will help.
I've been googling for the last 2 days and still can't figure out why it wont expose the SOAP web service. It works when I run it locally using Tomcat and Spring Boot. In the jboss-deployment-structure, jpa, javaee-api and webservices has been excluded. Also, there are no exceptions in sysout or logs. Only the message specified further down (HTTP 405). Even checked through TRACE logs.
JBoss Version: 6.4.4 (or 6.4.0)
Spring Boot: 1.3.0
CXF: 3.0.4
Spring MVC: From Spring Boot parent
I get this message:
HTTP Status 405 - Request method 'POST' not supported.
When debugging, I placed a breakpoint in class: DispatcherServlet, which then in getHandlerAdapter returned HttpRequestHandlerAdapter. Further along, it calls the HttpRequestHandlerAdapter.handle which again calls handleRequest on a WebContentGenerator. This only supports GET or HEAD requests.
Any ideas?
Code:
#Configuration
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {
ApplicationConfig.class
};
}
#Override
protected String[] getServletMappings() {
return new String[] {
"/*"
};
}
}
#Configuration
public class ApplicationServletInitializer extends SpringBootServletInitializer {
}
#Configuration
#EnableAutoConfiguration
#Import({
RepositoryConfig.class,
WebConfig.class,
WsProviderConfig.class
})
public class ApplicationConfig {
}
#Configuration
#EnableConfigurationProperties
public class WebConfig {
#Bean
public SelftestController selftestController() {
return new SelftestController();
}
}
#Configuration
public class WsProviderConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(WsProviderConfig.class);
#Autowired
private ApplicationContext context;
#Bean
ServletRegistrationBean messageDispatcherServlet() {
ServletRegistrationBean bean = new ServletRegistrationBean(new CXFServlet(), "/soap/*");
bean.setLoadOnStartup(1);
return bean;
}
#Bean(name = Bus.DEFAULT_BUS_ID)
Bus bus() {
SpringBus bus = new SpringBus();
bus.getFeatures().addAll(Arrays.asList(new WSAddressingFeature(), new LoggingFeature()));
return bus;
}
#Bean
PlayerServiceV1 defaultPlayerService() {
return new DefaultPlayerService();
}
#PostConstruct
void publishWebServices() {
LOGGER.info("Publishing WebServices");
DefaultPlayerService defaultPlayerService = context.getBean(DefaultPlayerService.class);
Bus bus = context.getBean(Bus.DEFAULT_BUS_ID, Bus.class);
EndpointImpl endpoint = new EndpointImpl(bus, defaultPlayerService);
endpoint.publish("/test/players");
}
}
I have searched quite a bit on this forum and have not been able to find an answer to this question.
I need to protect my RestServices with Basic Authorization. My SecurityConfig class is shown below and loads correctly. The log statements are displayed when the application is loaded into Websphere
#EnableWebMvcSecurity
#Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger LOG = LoggerFactory
.getLogger(WebSecurityConfigurerAdapter.class);
#Autowired
AppUserAuthService auas;
#Autowired
AuthenticationProviderImpl auai;
#Autowired
protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
LOG.debug("getting into configureGlobal");
LOG.debug(auas.toString());
LOG.debug(auai.toString());
auth
.userDetailsService(auas)
.and()
.authenticationProvider(auai) ;
}
#Override
public void configure(HttpSecurity http) {
LOG.debug("getting into configure");
try {
http.httpBasic().and()
.authorizeRequests().anyRequest().authenticated();
http.csrf()
.disable()
.antMatcher("/service/**") ;
} catch (Exception e) {
throw new SecurityWrapperException("configure() blowing up when trying to match /service/**" ,e);
}
}
My REST calls do not get checked with basic authentication though because I have not been able to figure out how to hook it up to the Servlet Initializer.
The problem is that all of the below config class wiring is done in various ApplicationContext.xml files. Whereas it appears I need to override the methods below. My question is do I have to convert everything over to JavaConfiguration or can I reference the appropriate classes that the application context files are using... and if so, what are their names?
So for instance I know there is some "RootConfig".class that the getRootConfigClasses method below needs
`public class MvcWebApplicationInitializers
extends
AbstractAnnotationConfigDispatcherServletInitializer {`enter code here`
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class[] { SecurityConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return null;
}`
I would like to return the correct classes that the ApplicationContext.xmls populate. Obviously returning null for these methods is not a good thing. Is it reasonable to mix the xml with JavaConfiguration in general?
From the documentation
In a Servlet 3.0+ environment, you have the option of configuring the
Servlet container programmatically as an alternative or in combination
with a web.xml file. Below is an example of registering a
DispatcherServlet:
import org.springframework.web.WebApplicationInitializer;
public class MyWebApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) {
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext.setConfigLocation("/WEB-INF/spring/dispatcher-config.xml");
ServletRegistration.Dynamic registration = container.addServlet("dispatcher", new DispatcherServlet(appContext));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
So you can still use xml dispatcher configuration IMO