Controller doesn't work with spring - java

I use spring mvc with spring configuration (without xml). And it seems like IDEA doesn't go to controller code. Maybe somewhere path is incorrect so #RequestMapping doesn't work. But i can't understand where exactly.
Here is my Controller
#Controller
public class MainController {
#RequestMapping(value = "/" , method = RequestMethod.GET)
public String home() {
return "index";
}
#RequestMapping(value = "welcome", method = RequestMethod.GET)
public String welcome(Model m){
m.addAttribute("name","lol kkeke");
return "index2";
}
}
WebMvcConfig
#Configuration
#ComponentScan("com.chat")
#EnableWebMvc
public class WebMVCConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/scripts/**").addResourceLocations("/scripts/");
registry.addResourceHandler("/styles/**").addResourceLocations("/styles/");
registry.addResourceHandler("/images/**").addResourceLocations("/images/");
registry.addResourceHandler("/fonts/**").addResourceLocations("/fonts/");
registry.addResourceHandler("/pages/**").addResourceLocations("/views/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index.jsp");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}

So.. I solved a problem. It was in Controller - path. My Idea automatically change path from com.chat.controller to c.c.controller. So i rebuild project structure to com.chat.controller.Controller.class; and com.chat.config.Configuration.class.
Also, i found the next article about similar trouble. May be it will help somebody! How do I map Spring MVC controller to a uri with and without trailing slash?

Related

SpringBoot White page

I just start learning SpringBoot.
I use spring boot build-in tomcat get my spring boot program run. But when I try to visit the page, it gives me a Whitelabel Error Page.
When I start this program, it shows as follow:
I think my program and tomcat start successfully.
This is my start code:
DemoApplication.java
#SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(DemoApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
This is my Controller code:
BookController.java
#Controller
public class BookController {
private IBookService bookService;
public BookController(IBookService bookService) {
this.bookService = bookService;
}
#RequestMapping(value = "/book_list", method = RequestMethod.GET)
public String getAllBook(Model model, HttpSession httpSession, HttpRequest httpRequest) throws Exception {
List<Book> list = bookService.getAllBook();
model.addAttribute("bookList", list);
return "book";
}
}
So if I visit 'localhost:8080/bookstore/book_list', it will find the controller and this controller should help me go to the /WEB-INF/jsp/book.jsp because my WebMvcConfig like following:
WebMvcConfig.java
#Configuration
public class WebMvcConfig {
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
}
But why this is a white page?
This is my program structure:
DemoApplication is in a demo subpackage. The default is that it only scans subpackages of the class annotated with #SpringBootApplication, so it doesn't find any of your components.
Two ways to fix:
Move the class out of the demo package.
This is what Spring Boot demo applications usually do.
Specify the packages to scan:
#SpringBootApplication(scanBasePackages = "com.zx")
Alternatively, use #ComponentScan, same thing:
#SpringBootApplication
#ComponentScan("com.zx")

Unable to resolve static resources in Spring MVC

I know this question has a lot of answers but i cannot solve mine so that is why i decided to put up the question
I want to resolve both jsp and html files. Below is my spring resolver configuration
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix("");
return resolver;
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/WEB-INF/views/static");
}
and controller class is below:
#RequestMapping("/testApi2")
#Controller
public class TestController2
{
#RequestMapping("/showHomePage")
public ModelAndView showHome(){
return new ModelAndView("/static/about.html");
}
}
I have also attached screen shot of my directory structure, it is giving 404 on every request
I think that you should add to your web resolver config class one very special handling configurer:
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
This method enables static resources processing.
After some efforts , thanks to lot of documentation on Spring , i was able to resolve the issue
I found a solution(searched on net) with which we can use both JSP and HTML as views
Forget the question , below are the new settings
Static resources (.css,.js,.jpg) are placed in webapp/assets/
HTML files are in /WEB-INF/static/
Here is my configuration file :
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix("");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**") //
.addResourceLocations("/assets/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
Please note i have used resolver.setSuffix("") both HTML and JSP
HTML code :
<link rel="stylesheet" href="/taxi/assets/css/theme-pink.css" />
Here taxi is the context root , means name of the project
Now if i run the below URL , it will fetch the image or CSS of js
localhost:8080/taxi/assets/css/icons.css

access static html page from jar file using spring

I want to call home.html file present in jar under /WEB-INF/lib using spring.
Below is configuration class
#Configuration
#ComponentScan("com.barclays.mobile.gateway.controller")
#EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter{
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/");
viewResolver.setSuffix(".html");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/component/**").addResourceLocations("classpath:/app/component/*");
registry.addResourceHandler("/assets/**").addResourceLocations("classpath:/app/assets/*");
registry.addResourceHandler("/home/**").addResourceLocations("classpath:/app/*");
}
}
Below is controller:
#Controller
public class StaffController {
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home() {
return "home";
}
}
Please suggest how to do this.?
remove / from /home, I guess that is the problem

#MatrixVariable Spring 3.2 return Null

I'm using Spring 3.2.6 in order to learn the #MatrixVariable feature with a basic example.
I have coded this method to get the matrix variable from the URI :
#RequestMapping(value="/matrix/{paths}", method=RequestMethod.GET)
public ModelAndView MatrixVariableExample(#MatrixVariable Integer age){
ModelAndView mv = new ModelAndView("affichageMatrix");
mv.addObject("age", age);
return mv;
}
I use this URI : localhost:8080/SpringMVC-Maven/matrix/user;age=23
The value returned for the age variable is null, but I it should be 23
Enable Matrix Variables in spring config file:
<mvc:annotation-driven enable-matrix-variables="true"/>
Try to change your code like this:
#RequestMapping(value="/matrix/{paths}", method=RequestMethod.GET)
public ModelAndView MatrixVariableExample(#PathVariable String paths, #MatrixVariable Integer age){
System.out.println(paths); //or do something with it, at your choice
ModelAndView mv = new ModelAndView("affichageMatrix");
mv.addObject("age", age);
return mv;
}
And use URL:
http://localhost:8080/SpringMVC-Maven/matrix/user;age=23
Your variable paths should now contain string user, and age should be 23. I guess you're not allowed to miss path parameters if you have already parametrized your request mapping.
To use matrix variable you have to enable Spring MVC framework to read matrix variable in your application.
You can do it using either XML notation or by java configuration
XML configuration:
By adding below configuration in dispatcher-servlet.xml
<mvc:annotation-driven enable-matrix-variables="true"/>
Java Configuration:
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {AppConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] {"/*"};
}}
#Configuration
#EnableWebMvc
#ComponentScan(basePackages= {"com.springmvc.test"})
public class AppConfig implements WebMvcConfigurer {
#Bean
public InternalResourceViewResolver resolver() {
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper=new UrlPathHelper();
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}}

Spring MVC - Return static page

I'm struggling with trying to return a static web page from a spring MVC controller.
I followed this tutorial: http://www.tutorialspoint.com/spring/spring_static_pages_example.htm and yet it still isn't working.
This is how I defined the configuration (used configuration class):
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan({ "com.my.web.api"})
#ImportResource("classpath:db-context.xml")
public class ApiServletConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/resources/");
internalResourceViewResolver.setSuffix("*.html");
return internalResourceViewResolver;
}
}
The controller method:
#RequestMapping(value = "/{id}/view", method = RequestMethod.GET, produces = "text/html")
#ResponseBody
public String getPostByIdHtml( #PathVariable String id) throws IOException {
return "/resources/Post.html";
}
Under the webapp folder there's a folder named "resources" and under which there's a file "Post.html". What else should I do in order to get this page returned as HTML instead of getting the string "resources/Post.html"?
Thanks for the help.
Please remove the annotation #ResponseBody. Your browser should be redirected to the desired page once the annotation is removed.
This annotation indicates that the value returned by a method in your controller should be bound to the web response body. In your case, you do not need that: you need Spring to render page /resources/Post.html, so no need for this annotation.

Categories