Internationalization of placeholders in Spring - spring

I can not find the way to internationalize the text inside a placeholder like I do with regular text. I would like to place my internationalization in:
input type="text" class="form-control" name="s" placeHolder="Search Hobbies"
with input type="text" class="form-control" name="s" placeHolder="ctrlpanel.search.placeholder"
ctrlpanel.search.placeholder=Search Hobbies
Right now, in my JSP I include the tag
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<c:set var="contextRoot" value="${pageContext.request.contextPath}" />
<c:url var="search" value="/search" />
<hr/>
<div class="row">
<div class="col-md-8 col-md-offset-2">
<form action="${search}" method="post">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<div class="input-group input-group-lg">
<input type="text" class="form-control" name="s" placeHolder="Search Hobbies">
<span class="input-group-btn">
<button id="search-button" class="btn btn-primary" type="submit">
<spring:message code="ctrlpanel.find.button" text="default text" />
</button>
</span>
</div>
</form>
</div>
</div>
My configuration works fine:
package com.caveofprogramming.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import java.util.Locale;
#Configuration
public class SpringMvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public LocaleResolver localeResolver(){
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(new Locale("es", "ES"));
//sessionLocaleResolver.setDefaultLocale(Locale.US);
return sessionLocaleResolver;
}
#Bean
LocaleChangeInterceptor localeChangeInterceptor(){
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor;
}
#Override
public void addInterceptors(InterceptorRegistry interceptorRegistry){
interceptorRegistry.addInterceptor(localeChangeInterceptor());
}
}
Since this does not work.
<input type="text" class="form-control" name="s" placeHolder="<spring:message code="ctrlpanel.search.placeholder"/>">

Use var attribute of spring:message which is used when binding the result to the page, request, session or application scope.
<spring:message code="ctrlpanel.search.placeholder" var="searchPlaceholder"/>
And then update your input field like this:
<input type="text" class="form-control" name="s" placeHolder="${searchPlaceholder}">

Related

How to get e.g. registration.jsp view appear correctly in browser?

