Thymeleaf+Spring, isAuthenticated()/hasRole() not working - java

I have a problem with isAuthenticated() method. It seems it always return false no matter if the user is logged in or not. Also after calling this method nothing is shown to the end of the html code. In this example:
aaa
<div sec:authorize="isAuthenticated()">
This content is only shown to authenticated users.
</div>
bbb
ccc
only aaa is shown.
Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>
^this code works perfectly, so there should not be a problem with sec: (I guess)
My Thymeleaf config class:
public class ThymeleafConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
#Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
engine.addDialect(new SpringSecurityDialect());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/css/**")
.addResourceLocations(
"classpath:/static/css/");
}
}
And maven dependencies:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
What could be causing this error?

Change your file pom.xml, and add this these dependencies:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
Now in your html file add:
<!DOCTYPE html>
<html lang="es" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
that is all 😉
<div sec:authorize="isAuthenticated()">
Text visible only to authenticated users.
</div>

Ok, i solved this problem. This is from : https://github.com/thymeleaf/thymeleaf-extras-springsecurity
Requirements (3.0.x)
Spring Framework version 3.0.x to 4.3.x
Spring Security version 3.0.x to 4.2.x
I was using Spring 5.0.0 - with Spring 4.3.13 and Spring Security 4.2.3 everything works fine.

Related

How to add Swagger-UI to a project running with tomcat 9.0.41 and Spring, without Spring Boot

Has anyone tried adding Swagger-UI to projects running with Tomcat and Spring, but without Spring Boot?
My project runs on a Tomcat server, with spring. I want to add swagger-UI to see all the endpoints but I can't implement it.
I tried with all kinds of dependencies and configurations but I didn't manage to finish it.
This is my configuration:
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.betfair"})
#Import(SwaggerConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("My REST API", "Some custom description of API.", "API TOS", "Terms of service", "myeaddress#company.com", "License of API", "API license URL");
return apiInfo;
} }
#Configuration
#EnableWebSecurity
public class WebSecurityConfiguration implements WebSecurityCustomizer {
#Override
public void customize(WebSecurity web) {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**");
}
}
// My pom.xml dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-schema</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>5.7.2</version>
</dependency>
What I am missing? Do I need more special configurations? Thanks.

Java Spring initialize, call a method on startup

I am new to java spring framework, and I am trying to call a method or initialize a method on startup so when the application start, I will be able to see my data from the database on my jsp page. I have try #EventListener, #PostConstruct but nothing is working for me.
This is my WebConfigura class
#Configuration
#ComponentScan("com.store.spring")
#EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {
#Bean
public DataSource dataSource() {
final JndiDataSourceLookup lookup = new JndiDataSourceLookup();
lookup.setResourceRef(true);
DataSource dataSource = lookup.getDataSource("jdbc/product_db");
return dataSource;
}
#Bean
public UrlBasedViewResolver resolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resource/css/**").addResourceLocations("/css/").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling (DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HeaderInterceptor());
}
}
This is Web Application Initializer class
#Component
public class WebInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(WebConfiguration.class);
// Add context.setCongiglocation("/WEB-INF/spring/dispatcher-config.xml");
ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
registration.addMapping("/");
registration.setLoadOnStartup(1);
ContextLoaderListener listener = new ContextLoaderListener(context);
servletContext.addListener(listener);
}
}
This is the controller class
#Controller
public class ProductController {
#Autowired
private ProductService productService;
#RequestMapping("/index")
public String index(Model model) {
List<Product> listProduct = productService.getPrducts();
model.addAttribute("listProduct", listProduct);
return "index";
}
// Request mapping using SQL tag
#RequestMapping("/location")
public String addLocation(Model model) {
List<Product> listProduct = productService.getPrducts();
model.addAttribute("listProduct", listProduct);
return "location";
}
#RequestMapping("/entry")
public String entry() {
return "Entry";
}
#RequestMapping("/aboutUs")
public String aboutUS() {return "AboutUs";}
#RequestMapping("/deal")
public String deal() {
return "Deal";
}
#RequestMapping("/listProduct")
public String listOrganizationService(Model model) {
List<Product> listProduct = productService.getPrducts();
model.addAttribute("listProduct", listProduct);
return "ListOrganizations";
}
}
This is the header interceptor class
public class HeaderInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
request.setAttribute("title", "We hope you have a scary and fun filled halloween");
String location = request.getParameter("locationName");
if (location != null) {
request.setAttribute("locationName", location);
}
return true;
}
}
This is the method I want to initialize or call on start up. Or at least
some thing close to this
#RequestMapping("/index")
public String index(Model model) {
List<Product> listProduct = productService.getPrducts();
model.addAttribute("listProduct", listProduct);
return "index";
}
I am using index.jsp to call the listProduct to print my data out. Notice that index.jsp is the first jsp that call when the application start. And I want it to ab able to automatic print those data out
<div class="main-container" style="text-align: center">
<c:forEach var="row" items="${listProduct}">
<div class="detail">
<td>ID: <c:out value="${row.id}"></c:out></td>
<br/>
<td>Name: <c:out value="${row.productName}"></c:out></td>
<br/>
<td>Quantity: <c:out value="${row.quantity}"></c:out></td>
<br/>
<td>Price: <c:out value="${row.price}"></c:out></td>
<br/>
<td><div class="few-line"><c:out value="${row.description}"></c:out></div></td>
</div>
</c:forEach>
I hope someone could help me out.
For Example I had this code inside my WebInitializer class, and when I run it I got an error message
#EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent(Model model) {
List<Product> productList = productService.getPrducts();
model.addAttribute("productList", productList)
}
Caused by: java.lang.IllegalArgumentException: argument type mismatch
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.context.event.ApplicationListenerMethodAdapter.doInvoke(ApplicationListenerMethodAdapter.java:256)
... 56 more
org.apache.catalina.core.StandardContext.startInternal One or more
listeners failed to start.
org.apache.catalina.core.StandardContext.startInternal Context []
startup failed due to previous errors
org.springframework.web.context.support.AnnotationConfigWebApplicationContext.doClose
Closing Root WebApplicationContext: startup date [Sun Aug 13 10:43:51
EDT 2017]; root of context hierarchy
These are my plug and dependencies for my jar
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
</dependencies>
Java Spring initialize, call a method on startup
You can annotate a Spring bean's method with #PostConstruct to have Spring call it after it gets constructed. You can also annotate a method with #Autowired to have Spring call it during the construction of that bean. We typically use one of those to call a method on startup, for example to load data from a database into cache.

Spring Swagger-ui integration

Needless to say I know there are a ton of questions about this same subject but I've been stuck trying to fix this for 2 days now and most of what I've read is outdated.
So yeah.. this is what I have right now:
Gradle:
dependencies {
compile 'org.springframework.cloud:spring-cloud-starter-hystrix'
compile 'org.springframework.boot:spring-boot-starter-web'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.springframework.ws:spring-ws-core'
compile 'io.springfox:springfox-swagger2:2.4.0'
compile 'io.springfox:springfox-swagger-ui:2.4.0'
}
Main class:
#EnableSwagger2
public class Application {
public static void main(String[] args) {
SpringApplication.run(FeedServiceApplication.class, args);
}
#Bean
public Docket swaggerSettings() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build()
.pathMapping("/");
}
When I visit: http://localhost:8080/v2/api-docs, I get the json documentation just fine. Also when I download swagger-ui from github, set the source to the link above and run it on desktop, it also works fine. What doesn't work is putting these 2 things together (getting it to work at http://localhost:8080/swagger-ui.html).
There are many tutorials such as these, where they claim the stuff above will make swagger-ui work:
http://kubecloud.io/guide-using-swagger-for-documenting-your-spring-boot-rest-api/
http://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
And a ton of other tutorials where they instruct you to add dist folder from swagger-ui git to your project.
Also mapping like this:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("**/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("**/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
Fails as well, throwing Scope 'request' is not active for the current thread; exception.
After trying some tutorials from youtube, the ones linked above and many others, all I've seen is "page not found". If anyone could explain what I'm missing I would be very grateful.
TL:DR How do I get swagger-ui.html to work?
EDIT: found the solution.
In case anyone else stumbles upon this, the problem is that if you have a request mapping that takes in a parameter #RequestMapping("/{param}"), dispatcherServlet no longer maps /** to ResourceHttpRequestHandler. The code below fixes that issue.
#Configuration
#EnableAutoConfiguration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter{
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build();
}
#Override public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
That's what we use as setup. A class for its own annotated with #Configuration
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error")))
.build()
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"APP NAME",
"APP DESCRIPTION",
"1.0",
null,
new Contact("Firstname Lastname", null, "firstname.lastname#somewhere.net"),
null,
null);
}
}
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spi</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-core</artifactId>
<version>${swagger.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-spring-web -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId>
<version>${swagger.version}</version>
</dependency>
Convert the above dependency to gradle.
Version i used is 2.3.1
package XXXX;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
#EnableSwagger2
public class SwaggerConfiguration {
}
We enabled the Swagger Config as stated above.
You can add Docket bean for custom headers:
#Bean
public Docket docket() {
Parameter parameterAuthorization =
new ParameterBuilder().name("Authorization").description("Authentication of the API User")
.modelRef(new ModelRef("string")).parameterType("header").required(true).build();
Parameter parameterClientUserId =
new ParameterBuilder().name("user_id").description("Client user identifier")
.modelRef(new ModelRef("string")).parameterType("header").required(true).build();
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any()).build()
.globalOperationParameters(Lists.newArrayList(parameterClientUserId, parameterAuthorization));
}
And finally import the Swagger config in Main Application Class on Spring boot
#Import({SwaggerConfiguration.class})

