I am working on Spring MVC project. I am getting an error while binding the checkbox value to the back end file. Can any one please suggest whats the mistake or missing step please?
I have searched for similar threads but the answers did'nt solve my issue. Appreciate any help here.
Code:
JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<form:form modelAttribute="listOfShapes" action="/calculateArea">
<form:checkboxes items="${listOfShapes}" path="selectedShapes" />
</form:form>
</body>
</html>
MOdelAttribute:
#ModelAttribute("listOfShapes")
public List<String> getListOfShapes() {
List<String> shapesOfList = new ArrayList<String>();
shapesOfList.add("Circle");
shapesOfList.add("Rectangle");
shapesOfList.add("Square");
return shapesOfList;
}
POJO:
package model.pojo.org;
import java.util.List;
public class ListOfShapes {
private List<String> selectedShapes;
/**
* #return the selectedShapes
*/
public List<String> getSelectedShapes() {
return selectedShapes;
}
/**
* #param selectedShapes the selectedShapes to set
*/
public void setSelectedShapes(List<String> selectedShapes) {
this.selectedShapes = selectedShapes;
}
}
XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="calculate.area.org" />
</beans:beans>
I am getting the below Error. Can anyone please suggest?
org.springframework.beans.NotReadablePropertyException: Invalid property 'selectedShapes' of bean class [java.util.ArrayList]: Bean property 'selectedShapes' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The Form Model should not be listOfShapes. The Form Model is what actually receives the input. So I believe this is wrong:
<form:form modelAttribute="listOfShapes" action="/calculateArea">
It's OK to use it as a Checkbox Display Constants getter in your <form:checkboxes items="${listOfShapes}" path="selectedShapes" /> but it's not OK to use it as an actual Form Model that gathers input. That would be your POJO instance, not a list of constants.
For example, see here:
http://www.baeldung.com/spring-mvc-form-tutorial
I assume you have a Controller that exposes the ModelAndView with the form model object, right? Something like
public String processForm(#ModelAttribute("employee")Employee employee,
BindingResult result, ModelMap model) {
}
in that case the Form Model would be
<form:form method="POST" action="/spring-mvc-xml/addEmployee" modelAttribute="employee">
as in that website example.
Related
I have a problem with Hibernate Validator. I putted in my code #Size annotation but when I am running app on Tomcat server I can submit without filled text field. What is wrong with this code?
Customer class:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Customer {
private String firstName;
#NotNull(message="is required")
#Size(min=1, message="is required")
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerController class:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.validation.Valid;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping("/showForm")
public String showForm(Model theModel) {
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
#RequestMapping("/processForm")
public String processForm(
#Valid #ModelAttribute("customer") Customer theCustomer, BindingResult theBindingResult) {
if (theBindingResult.hasErrors()) {
return "customer-form";
} else {
return "customer-confirmation";
}
}
}
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Add support for scanning countries from file -->
<util:properties id="countryOptions" location="WEB-INF/countries.properties" />
<!-- Step 3: Add support for component scanning -->
<context:component-scan base-package="com.rafal.springdemo" />
<!-- Step 4: Add support for conversion, formatting and validation support -->
<mvc:annotation-driven/>
<!-- Step 5: Define Spring MVC view resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
customer-form.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Customer Registration Form</title>
<style>
.error {color:red}
</style>
</head>
<body>
<form:form action="processForm" modelAttribute="customer" >
First name: <form:input path="firstName" />
<br><br>
Last name (*): <form:input path="lastName" />
<form:errors path="lastName" cssClass="error" />
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
And screenshots from lib folder and project structure.
You might need to add the following bean definition in your xml.
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
OR
for custom error messages you need to create a message.properties in the resource folder and use ResourceBundleMessageSource
<!-- bind your messages.properties -->
<bean class="org.springframework.context.support.ResourceBundleMessageSource"
id="messageSource">
<property name="basename" value="messages" />
</bean>
Did you try to place
<!-- Hibernate Validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
in your pom.xml?
I used the jar hibernate-validator-5.1.3.Final and it worked for me.
I was facing the same problem when I was using 6.
Restarting IntelliJ fixed this for me. Really. 25 minutes of my life I'll never get back.
I had the same problem.
My solution was using older version of Hybernate validator. The thing is they changed package name into jakarta. instead of javax. from version 6.2 and it was causing problems for me, because spring class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" was still implementing javax.validation.ValidatorFactory
I had the same problem using Hibernate Validator 7. I used Hibernate 6 and the problem was solved!
I was having the same problem, To solve this
use #NotEmpty instead of #NotNull,
this should fix the issue.
I'm very new to Spring mvc,for this question i've found many answers here but nothing is working for me and please help me to find out what mistake i'm doing here.
I have created a css file under WebContent>WEB-INF>resources>css>style.css and mapping is done under spring-servelet.xml and the code is
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<context:component-scan base-package="com.journaldev.spring" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<!-- Handles HTTP GET requests by efficiently serving up static resources
in the corresponding directory -->
<mvc:annotation-driven />
<mvc:default-servlet-handler />
<mvc:resources mapping="resources/**" location="resources/" cache-period="31556926"/>
</beans:beans>
and i've called the css file from jsp and the jsp file is
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>welcome</title>
<!-- Custom Theme files -->
<link href="<spring:url value='resources/css/style.css' />" rel="stylesheet" type="text/css" media="all" />
</head>
<body>
<h1>Hello world!</h1>
<P>The time on the server is ${serverTime}.</p>
</body>
</html>
Now network is aborted error is displaying at console .As i told i'm newbie to this framework so please help me out other than giving a link to an answer because i've tried almost all.Thank you
Put your CSS folder inside webcontent and add below code servlet xml file
<mvc:resources mapping="/css/**" location="/css/" />
Now you will be able to take the CSS from JSP inside views folder using below code -
<link href="/css/yourCSS.css" rel="stylesheet" type="text/css" media="all" />
This should work otherwise let usknow!
So, you will need to do what vipin cp is suggesting. You need this:
<link href="<spring:url value='/css/style.css' />" rel="stylesheet" type="text/css" media="all" />
This is because the you are using the mapping mapping="/css/**" , so your value needs to begin with the same thing as your mapping "/css/...", without the beginning slash, it doesn't match your mapping so spring doesn't know where to map it too, you could also change your mapping to mapping="css/**". Which ever you choose, they just need to match each other.
Once they match Spring can then resolve your urls to what they need to be.
Also, just a suggestion for readability. Specify all your spring:url elements at the top with a var argument and then you can reference that with standard SpEl.
And example is:
<spring:url value='/css/style.css' var='styleCss'/>
So, that tells Spring that the styleCss variable references the resolved url from /css/style.css. You can then reference that variable like:
<link href="${styleCss}" rel="stylesheet" type="text/css" media="all" />
Obviously, up to you, but I have always found it more readable.
For what it is worth, this can also be done with your JS imports if you have any.
I'm testing for the first time Thymeleaf 3.x with a simples web app, and I'm having some issues doing form validation. I'm not able to change the graphical style of my form fields with the Thymeleaf attribute th:errorclass, and I don't know why.
Here is my controller:
#RequestMapping(value = {"/" , "" , "/home" , "/index" , "/login"} , method = RequestMethod.GET)
public String getLogin(final Model m)
{
if(m.containsAttribute("login") == false)
{
System.out.println("Creating login form...");
m.addAttribute("login", new For_Login());
}
return Util_Paginas.PAG_LOGIN.toString();
}
#RequestMapping(value = "/login" , method = RequestMethod.POST)
public String authenticate(
#Valid #ModelAttribute("login") final For_Login form ,
final BindingResult br ,
final Model m)
{
System.out.printf("Authentication received!%n");
System.out.printf("LOGIN: %s%n" , form.getLogin());
System.out.printf("PASS: %s%n" , form.getSenha());
if(br.hasErrors())
{
System.out.printf("Found %d fields!%n" , br.getErrorCount());
}
return Util_Paginas.PAG_LOGIN.toString();
}
My HTML file with Thymeleaf 3.x nature:
<!DOCTYPE html>
<html>
<head>
<title>Login page</title>
<link rel="stylesheet" type="text/css" media="all" th:href="#{/css/estilos.css}" />
</head>
<body>
<p>Welcome. Please login.</p>
<form action="#" th:action="#{/login}" th:object="${login}" method="post">
<fieldset>
<p>
Login:
<input
type="text"
th:field="*{login}"
th:class="campo"
th:errorclass="campo-invalido">
</p>
<p>
Password:
<input
type="password"
th:field="*{senha}"
th:class="campo"
th:errorclass="campo-invalido">
</p>
<p>
<input type="submit" value="Submit"/>
</p>
</fieldset>
</form>
</body>
</html>
My CSS file:
#CHARSET "ISO-8859-1";
.campo
{
background-color: gray;
border: 2px solid red;
}
.campo-invalido
{
background-color : #ff0000;
border: 1px solid #800000;
width: 230px;
color: white;
}
p
{
color: blue;
font-size: 22pt;
}
What is happening is that the style is not being applied. Errors are found on the server side, but when the page is returned, it is as if the th: errorclass attribute was not present. I do not know what I'm doing wrong.
I know that my css file is being read because the P tags are getting stylized.
I'm using:
Eclipse Mars.2 Release (4.5.2)
thymeleaf 3.0.3 RELEASE
thymeleaf-spring4 3.0.3 RELEASE
spring-webmvc 4.1.1 RELEASE
spring-context 4.1.1 RELEASE
validation-api 1.1.0 FINAL
hibernate-validator 5.3.4 FINAL
If in case someone wants to see some more code of my project, I'll be happy to present it here.
Thank you for your time and patience.
EDIT
I almost forgot something important too, my Spring MVC Application Context file:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<!-- ################################################################################### -->
<!-- MAPEAMENTO DE RECURSOS -->
<!-- ################################################################################### -->
<!-- Mapeamento de recursos (arquivos css, fontes, imagens, dentre outros). -->
<mvc:resources mapping="/css/**" location="/WEB-INF/recursos/css/" />
<mvc:resources mapping="/imagens/**" location="/WEB-INF/recursos/imagens/" />
<mvc:resources mapping="/fontes/**" location="/WEB-INF/recursos/fontes/" />
<!-- ################################################################################### -->
<!-- ANOTAÇÕES E RECURSOS SPRING -->
<!-- ################################################################################### -->
<!-- Possibilita o uso de anotações Spring Mvc. -->
<mvc:annotation-driven />
<!-- Define local para procura de componentes Spring (beans configurados
por anotações em classes). -->
<context:component-scan base-package="com.regra7.st.controle" />
<!-- ################################################################################### -->
<!-- INTERNACIONALIZAÇÃO -->
<!-- ################################################################################### -->
<!-- ################################################################################### -->
<!-- CONFIGURAÇÕES DO THYMELEAF -->
<!-- ################################################################################### -->
<!-- Template Resolver para Template Engine. -->
<!-- <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" /> <property name="suffix"
value=".html" /> <property name="templateMode" value="HTML5" /> </bean> -->
<!-- SpringResourceTemplateResolver automatically integrates with Spring's
own -->
<!-- resource resolution infrastructure, which is highly recommended. -->
<bean id="templateResolver"
class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".html" />
<!-- HTML is the default value, added here for the sake of clarity. -->
<property name="templateMode" value="HTML" />
<!-- Template cache is true by default. Set to false if you want -->
<!-- templates to be automatically updated when modified. -->
<property name="cacheable" value="true" />
</bean>
<!-- SpringTemplateEngine automatically applies SpringStandardDialect and -->
<!-- enables Spring's own MessageSource message resolution mechanisms. -->
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<!-- Enabling the SpringEL compiler with Spring 4.2.4 or newer can speed
up -->
<!-- execution in most scenarios, but might be incompatible with specific -->
<!-- cases when expressions in one template are reused across different
data -->
<!-- ypes, so this flag is "false" by default for safer backwards -->
<!-- compatibility. -->
<property name="enableSpringELCompiler" value="true" />
</bean>
<!-- ################################################################################### -->
<!-- CONFIGURAÇÕES DO SPRING MVC -->
<!-- ################################################################################### -->
<!-- View resolver do Thymeleaf. -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
</bean>
<!-- Definição de HandlerMapping. -->
<!-- Cuida de classes controladoras. -->
<!-- <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
</bean> -->
<!-- ################################################################################### -->
<!-- INTERCEPTADORES -->
<!-- ################################################################################### -->
<!-- INTERCEPTADORES -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/usuario/*" />
<bean class="com.regra7.st.interceptadores.Login" />
</mvc:interceptor>
</mvc:interceptors>
</beans>
EDIT 2
After messing around a bit with the validation code, I changed the approach used and suddenly, things started to work.
Previously, I was using bean validation with my own annotations for data validation. I decided to change to the validation done with Spring, using org.springframework.validation.Validator, And magically everything went well.
However, I would not like to use the data validation approach with Spring, but rather with bean validation annotations. I've figured out where I'm wrong, but I do not understand why.
I'll put my login validation code:
// My bean validation annotation.
#Documented
#Constraint(validatedBy = Val_Login.class)
#Target({ElementType.METHOD , ElementType.FIELD , ElementType.ANNOTATION_TYPE})
#Retention(RetentionPolicy.RUNTIME)
public #interface Login
{
String message() default "{com.regra7.st.login}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
int min() default 10;
int max() default 20;
}
// Validator implementation.
public class Val_Login implements ConstraintValidator<Login , String>
{
private int min;
// private int max;
#Override
public void initialize(Login login)
{
this.min = login.min();
// this.max = login.max();
}
#Override
public boolean isValid(String value, ConstraintValidatorContext context)
{
return Util_Validador.isLoginValido(value , this.min);
}
}
// The form input object.
public class For_Login
{
#Login(min = 8)
private String login;
// Many things ommited
}
The Util_Validador class is able to return a true or false value, this has already been tested. If I do this:
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.regra7.st.formularios.For_Login;
import com.regra7.st.util.Util_Texto;
public class ValidadorFormulario implements Validator
{
#Override
public boolean supports(Class<?> clazz)
{
return For_Login.class.isAssignableFrom(clazz);
}
#Override
public void validate(Object objeto, Errors erros)
{
For_Login log = (For_Login) objeto;
if(Util_Texto.isVazia(log.getLogin()) ||
log.getLogin().length() < 8)
{
erros.rejectValue("login", "Login errado!");
}
if(Util_Texto.isVazia(log.getSenha()) ||
log.getSenha().length() < 14)
{
erros.rejectValue("senha", "Senha errada!");
}
}
}
Everything works out. Can you guys help me a bit, please? I think this can help many people who get on the same place as me.
As always, thank you.
I did two things wrong:
I forgot to import some libraries needed by Hibernate Validator.
I was using prefixes for form fields (For_Login). The data binding
was not happening properly. Actually, it was, but Thymeleaf was not
recognizing it properly. It's no use having a field named _myField
(for instance), and setting setMyField and getMyField methods. Either
you write the field with the name myField, or the methods with the
names get_myField and set_myField.
This is my dispacter-servlet.xml file. When i deploy the project on resin pro 4.0.36 it loads my index page and the content BUT FAILS to load css files and images stored under the staticresources folder
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.dogears" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<import resource="classpath:beans.xml"/>
<mvc:resources mapping="/resources/**" location="/staticresources/" />
<mvc:annotation-driven />
Please can anyone tell me how to mapp my static resources folder, so that whenever the request is of the patter /resources/* it redirects the request to the static resources folder. the staticresources folder is in MyspringProject/src/main/webapps directory.
I believe you need to map your staticresources directory as a root directory. In Eclipse that would be a "Source Folder" and in IntelliJ a "Resources Root".
Refer to the following help docs depending on your IDE:
Eclipse: http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-wizard-source-folder.htm
IntelliJ: https://www.jetbrains.com/webstorm/help/configuring-folders-within-a-content-root.html
Suppose your project directory structure is like
- src
- main
- webapp
- resources
- css
- abc.css
- images
- xyz.jpg
& your .html or .jsp pages are located in the directory as below
- webapp
- index.jsp
- pages
- welcome.jsp
then you can add link to your resources in index.jsp page with the URL BaseURL/index.jsp
<link href="resources/css/abc.css" rel="stylesheet" type="text/css" />
<body>
<img src="resources/images/xyz.jpg" alt="" style="width:100px;height:100px" />
</body>
& to welcome.jsp with URL BaseURL/pages/welcome.jsp as
<link href="../resources/css/abc.css" rel="stylesheet" type="text/css" />
<body>
<img src="../resources/images/xyz.jpg" alt="" style="width:100px;height:100px" />
</body>
Hope this helps you.
I finally found my solution. I had deployed my spring webapp in the webapps folder of the resin directory.
I realised that <mvc:resource /> mapping tag does not work when you have deployed your spring app on resin server instead of tomcat.
Hence i solved this by first creating a war file of my project and then extracted the war file on the desktop and later placed all the contents from the war file in the webapps/root (and not webapps folder) folder of resin directory. and then from my index page i used JSTL TAG to include the external stylesheet.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<link rel="stylesheet" type="text/css" href="<c:url value="/staticresources/externalcss.css"/>">
</head>
<body>
<h2 class="text_style">Hello World!</h2>
</body>
</html>
IT WORKS !!!
I am new to Spring security, so I am trying to use Spring MVC to handling invalid login, but ended up with Page Not Found 404
In my security-context.xml, i have this AuthenticationProvider handling all the authentication login, so just basically checking the user's account and password, but for some reasons it keeps saying the authentication-failure-url is not found 404 whenever there's an invalid login attempt.
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider ref="AuthenticationProvider"/>
</security:authentication-manager>
<bean id="preAuthenticationFilter"
class="authentication.PreAuthenticationFilter"
p:authenticationManager-ref="authenticationManager" />
<security:http auto-config="true">
<security:intercept-url pattern="/member/**" access="MEMBER" requires-channel="https"/>
<security:form-login login-page="/login"
username-parameter="email"
password-parameter="password"
default-target-url="/member/"
authentication-failure-url="/loginfailed" />
<security:custom-filter position="PRE_AUTH_FILTER" ref="preAuthenticationFilter" />
</security:http>
But I do have a corresponding controller listens to that url pattern for handling invalid login.
#Controller
public class LoginController
{
#RequestMapping(value = "/loginfailed", method = RequestMethod.GET)
public String loginError(ModelMap model)
{
model.addAttribute("error", "true");
return "login";
}
}
****UPDATE*****
At some points my AuthenticationProvider validates the user and throw an exception (I don't know if that matters) whenever the user has a bad credential
#Component
public class AuthenticationProvider{
private User validateUser(String userName, String password)
{
try{
//authenticate user's info
.......
}
catch (UnauthorizedAccessException e)
{
throw new BadCredentialsException(e);
}
}
}
(As follow-up to comments.) 302 statu from j_spring_security_check and BadCredentialsException are both correct. It looks like your controller isn't registered at all. Do you have in mind that annotating bean with #Controller isn't enough to make it work? Quoting documentation:
You can define annotated controller beans explicitly, using a standard
Spring bean definition in the dispatcher's context. However, the
#Controller stereotype also allows for autodetection, aligned with
Spring general support for detecting component classes in the
classpath and auto-registering bean definitions for them.
To enable autodetection of such annotated controllers, you add
component scanning to your configuration. Use the spring-context
schema as shown in the following XML snippet:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.example"/>
<!-- ... -->
</beans>
(assuming LoginController is in com.example package).
Simple bean declaration can be use instead of component scanning:
<bean class="com.example.LoginController" />