I am following this tutorial for a login and registration functionality in a Spring Boot web application: https://hellokoding.com/registration-and-login-example-with-spring-security-spring-boot-spring-data-jpa-hsql-jsp/
I can't get the views to display properly - instead of e.g. the registration.jsp view page, I see the following string on screen, which is returned by my GET registration controller method: https://ibb.co/XXXtdSZ
I am new to Java, Spring Boot and even newer to JSP.
I am using IntelliJ Community Edition 2017.3.5 and I had a notification that .jsp files are not supported. Following this, https://stackoverflow.com/a/36572413/11451547, I went to Settings - File Types - HTML under Recognized File Types, and I added a new registered pattern, .*jsp, overriding the already existing registered pattern for JSP Files (syntax Highlighting Only). The message that .jsp was not supported disappeared but I still don't see the view pages properly.
In my registration.jsp I see a lot of 'namespace e.g.'form' is not bound' notifications. In my login.jsp, which has the same display issue (on screen I see the string 'login' instead of the login view), I have one notification - 'Namespace 'c' is not bound'.
Could you help with some ideas on how to display the views correctly?
Thank you!
This is the respective part of my controller (maybe I am wrong in adding #ModelAttribute to GET registration twice, this is part of the amendments I did to the tutorial code but e.g. my GET login controller method is the same as in the tutorial):
#GetMapping("/registration")
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
#PostMapping("/registration")
public String registration(#ModelAttribute("userForm") User userForm, #ModelAttribute("roleId") Long roleId, BindingResult bindingResult) { //diff w tutorial
userValidator.validate(userForm, bindingResult);
// userValidator.validate(roleId, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.saveUser(userForm, roleId);
securityService.autoLogin(userForm.getUserName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#GetMapping("/login")
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and/or password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#GetMapping({"/", "/welcome"})
public String welcome(Model model) {
return "welcome";
}
My registration.jsp:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Create an account</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form:form method="POST" modelAttribute="userForm" modelAttribute="roleId" class="form-signin">
<h2 class="form-signin-heading">Create Your Account</h2>
<spring:bind path="userName">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="text" path="userName" class="form-control" placeholder="Enter your username"
autofocus="true"></form:input>
<form:errors path="userName"></form:errors>
</div>
</spring:bind>
<spring:bind path="password">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="password" path="password" class="form-control" placeholder="Enter your password"></form:input>
<form:errors path="password"></form:errors>
</div>
</spring:bind>
<spring:bind path="passwordConfirm">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input type="password" path="passwordConfirm" class="form-control"
placeholder="Confirm your password"></form:input>
<form:errors path="passwordConfirm"></form:errors>
</div>
</spring:bind>
<button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
</form:form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
My login.jsp:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log in with your account details</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
<link href="${contextPath}/resources/css/common.css" rel="stylesheet">
</head>
<body>
<div class="container">
<form method="POST" action="${contextPath}/login" class="form-signin">
<h2 class="form-heading">Log In</h2>
<div class="form-group ${error != null ? 'has-error' : ''}">
<span>${message}</span>
<input name="userName" type="text" class="form-control" placeholder="Enter your username"
autofocus="true"/>
<input name="password" type="password" class="form-control" placeholder="Enter your password"/>
<span>${error}</span>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button class="btn btn-lg btn-primary btn-block" type="submit">Log In</button>
<h4 class="text-center">Create an Account</h4>
</div>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
My welcome.jsp:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome</title>
<link href="${contextPath}/resources/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<c:if test="${pageContext.request.userPrincipal.name != null}">
<form id="logoutForm" method="POST" action="${contextPath}/logout">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</form>
<h2>Welcome ${pageContext.request.userPrincipal.name} | <a onclick="document.forms['logoutForm'].submit()">Logout</a></h2>
</c:if>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="${contextPath}/resources/js/bootstrap.min.js"></script>
</body>
</html>
The respective part of my application.yml file:
spring:
main:
banner-mode: 'off'
datasource:
url: jdbc:mysql://localhost:3306/inspire_me_db?useSSL=false
username: springuser
password: ThePassword
jpa:
hibernate:
ddl-auto: update
flyway:
baselineOnMigrate: true
mvc:
view:
prefix: /
suffix: .jsp
messages:
basename: validation
The respective part of my pom.xml:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
My package structure:
https://ibb.co/Qr2dmNr
Can you try registering your jsp view resolver as follows :
#Configuration
#EnableWebMvc
#ComponentScan
public class MvcConfiguration implements WebMvcConfigurer
{
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
registry.viewResolver(resolver);
}
}
Or you can also specify jsp as the view resolver in Spring-boot by providing the following in application.properties or yml :
spring.mvc.view.prefix=/WEB-INF/view/
spring.mvc.view.suffix=.jsp
Verify that the prefix provided points to the correct directory in which the jsp files reside.Usually the jsp files are put under src/main/WEB_INF/view .
Also since you are using spring-boot , if you don't have the appropriate dependencies to compile the jsp add the following to the pom :
<!-- JSTL -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<!-- To compile JSP files -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

Spring Security with custom login form not working

I have a custom login form with spring security and when logging in I keep getting a 404
Heres my web config
package coffee.web;
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.WebMvcConfigurer;
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/regular/index.html");
}
}
Heres my security config
package coffee.security;
import org.springframework.context.annotation.Bean;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("peter").password("peter").authorities("ROLE_USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").hasRole("USER").antMatchers("/", "/**").permitAll()
.and().formLogin().loginPage("/regular/login.html").permitAll().defaultSuccessUrl("/admin/adminIndex.html").and().csrf().disable();
}
}
Heres my login html form
<head>
<link href="index.css" type="text/css" rel="stylesheet" />
<link href="adminIndex.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="page">
<div id="bar"></div>
<header>
<h1><img id="logo" src="resources/logo.png" width="300" height="75" /></h1>
</header>
<section id="main">
<div id="container">
<div id="loginDiv">
<form name="login" id="login" action="login" method="POST">
<div id="formDiv">
<label for="addUsername" class="title">Username</label>
<span id="validateUsername" class="error"></span>
<input class="input" type="text" id="addUsername" name="username" />
<br />
<label for="addPassword" class="title">Password</label>
<span id="validatePassword" class="error"></span>
<input class="input" type="text" id="addPassword" name="password" />
<br />
<button id="submit" name="submit" type="submit" class="submit">submit</button>
</div>
</form>
</div>
</div>
</section>
</div>
</body>
Even when I turn authorization off, and only authentication is on, i still get the 403 error code after logging in. Even though I could still go directly to admin.adminIndex.html directly and it works.. (with authorization off and only authentication on).
Okay, I updated my security code with ".and().csrf().disable();" and now I am getting a 404 not found error when i log in.
That happened to me too (or at least something similar).
Try to add .and().csrf().disable() after .defaultSuccessUrl("/admin/adminIndex.html") to your configure method.

Using spring form tag inside a custom JSTL library