Thymeleaf Spring configuration

I'm trying to set up Thymeleaf in my Spring MVC application but somethings goes wrong
Here is my pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<spring.version>4.3.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.1.RELEASE</version>
</dependency>
</dependencies>
</project>
and here is my configuration
package thyme.leaf.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.WebMvcConfigurerAdapter;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
#Configuration
#EnableWebMvc
#ComponentScan("my.package")
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}
#Bean
public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}
#Bean
public TemplateResolver templateResolver() {
TemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
the problem is somewhere with TemplateResolver class in my methods. Unfortunatelly it can not be found at all. I inspected org.thymeleaf.templateresolver package where I think it should be but it is not there
can anybody advice what is wrong here please
Finally found correct implementation:
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
#Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
}
I'm not sure but try to change #ComponentScan("my.package") with #ComponentScan("thyme.leaf.config").

Spring MVC annotation based configuration not working

I tried to create a simple Spring MVC project with help of this tutorial
but when I deployed it is showing 404 server error.Since I am a beginner to spring MVC I couldn't make out what is wrong in project inspite of going through all the answers here and other places as well.I would greatly appreciate your help in figuring out.
These are the Contents:
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com</groupId>
<artifactId>deevigeweb</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>deevigeweb Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>deevigeweb</finalName>
</build>
</project>
Servlet Initializer(DeevigeServletInitializer.java)
package com.deevigeweb.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class DeevigeServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {DeevigeWebMVCConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
Web MVC Config(DeevigeWebMVCConfig.java)
package com.deevigeweb.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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan({"com.deevigeweb"})
public class DeevigeWebMVCConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/views");
resolver.setSuffix(".jsp");
return resolver;
}
}
Controller(SearchViewController.java)
package com.deevigeweb.controllers.webapp;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
public class SearchViewController {
#RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView doLanding(){
return new ModelAndView("searchview");
}
}
JSP(searchview.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<h1>Welcome</h1>
</body>
</html>
Directory Structure
project structure
Maybe adding the trailing slash does the trick for you:
resolver.setPrefix("/WEB-INF/views/");
Also add a #Controller annotation on your SearchViewController class
Add a class level #Controller annotation on SearchViewController. You missed it.
#Controller
public class SearchViewController {
#RequestMapping(value="/",method=RequestMethod.GET)
public ModelAndView doLanding(){
return new ModelAndView("searchview");
}
}
Now the URL localhost:8080/deevigeweb/ will return searchview.jsp page.
And web.xml is not required in your project as this is pure Java based configuration.

Categories

Resources