I'm currently new to Spring, and I'm trying to learn the pure java configuration element of it.
I'm able to run my Spring application on Tomcat with the following classes:
Config class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.inka.spring.test.maven.configuration;
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.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
/**
*
* #author User
*/
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.inka.spring.test.maven")
public class HelloWorldConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
Initializer class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.inka.spring.test.maven.configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
*
* #author User
*/
public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {HelloWorldConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
Controller class:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.inka.spring.test.maven.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
*
* #author User
*/
#Controller
#RequestMapping("/")
public class HelloWorldController {
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("greeting", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/helloagain", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
}
This calls a .jsp page that prints the respective messages depending on the path I enter as stated above in the codes.
However, when I try this with weblogic, it doesn't work. All I get is a 403 and a 404 error.
I would have stuck with Tomcat, but we use weblogic at our organisation and I've been instructed to build my application to work with weblogic.
Please, is there some extra configuration I'm supposed to use on weblogic?
Ok, I've finally resolved the issue. Turns out, in your initializer class, no matter what class you extend, you must ALWAYS implement the WebApplicationInitializer class if you intend to deploy on weblogic. You don't have to for Tomcat (don't know about JBoss and the rest), but for weblogic, you MUST implement that class.
So, after changing this:
public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
To this:
public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {
Everything works fine!
For more information, please visit the spring guide.
Related
I am working on a reactjs project and I just did a yarn build and moved the contents into the Java project.
my-project\complete\src\main\resources\static
but when I view the project from the Java site -- localhost:8080 -- I get a ton of 404 errors
logo.a67f8998.png:1 GET http://localhost:8080/static/media/logo.a67f8998.png
registerServiceWorker.js:77 GET http://localhost:8080/service-worker.js 404
-beefeater.78e4414b.jpg:1 GET http://localhost:8080/static/media/-beefeater.78e4414b.jpg 404 ()
For this project I am mostly acting as a frontend dev - Where do I make the required changes to get the routing correct for these files?
my Application.java file looks like this - when I uncomment the code I get told to remove the #overide?
//import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
/**
* Hello world!
*
*/
#SpringBootApplication
public class Application implements CommandLineRunner {
//#Autowired
//private AccountRepository accountRepository;
/**
* #param args
*/
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
public void run(String... arg0) throws Exception {
}
/*
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}*/
}
I've tried to add a config file to sort this out.. do I need to import it in the application.java?
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//#Configuration
#EnableWebMvc
#WebAppConfiguration
public class Configuration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
}
}
You're missing #WebMvcAutoConfiguration annotation I think
Lately I started working on a tomcat web service again.
I hadn't touched it in a couple of weeks, and when I went to try something I'd written, I received a 404 error.
Stumped by what was going on, I eventually decided to just write a new hello world service to see what was going on, but then that 404's too.
I don't recall any updates to Tomcat, or having tweaked any settings, yet I can no longer access any methods I write for anything and it's confusing the hell out of me.
For example, the below classes should mean that http://localhost:8080/HelloWorld/API/Test/ should return a "Hello World" message, however it 404s and I have no idea what's going on.
context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/HelloWorld"/>
Application Config:
package main;
import java.util.Set;
import javax.ws.rs.core.Application;
#javax.ws.rs.ApplicationPath("API")
public class ApplicationConfig extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> resources = new java.util.HashSet<>();
addRestResourceClasses(resources);
return resources;
}
/**
* Do not modify addRestResourceClasses() method.
* It is automatically populated with
* all resources defined in the project.
* If required, comment out calling this method in getClasses().
*/
private void addRestResourceClasses(Set<Class<?>> resources) {
resources.add(main.HWTest.class);
}
}
HWTest:
package main;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.core.MediaType;
#Path("/Test")
public class HWTest {
#Context
private UriInfo context;
/**
* Creates a new instance of HWTest
*/
public HWTest() {
}
/**
* Retrieves representation of an instance of main.HWTest
* #return an instance of java.lang.String
*/
#GET
#Path("/")
#Produces(MediaType.TEXT_PLAIN)
public String getText() {
//TODO return proper representation object
return "Hello world";
}
}
This definitely worked a few weeks ago, so I believe it might be something to do with a setting I accidentally tweaked, but I'm not sure as that wouldn't explain why new projects don't work either.
So, I'm trying to learn Spring Framework, but currently I'm stuck on this problem, for some reason my mappings don't work and when I try to access that address I'm getting a 404 error.
Can someone please clarify what I'm doing wrong (both in usage of spring classes and the source of the problem I have described above)?
I'm configuring spring using the example shown in this video: YouTube Video, the code is basically the same, the only difference is package name and the location of the JSP file (could this be the source of my problem?).
The project was made in IntelliJ Idea and is attached to the following link (Google Drive): Project Link
As my servlet container I'm using Tomcat8 (tried both 9 and 8.5, no cigar).
HomeController.java
package com.demo.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
package com.demo.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by ARTERC on 1/16/2017.
*/
#Controller
public class HomeController {
#RequestMapping("/")
public String home() {
return "home";
}
}
WebInit.java
package com.demo.spring.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Configuration
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
WebConfig.java
package com.demo.spring.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("com.demo.spring")
public class WebConfig extends WebMvcConfigurerAdapter{
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
return resolver;
}
}
home.jsp path: /web/home.jsp
Okay, so I found the solution.
Add war plugin to pom.xml
Fix web resource directory path (was webapp) Image Link
I have this code:
package biz.tugay.springJuly18.config;
/* User: koray#tugay.biz Date: 18/07/15 Time: 15:09 */
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#SuppressWarnings(value = "unused")
public class MyWebAppInnit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfigClass.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ServletConfigClass.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
and the ServletConfig.class
package biz.tugay.springJuly18.config;
/* User: koray#tugay.biz Date: 18/07/15 Time: 15:10 */
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.view.InternalResourceViewResolver;
#Configuration
#ComponentScan(basePackages = "biz.tugay.springJuly18.web")
public class ServletConfigClass {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
}
and finally a Controller:
package biz.tugay.springJuly18.web;
/* User: koray#tugay.biz Date: 18/07/15 Time: 12:53 */
import biz.tugay.springJuly18.service.MyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MyWeb {
#Autowired
private MyService myService;
#RequestMapping("/test")
public ModelAndView helloWorld() {
ModelAndView mv = new ModelAndView();
mv.addObject("message", myService.sayHello());
mv.setViewName("koko");
return mv;
}
}
When I deploy this to Tomcat and go to /test I will be redirected to koko.jsp . So why does this work without #EnableWebMvc?
According to this answer here it should not?
Here is RootConfig.java
package biz.tugay.springJuly18.config;
/* User: koray#tugay.biz Date: 18/07/15 Time: 15:10 */
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
#Configuration
#ComponentScan(basePackages = "biz.tugay.springJuly18.service")
public class RootConfigClass {
}
The DispatcherServlet has two fields
/** List of HandlerMappings used by this servlet */
private List<HandlerMapping> handlerMappings;
/** List of HandlerAdapters used by this servlet */
private List<HandlerAdapter> handlerAdapters;
whose values decide how a request will be handled (among other things). These fields are initialized and populated with values when the DispatcherServlet is initialized by the container. The values come from the context configuration you specify. If your context configuration doesn't provide at least one value of the appropriate type, the DispatcherServlet uses some defaults.
These defaults are included in a file named DispatcherServlet.properties which is in the same package as DispatcherServlet.
For HandlerMapping, the values (class names) are
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
The javadoc of AnnotationMethodHandlerAdapter states
Implementation of the HandlerAdapter interface that maps handler
methods based on HTTP paths, HTTP methods and request parameters
expressed through the RequestMapping annotation.
In other words, this implementation also uses methods annotated with #RequestMapping.
However, AnnotationMethodHandlerAdapter is deprecated
in Spring 3.2 in favor of RequestMappingHandlerAdapter
#EnabledWebMvc instead registers a RequestMappingHandlerAdapter, which is much more sophisticated.
Is it possible in Spring 3.1.1 to configure a view resolver using Java annotations?
I am done with all configurations using Java annotations, but I am stuck at view resolver.
Code
package com;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.*;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#ComponentScan("com")
public class AppConfig
{
{
//Other bean declarations
}
#Bean
public UrlBasedViewResolver urlBasedViewResolver()
{
UrlBasedViewResolver res = new InternalResourceViewResolver();
res.setViewClass(JstlView.class);
res.setPrefix("/WEB-INF/");
res.setSuffix(".jsp");
return res;
}
}
I used this code and ran the application, but it's not returning the appropriate view. However, if I configure a viewresolver in the app-servlet.xml file, it works fine.
Your class should extend WebMvcConfigurerAdapter class. please have a look at below example
#Configuration
#ComponentScan(basePackages="com")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
I tested your scenario with Spring 4.3.4 and it is working ok.
I would suggest double checking packages you scan and that AppConfig is properly provided.
I am attaching all files starting from your AppConfig. Yet it is good to extend WebMvcConfigurerAdapter. The source code attached is not ideal, it s simplistic and only to try to reproduce the problem you have reported.
Starting from AppConfig:
package com;
import org.springframework.context.annotation.*;
import org.springframework.web.servlet.view.*;
#Configuration
#ComponentScan("com")
public class AppConfig {
#Bean
public UrlBasedViewResolver getViewResovler() {
UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver();
urlBasedViewResolver.setViewClass(JstlView.class);
urlBasedViewResolver.setPrefix("/WEB-INF/jsp/");
urlBasedViewResolver.setSuffix(".jsp");
return urlBasedViewResolver;
}
}
Then:
package com;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { AppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
Finally:
package com;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MainController {
#RequestMapping("/")
public ModelAndView asdf() {
return new ModelAndView("ABC");
}
}
The problem with the above is that the DispatcherServlet.initViewResolvers get's called before the bean getViewResolver is defined and it cannot find the bean so it never adds the view resolver.
If you move the bean definition into an xml definition, it get's picked up. For some reason the MvcConfiguration class you have defined does not trigger a DispatcherServlet refresh if there are no ViewResolvers defined in the XML.