I need to create a custom JSTL tag which wraps multiple spring form tags. A single tag which produces the below content with custom attribute values as well.
<div class="col-md-4 col-sm-6 cal-xs-12">
<div class="form-group">
<label for="statusCode">Employee Status Code: </label>
<form:input path="statusCode" class="form-control" id="statusCode" value="${statusCode}" />
</div>
</div>
Is this achievable?
create a file formInputFiled.tag inside WEB-INF/tags/form directory.
formInputFiled.tag:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# attribute name="id" required="true" rtexprvalue="true" %>
<%# attribute name="path" required="true" rtexprvalue="true" %>
<%# attribute name="label" required="true" rtexprvalue="true" %>
<%# attribute name="value" required="true" rtexprvalue="true" %>
<%# attribute name="parentDivClass" required="true" rtexprvalue="true" %>
<%# attribute name="divClass" required="true" rtexprvalue="true" %>
<%# attribute name="inputClass" required="true" rtexprvalue="true" %>
<div class="${parentDivClass}">
<div class="${divClass}">
<label for="${id}">${label}</label>
<form:input path="${path}" class="${inputClass}" id="${id}" value="${value}" />
</div>
</div>
Add taglib declaration in your jsp like below:
<%# taglib prefix="form" tagdir="/WEB-INF/tags/form" %>
Finally use the new tag like below:
<form:formInputFiled id="statusCode" path="statusCode" label="Employee Status Code:" value="${statusCode}" parentDivClass="col-md-4 col-sm-6 cal-xs-12" divClass="form-group" inputClass="form-control"/>

Spring security: New user workflow

