I'm actually learning Spring Boot. I follow the guides and i'm tryng this one : Securing a Web Application.
So I've made 2 files (hello.html/home.html) and i would like to deploy my application to see them but when i try to access localhost:8080 i get this error :
Circular view path [home]: would dispatch back to the current handler URL [/home] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
If someone can help me there ? Here is my code :
src/main/java/com/society/MyApplication :
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyApplication {
public static void main(String[] args) throws Throwable {
SpringApplication.run(CalamarApplication.class, args);
}
}
src/main/java/com/society/MvcConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
src/main/resources/templates/home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
Thanks by advance.
Related
I am learning Spring Framework. I added home.html in resources/templates/home.html. But it is not visible when I visit http://localhost:8080. I have the following structure:
taco-cloud\src\main\java\tacos\TacoCloudApplication.java
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args);
}
}
taco-cloud\src\main\java\tacos\HomeController.java
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class HomeController
{
#GetMapping("/")
public String home()
{
return "home.html";
}
}
taco-cloud\src\main\resources\static\home.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
</head>
<body>
<h1>Welcome to...</h1>
<img th:src="#{/images/TacoCloud.png}"/>
</body>
</html>
Output
Whitelable error page
localhost:8080/home.html
show home.html
You have to change the location of your home page to be in the static folder :
resources/static/home.html
^^^^^^
instead of
resources/templates/home.html
and specify the extension in your controller :
return "home.html";
^^^^^
else you have to create a view resolver to avoid using extensions and to specify the other locations of your pages take a look at Configure ViewResolver with Spring Boot and annotations gives No mapping found for HTTP request with URI error
You can try this.
#GetMapping("/")
public String home()
{
return "templates/home.html";
}
Check more details
Below are few different ways you can place html files in your project.(Note it is from highest to lowest precedence)
src/main/resources/resources/home.html
src/main/resources/static/home.html
src/main/resources/public/home.html
Go through this to get an idea about spring mvc project structure
I couldn't achieve a functional reference scheme to my example application as follows. File teste.js seems not being reached by the resource declaration in jsp file. Any help could be valuable.
jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title> Composição </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" charset="UTF-8" src="http://localhost:8080/compo/resources/js/teste.js"></script>
</head>
<body>
Greeting : ${greeting}
<table><tr><td id="save"> clique </td></tr></table>
<script type="text/javascript">
window.onload = function() {
document.getElementById("save").onclick = function fun() {
//alert("hello"); - working
testing("hello 2"); //not working
}
}
</script>
</body>
</html>
teste.js
function testing(message){
alert('messaged script: ' + message);
}
I am using Spring MVC and I've build the application in Eclipse, using its wizard, and for this reason it is using a "WebContent" folder structure, in spite of the fact that I have turn my project into a Maven project after creation. I think this is an important information.
UPDATE
After several tests, I concluded that the problem is in the Web-MVC configuration, because a similar project without Spring performs the access to resources perfectly.
Configuration (Spring 5.0.2):
package com.mycompany.compo;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.mycompany.compo")
public class SpringConfiguration implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("public", "classpath:/resources/")
.setCachePeriod(31556926)
;
}
}
My Spring release is 5.x and tomcat version is 8.5, so according to introduction, they will support the web application running without web.xml, but I got 404 error, see my project structure below:
I use this url to access my application, but got 404 error:
http://localhost:8080/SpringMVC/
see my code below:
RootConfig.java:
package spittr.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#ComponentScan(basePackages= {"spitter"},
excludeFilters= {#Filter(type=FilterType.ANNOTATION, value=EnableWebMvc.class)}
)
public class RootConfig {
}
WebConfig.java:
package spittr.config;
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.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan("spittr.web")
public class WebConfig implements WebMvcConfigurer{
public ViewResolver viewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
{
configurer.enable();
}
}
SpittrWebAppInitializer.java:
package spittr.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpittrWebAppInitializer 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[] {"/"};
}
}
HomeController.java:
package spittr.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class HomeController {
#RequestMapping(value="/",method=RequestMethod.GET)
public String home()
{
System.out.println("test");
return "home";
}
}
home.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>this is the Home Jsp page</title>
</head>
<body>
<h1>Hello, Spring MVC!</h1>
</body>
</html>
from the Eclipse console, I can see output "test" that means spring context find out the controller, but seems it cannot find the jsp page, I don't know the reason, can someone tell me what's wrong with my code?
Try adding #Bean annotation on top of WebConfig#viewResolver() method. So, the Spring Container manage your method as bean and your custom configuration will probably work.
#Bean
public ViewResolver viewResolver(){}
Indicates that a method produces a bean to be managed by the Spring
container.
I am getting this error while adding Assets folder.
It is giving error for every file which is included from "assets" folder.
WARN o.s.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/assets/plugins/datepicker/datepicker3.css] in DispatcherServlet with name 'dispatcher'
Here is the Dispacther Config file
package com.springmaven.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.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
#ComponentScan({"com.springmaven.controller"})
public class DispatcherConfig {
#Bean
public InternalResourceViewResolver getInternalResourceViewResolver()
{
InternalResourceViewResolver internalResourceViewResolver=new InternalResourceViewResolver();
internalResourceViewResolver.setPrefix("/WEB-INF/JSP/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
This is App Config
package com.springmaven.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class AppIntializer implements WebApplicationInitializer{
#Autowired
public void onStartup(ServletContext servletCon) throws ServletException {
// TODO Auto-generated method stub
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(ApplicationConfig.class);
servletCon.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext servletConfig = new AnnotationConfigWebApplicationContext();
servletConfig.register(DispatcherConfig.class);
ServletRegistration.Dynamic registration = servletCon.addServlet("dispatcher", new DispatcherServlet(servletConfig));
registration.setLoadOnStartup(1);
registration.addMapping("/");
}
}
This is security Config
package com.springmaven.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.data.repository.query.SecurityEvaluationContextExtension;
import org.springframework.security.web.csrf.CsrfTokenRepository;
import org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
#Autowired
private AuthenticationProvider customAuthenticationProvider;
#Autowired
CustomSuccessHandler customSuccessHandler;
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers("/assets/**");
}
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.authenticationProvider(customAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/assets/**").permitAll()
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("username").passwordParameter("password")
.and().csrf().csrfTokenRepository(csrfTokenRepository())
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
#Bean
public SecurityEvaluationContextExtension securityEvaluationContextExtension() {
return new SecurityEvaluationContextExtension();
}
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
private CsrfTokenRepository csrfTokenRepository()
{
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setSessionAttributeName("_csrf");
return repository;
}
}
Folder Structure
source->main->webapp->WEB-INF->JSP->assets(This folder is not recognised)
source->main->webapp->WEB-INF->JSP->homePage.jsp
From the Style or Icon is not coming in homePage.
homePage.jsp
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>New Member</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<!--Favicon Image -->
<link rel="shortcut icon" href="assets/dist/img/favicon.ico"/>
<link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="assets/plugins/datepicker/datepicker3.css">
</head>
<body>
Welcome,
<form id="logout" action="${Signout}" method="post" >
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:if test="${pageContext.request.userPrincipal.name != null}">
Logout
</c:if>
</body>
</html>
You need to add support for static web resources.
To configure it to be managed by Spring see this question, for example.
I want to add css, javascript and images to a spring 4 web application, i could give an example but I'm trying a spring tutorial:
Securing Web - http://spring.io/guides/gs/securing-web/
I added following changes:
package hello;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
Then i added a folder css with a simple css to the resources folder:
#CHARSET "ISO-8859-1";
p {
border-style:solid;
border-width:5px;
}
Then i added the css to the home.html:
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
<link type="text/css" rel="stylesheet" href="/resources/css/dummy.css"></link>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="#{/hello}">here</a> to see a greeting.</p>
</body>
</html>
Security config is injected through the following java class:
package hello;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
Then when using the google debug it returns the code
Status Code:302 Found but the css is not applied.
Could anyone indicate the changes necessary to add to make this working?
Discovered the problem after some search, the changes need to be able to use the css in the example are:
Create the following dirs under src/main:
- webapp
- resources
- css
Then add the dummy.css and in the desired html use:
<link th:href="#{/resources/css/dummy.css}" type="text/css" rel="stylesheet" href="/resources/css/dummy.css"></link>
Thanks to everyone that tried to help :)