My linux world » Java Spring – Quick start

Java Spring - Quick start


Contents

Dependencies

If you use maven, add this to your pom.xml :

<!-- spring boot -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>		    
</dependency>
 
<!-- jstl -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
</dependency>

Configuration

MainConfig.java

This file will tell spring what packages to scan:

@Configuration
@ComponentScan(basePackages = "net.rabahi.spring")
public class MainConfig {
 
}

WebConfig.java

This implementation replace the WEB-INF/web.xml file.

public class WebConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
 
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getRootConfigClasses()
	 */
	@Override
	protected Class<?>[] getRootConfigClasses() {
		return new Class<?>[] { MainConfig.class, WebMvcConfig.class};
	}
 
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer#getServletConfigClasses()
	 */
	@Override
	protected Class<?>[] getServletConfigClasses() {
		return null;
	}
 
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletMappings()
	 */
	@Override
	protected String[] getServletMappings() {
		return new String[] { "/" };
	}
 
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.support.AbstractDispatcherServletInitializer#getServletFilters()
	 */
	@Override
    protected Filter[] getServletFilters() {
 
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
 
        return new Filter[] { characterEncodingFilter};
    }
 
}

WebMvcConfig.java

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
 
 
	@Bean
	public ViewResolver viewResolver() {
		UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
		viewResolver.setViewClass(JstlView.class);
		viewResolver.setPrefix("/WEB-INF/jsp/");
		viewResolver.setSuffix(".jsp");
		return viewResolver;
	}	
 
}

Controller

When user request in the navbar ‘/helloworld’, the following method is fired:

@Controller
@RequestMapping("/")
public class HelloWorldController {
 
	@RequestMapping("/helloworld")
	public ModelAndView helloworld() {
		String message = "Hello world from spring controller !";
		return new ModelAndView("helloworld", "message", message);
	}
 
}

It will request WEB-INF/jsp/helloworld.jsp (as describes in the WebConfig.java implementation).

JSP view

To print the message “message”, we use ${message} in WEB-INF/jsp/helloworld.jsp :

message : ${message}

Copyright © 2024 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.