I am new to Spring security.
I have created a custom form that logs a user in and then, upon successful login, the user continues to his/her intended webpage. My implementation is standard and it works.
Here's my problem.
A user wants to go to page mywebpage.html.
The user is not logged in. The
user is redirected (by Spring Security) to the login page.
The user
does not have an account.
The user clicks on the createAccount link
and goes via standard MVC protocols to a registration page.
How do I now get the user's originally intended destination (mywebpage.html) from Spring Security, so I can redirect the user to that page once he/she has created an account?
For the record, security.xml
<http auto-config="true">
<intercept-url pattern="/login" access="permitAll()" />
<intercept-url pattern="/flow-entry.html" access="hasRole('ROLE_USER')"/>
<form-login
login-page="/login"
authentication-failure-url="/login?error=true" />
<logout logout-success-url="/login" />
</http>
login form
<form name='f' action="login" method='POST'>
<table style="text-align:left" class="w3-table" >
<tr style="text-align:center;color:red" th:if="${loginresponse}">
<td colspan="2" style="text-align:center" th:text="#{${loginresponse}}"> </td>
</tr>
<tr>
<td th:text="#{label.emaillogin}"></td>
<td><input type="text" name="username" value=''/></td>
</tr>
<tr>
<td th:text="#{label.password}">Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2" style="text-align:center"><input name="submit" type="submit" class="w3-btn w3-blue w3-hover-aqua w3-round-large" th:value="#{label.ok}" /></td>
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
</tr>
<tr style="text-align:center">
<td colspan="2" style="text-align:center"> <span th:text="#{label.register}"></span> </td>
</tr>
</table>
</form>
Controller Method. I need originally intended web page in this method
#RequestMapping(value = "/doRegistration", method=RequestMethod.POST)
public ModelAndView doRegistration(ModelAndView mv, HttpServletRequest request)
{
mv.setViewName("register");
SSm.getLogger().debug("registering new user");
String email = request.getParameter("username");
String email1 = request.getParameter("username1");
if(email.equals(email1))
{
if(email.contains("#")&&email.contains("."))
{
SSm.getLogger().debug("got legit email");
String password = request.getParameter("password");
String password1 = request.getParameter("password1");
if(password.equals(password1))
{
SSm.getLogger().debug("ready to login");
I NEED USERS ORIGINALLY INTENDED DESTINATION RIGHT HERE SO I CAN SET THE VIEW
}
else
{
mv.setViewName("register");
mv.addObject("loginresponse", "message.passwordmismatch");
}
}
else
{
mv.setViewName("register");
mv.addObject("loginresponse", "message.invalidemail");
}
}
else
{
mv.setViewName("register");
mv.addObject("loginresponse", "message.emailmismatch");
}
return mv;
}
You could use a SavedRequestAwareAuthenticationSuccessHandler.
When a non authorized request reaches the ExceptionTranslationFilter, a RequestCache of class HttpSessionRequestCache is created and the original request is saved on it.
This way, if you do not set alwaysUseDefaultTargetUrl to true, httpRequest would be reconstructed and used as target url while correct login is performed.
So, try to #Autowire (I use #Resource instead as I have more than one AuthenticationManager and AuthenticationSuccessHandler in my security config) the AuthenticationSuccessHandler in your controller and calling determineTargetUrl() like this:
I made a little modifications such as use #Valid annotations and implement a Validator to validate the registration form
Security.xml
<beans:bean id="savedRequestSuccesHandler"
class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<beans:property name="defaultTargetUrl" value="/zone4/secured/securedPage.htm" />
</beans:bean>
<security:http pattern="/zone4/**" use-expressions="true" authentication-manager-ref="mainAuthenticationManager">
<security:intercept-url pattern="/zone4/simple/**" access="permitAll()" />
<security:intercept-url pattern="/zone4/secured/**" access="isAuthenticated()"/>
<security:form-login
login-page="/zone4/simple/login.htm"
authentication-failure-url="/login.htm?error=true"
authentication-success-handler-ref="savedRequestSuccesHandler"
username-parameter="email"
password-parameter="password"
login-processing-url="/zone4/secured/performLogin.htm"
/>
<security:logout
logout-url="/zone4/secured/performLogout.htm"
logout-success-url="/zone4/simple/login.htm" />
<security:csrf disabled="true"/>
</security:http>
Controller:
/**
*
*/
package com.eej.ssba2.controller.test;
import java.io.IOException;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.eej.ssba2.model.test.zone4.RegisterModel;
import com.eej.ssba2.model.test.zone4.RegisterModelValidator;
/**
*
*/
#Controller
#RequestMapping("/zone4")
public class Zone4TestController {
private Logger logger = Logger.getLogger(this.getClass());
#Resource(name="mainAuthenticationManager")
private AuthenticationManager authenticationManager;
#Resource(name="savedRequestSuccesHandler")
private SavedRequestAwareAuthenticationSuccessHandler successHandler;
#RequestMapping("/simple/unsecuredPage.htm")
public String unsecuredPage(){
return "simple/unsecuredPage";
}
#RequestMapping("/secured/securedPage.htm")
public String securedPage1(){
return "simple/secured/securedPage";
}
#RequestMapping("/secured/securedPage2.htm")
public String securedPage2(){
return "simple/secured/securedPage2";
}
#RequestMapping("/secured/securedPage3.htm")
public String securedPage3(){
return "simple/secured/securedPage3";
}
#RequestMapping("/simple/login.htm")
public String login(){
return "simple/login/login";
}
#RequestMapping(value="/simple/register.htm", method=RequestMethod.GET)
public String register(ModelMap model){
logger.debug("Entrada en register.htm");
if(!model.containsAttribute("registerModel")){
model.addAttribute("registerModel", new RegisterModel());
}
return "simple/login/register";
}
#RequestMapping(value="/simple/register.htm", method=RequestMethod.POST)
public String register(
HttpServletRequest request, HttpServletResponse response,
#Valid RegisterModel registerModel, ModelMap model, BindingResult bindingResult){
logger.info("entrada en register");
RegisterModelValidator userValidator = new RegisterModelValidator();
userValidator.validate(registerModel, bindingResult);
if(bindingResult.hasErrors()){
logger.info("BindingResult has errors: " + bindingResult.getAllErrors());
model.addAttribute("errors", bindingResult.getAllErrors());
model.addAttribute("registerModel", registerModel);
return "simple/login/register";
}
// Your user register business
Authentication authenticated = null;
/*
* If the user is created at this time due to your business logic, you could authenticate it directly
* through the manager
*
authenticated =
this.authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
registerModel.getMail1(),
registerModel.getPassword1()
)
);
*/
authenticated = new UsernamePasswordAuthenticationToken(
registerModel.getMail1(),
registerModel.getPassword1(),
Arrays.asList(new SimpleGrantedAuthority("ROLE_USER"))
);
SecurityContextHolder.getContext().setAuthentication(authenticated);
try {
this.successHandler.onAuthenticationSuccess(request, response, authenticated);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
Registration model bean:
package com.eej.ssba2.model.test.zone4;
import java.io.Serializable;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import org.apache.log4j.Logger;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.eej.ssba2.ApplicationVersion;
/**
*
*
*/
public class RegisterModel implements Serializable{
private Logger logger = Logger.getLogger(this.getClass());
/**
*
*/
private static final long serialVersionUID = 1L;
#NotEmpty
#Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*" +
"#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$|")
public String mail1;
#NotEmpty
#Pattern(regexp = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*" +
"#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$|")
public String mail2;
#NotEmpty
public String password1;
#NotEmpty
public String password2;
// getters and setters
}
The Validator imiplementation I use to validate the fields in the model:
package com.eej.ssba2.model.test.zone4;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
public class RegisterModelValidator implements Validator {
#Override
public boolean supports(Class<?> arg0) {
return RegisterModel.class.equals(arg0);
}
#Override
public void validate(Object target, Errors errors) {
RegisterModel user = (RegisterModel) target;
if(!user.getMail1().equals(user.getMail2())){
errors.rejectValue("mail1", "lbl_mail1_and_mail2_must_be_equal");
errors.rejectValue("mail2", "lbl_mail1_and_mail2_must_be_equal");
}
if(!user.getPassword1().equals(user.getPassword2())){
errors.rejectValue("password1", "lbl_pass1_and_pass2_must_be_equal");
errors.rejectValue("password2", "lbl_pass1_and_pass2_must_be_equal");
}
}
Finally, the registration jsp:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags" %>
<%# 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>Login</title>
</head>
<body>
<form:form role="registerModel" commandName="registerModel" method="POST" action="${pageContext.request.contextPath}/zone4/simple/register.htm">
<form:errors path="*" cssClass="errorblock" element="div" />
<fieldset>
<div class="form-group">
<form:input path="mail1" id="mail1" name="mail1" placeHolder="email" />
<form:errors path="mail1" id="mail1" name="mail1" placeHolder="email" cssClass="error" />
</div>
<div class="form-group">
<form:input path="mail2" id="mail2" name="mail2" placeHolder="email" />
<form:errors path="mail2" id="mail2" name="mail2" placeHolder="email" cssClass="error" />
</div>
<div class="form-group">
<form:input path="password1" id="password1" name="password1" placeHolder="password" />
<form:errors path="password1" id="password1" name="password1" placeHolder="password" cssClass="error" />
</div>
<div class="form-group">
<form:input path="password2" id="password2" name="password2" placeHolder="password" />
<form:errors path="password2" id="password2" name="password2" placeHolder="password" cssClass="error" />
</div>
<div class="checkbox">
<label>
<input name="remember-me" id="remember-me" type="checkbox" value="Remember Me">Remember Me
</label>
</div>
<!-- Change this to a button or input when using this as a form -->
<button type="submit" class="btn btn-lg btn-success btn-block" name="submit"><spring:message code="lblRegistration"/></button>
</fieldset>
</form:form>
</body>
</html>

Spring Error in dynamic attributes

I work with Eclipse Juno, Spring 3.2.6.RELEASE, Weblogic 10.3.6.
I have the following jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<form:form id="create-survey" method="POST" action="/eusurvey/noform/management/createNewSurvey" style="display: none">
<input type="hidden" name="shortname" id="create-survey-shortname" value="" />
<input type="hidden" name="uuid" id="create-survey-uuid" value="" />
<input type="hidden" name="original" id="create-survey-original" value="" />
<input type="hidden" name="security" id="create-survey-security" value="" />
<input type="hidden" name="audience" id="create-survey-audience" value="" />
<input type="hidden" name="surveylanguage" id="create-survey-language" value="" />
<textarea style="display: none;" name="title" id="create-survey-title"></textarea>
<input type="hidden" name="listform" id="create-survey-listform" value="" />
<input type="hidden" name="contact" id="create-survey-contact" value="" />
<input type="hidden" name="contactlabel" id="create-survey-contact-label" value="" />
</form:form>
When I execute the application, I get the error:
weblogic.servlet.jsp.CompilationException: Failed to compile JSP /WEB-INF
/views/auth/tos.jsp
tos.jsp:79:21: Error in "menu.jsp" at line 358: The method
setDynamicAttribute(null, String, String) is undefined for the type FormTag
<%# include file="../menu.jsp" %>
^-----------^
at weblogic.servlet.jsp.JavelinxJSPStub.reportCompilationErrorIfNeccessary(JavelinxJSPStub.java:226)
at weblogic.servlet.jsp.JavelinxJSPStub.compilePage(JavelinxJSPStub.java:162)
at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:256)
at weblogic.servlet.jsp.JspStub.prepareServlet(JspStub.java:216)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:244)
at weblogic.servlet.internal.ServletStubImpl.onAddToMapException(ServletStubImpl.java:416)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:327)
at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:26)
at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.java:56)
What does this error mean?. What are dynamic attributes?
It looks to be a classloading issue between your Spring and the one bundled into JRF.
Similar questions:
Weblogic 10.3 issues with spring 3.1.0 jsp compilation
Weblogic 10.3.5 Overriding Spring Version
It looks the quicker solution is to filter with prefer-web-inf-classes tag at weblogic.xml

Resources