Spring Multipart File Upload - spring

I'm trying to upload a MultipartFile using Spring MVC, tomcat, Tyhmleaf but can't get it work.
java.lang.NullPointerException
com.cars.actions.controller.brand.BrandController.persist2(BrandController.java:75)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:483)
My controller:
#RequestMapping(value = "/addimage", method = RequestMethod.POST)
public String persist2( #Valid #ModelAttribute("brand") BrandDTO brandDTO, BindingResult result, RedirectAttributes redirectAttrs, Model model) {
if (result.hasErrors()) {
if (!brandDTO.getFile().isEmpty()) { // null pointer exception
errorNotValid(model, "");
return ADD_PAGE;
} else {
try {
BufferedImage src = ImageIO.read(new ByteArrayInputStream(brandDTO.getFile().getBytes()));
File destination = new File("/Users/katsu/Desktop/file/");
ImageIO.write(src, "png", destination);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
Brand brand = getEntity(brandDTO);
service.save(brand);
successAddMesage(model, "succes");
model.addAttribute(businessObject, new Brand());
return ADD_PAGE;
} catch (DuplicateItemFoundException e) {
errorDuplicateMessage(redirectAttrs, "dublucate");
return REDIRECT_LIST_PAGE;
}
}
}
My DTO:
public class BrandDTO {
private Integer id;
private String name;
private boolean enabled;
private CommonsMultipartFile file;
Apliaiton iniliaze:
public class ApplicationInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
// Register the Root application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootConfig.class);
// Register the Web application context
AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
mvcContext.register(WebAppConfig.class);
// Context loader listener
//servletContext.addListener(new ContextLoaderListener(rootContext));
// Register the Dandelion filter
FilterRegistration.Dynamic dandelionFilter = servletContext.addFilter("dandelionFilter", new DandelionFilter());
dandelionFilter.addMappingForUrlPatterns(null, false, "/*");
// Register the Spring dispatcher servlet
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("springServlet", new DispatcherServlet(mvcContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
//dispatcher.setMultipartConfig(rootContext.getBean(Multi));
// Register the Dandelion servlet
ServletRegistration.Dynamic dandelionServlet = servletContext.addServlet("dandelionServlet",new DandelionServlet());
dandelionServlet.setLoadOnStartup(2);
dandelionServlet.addMapping("/dandelion-assets/*");
}
My Web initialize:
#Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver resolver=new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxUploadSize(40000000);
return resolver;
}
My Form:
<form class="mainForm" action="#" data-th-action="#{/admin/brand/addimage}" data-th-object="${brand}" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<!-- Input text fields -->
<fieldset>
<div class="widget first">
<div class="head">
<h5 class="iList">Marka Ekleme</h5>
</div>
<div class="rowElem">
<label>Marka Adı:</label>
<div class="formRight">
<input type="text" placeholder="adını giriniz" data-th-value="*{name}" data-th-field="*{name}" />
<span th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</span>
</div>
<div class="fix"></div>
</div>
<div class="rowElem">
<label>Marka Logo:</label>
<div class="formRight">
<input type="file" data-th-field="*{file}"/>
</div>
<div class="fix"></div>
</div>
<div class="rowElem">
<label>Aktif Mi:</label>
<div class="formRight">
<select class="select2" title="Click to Select a City" th:field="*{enabled}">
<option th:each="type : ${enabledOptions}" th:value="${type}" th:text="${type}">Dropdown</option>
</select>
</div>
<div class="fix"></div>
</div>
<input type="submit" value="Submit form" class="greyishBtn submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
and last tomcat permission:
<Context allowCasualMultipartParsing="true">
I digging all internet but cant resolve this problem. whats my wrong?

Try to replace
#ModelAttribute BrandDTO brandDTO
with
#ModelAttribute("brand") BrandDTO brandDTO
Currently your controller expects a model attribute named "brandDTO" which is null since without explicit naming it is derived from the argument type. But in your form you set a data-th-object=${brand}.
If instead you keep the brandDTO name for the attribute and rename your th object in the page you better change :
data-th-field="${brand.file}"
to:
data-th-field="*{file}"

Related

Request method 'GET' not supported Spring Boot

I'm a beginer full stack developer. I need help.
I have the following code:
Controller:
#Controller
public class GreetingController {
#Autowired
private MessageRepos messageRepos;
#GetMapping("/")
public String greeting(Map<String, Object> model) {
return "greeting";
}
#GetMapping("/main")
public String main(Map<String, Object> model) {
Iterable<Message> messages = messageRepos.findAll();
model.put("messages", messages);
return "main";
}
#PostMapping("/main")
public String add(#RequestParam String text, #RequestParam String tag, Map<String, Object> model) {
Message message = new Message(text, tag);
messageRepos.save(message);
Iterable<Message> messages = messageRepos.findAll();
model.put("messages", messages);
return "main";
}
#PostMapping("filter")
public String filter(#RequestParam String filter, Map<String, Object> model) {
Iterable<Message> messages;
if (filter != null && !filter.isEmpty()) {
messages = messageRepos.findByTag(filter);
} else {
messages = messageRepos.findAll();
}
model.put("messages", messages);
return "main";
}
HTML:
</div>
<div>
<form method="post">
<input type="text" name="text" placeholder="Message" />
<input type="text" name="tag" placeholder="Tag">
<button type="submit">Add</button>
</form>
</div>
<div>
<form method="post" action="filter">
<input type="text" name="filter">
<button type="submit">Find</button>
</form>
</div>
When I click on the buttons add and find I get the problem.
Problem:
Request method 'GET' not supported.

Spring tags form do not show validation errors in jsp

I am writing a page with user registration. Faced a display problem in the form of validation errors
My Controller:
#Controller
public class UIController {
private final Logger log = LoggerFactory.getLogger(getClass());
#Autowired
private UserService service;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator validator;
#PostMapping(value = "/login")
public String signIn(#ModelAttribute("userForm") UserTo userForm, BindingResult bindingResult, Model model) {
validator.validate(userForm, bindingResult);
User user = service.findByLogin(UserUtil.createNewFromTo(userForm).getLogin());
if (!userForm.getPassword().equals(user.getPassword())) {
log.info("invalid password {}", user);
return "redirect:/login";
}
log.info("signIn {}", user);
securityService.autologin(user.getLogin(), user.getPassword());
return "redirect:/welcome";
}
}
My Validator:
#Component
public class UserValidator implements Validator {
#Autowired
private UserRepositoryImpl userRepository;
#Override
public boolean supports(Class<?> aClass) {
return UserTo.class.equals(aClass);
}
#Override
public void validate(Object o, Errors errors) {
UserTo user = (UserTo) o;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "login", "NotEmpty");
if (user.getLogin().length() < 6 || user.getLogin().length() > 32) {
errors.rejectValue("login", "Size.userForm.login");
}
if (userRepository.findByLogin(user.getLogin()) != null) {
errors.rejectValue("login", "Duplicate.userForm.login");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
if (user.getPassword().length() < 8 || user.getPassword().length() > 32) {
errors.rejectValue("password", "Size.userForm.password");
}
}
}
My jsp form :
<div id="wrapper">
<!--SLIDE-IN ICONS-->
<div class="user-icon"></div>
<div class="pass-icon"></div>
<!--END SLIDE-IN ICONS-->
<!--LOGIN FORM-->
<form:form name="login-form" modelAttribute="userForm" class="login-form" method="post" id="form">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<!--CONTENT-->
<div class="content">
<!--USERNAME-->
<spring:bind path="login">
<div class="form-group ${status.error ? 'has-error' : ''}">
<form:input name="login" id="login" type="text" path="login" class="input username"
placeholder="Login"></form:input>
<form:errors path="login"></form:errors>
</div>
</spring:bind>
<!--END USERNAME-->
</div>
<!--END CONTENT-->
<!--FOOTER-->
<div class="footer">
<button class="button" type="submit">Login</button>
<button class="register" type="button" name="submit" onclick=" register_url('${contextPath}/registration')">
Register
</button>
</div>
<!--END FOOTER-->
</form:form>
</div>
When debugging in chrome when sending a POST request, a 302 HTTP error appears.
Accordingly, if I set a breakpoint in the controller, then the debug is not processed.
Tell me what could be the problem?
The "form" tag in your jsp does not have "action" attribute.
You should not redirect on errors, because the redirect will erase the binding result. Instead do :
if (!userForm.getPassword().equals(user.getPassword())) {
log.info("invalid password {}", user);
return "login";
}

form:errors are not displaying errors on JSP in Spring

I can not get the validation error messages to be showed in JSP page. The validation is working but messages are not getting displayed at all.
SystemValidator class :
#Override
public void validate(Object target, Errors errors) {
SystemUser systemUser = (SystemUser) target;
SystemUser user = systemUserRepository.findByUsername(systemUser.getUsername());
if (user != null && !(user.getId() == systemUser.getId()) || superUserName.equalsIgnoreCase(systemUser.getUsername())) {
errors.rejectValue("username", "Duplicate Username");
}
}
the view :
<form:form method="post" modelAttribute="user" action="addUser">
<div class="form-group">
<label for="username" class="col-form-label">User Name</label>
<form:input type="text" required="required" class="form-control" id="username" path="username"/>
<form:errors path = "username" cssClass = "error" />
</div>
<form:input type="hidden" id="id" name="id" path="id"/>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form:form>
the controller class :
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String saveUser(Model model, #Validated #ModelAttribute("user") SystemUser user, BindingResult result) {
logger.info("User save/update request received [{}]", user.toString());
if (result.hasErrors()) {
loadData(model);
model.addAttribute("user", user);
return "users";
}
systemUserService.saveSystemUser(user);
loadData(model);
return "users";
}
private void loadData(Model model) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("user", new SystemUser());
}
Use #Valid instead of #Validated like below.
#RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String saveUser(#Valid #ModelAttribute("user") SystemUser user, BindingResult result,Model model)
Don't do model.addAttribute("user", new SystemUser()); when validation error occurs.
Change to this:
if (result.hasErrors()) {
loadData(model, user);
return "users";
}
And:
private void loadData(Model model, User user) {
model.addAttribute("users", systemUserService.getAllUsers());
model.addAttribute("user", user);
}

Spring Boot multiple controllers with same mapping

My problem is very similar with this one: Spring MVC Multiple Controllers with same #RequestMapping
I'm building simple Human Resources web application with Spring Boot. I have a list of jobs and individual url for each job:
localhost:8080/jobs/1
This page contains job posting details and a form which unauthenticated users -applicants, in this case- can use to apply this job. Authenticated users -HR Manager-, can see only posting details, not the form. I have trouble with validating form inputs.
What I tried first:
#Controller
public class ApplicationController {
private final AppService appService;
#Autowired
public ApplicationController(AppService appService) {
this.appService = appService;
}
#RequestMapping(value = "/jobs/{id}", method = RequestMethod.POST)
public String handleApplyForm(#PathVariable Long id, #Valid #ModelAttribute("form") ApplyForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "job_detail"; //HTML page which contains job details and the application form
}
appService.apply(form, id);
return "redirect:/jobs";
}
#RequestMapping(value = "/applications/{id}", method = RequestMethod.GET)
public ModelAndView getApplicationPage(#PathVariable Long id) {
if (null == appService.getAppById(id)) {
throw new NoSuchElementException(String.format("Application=%s not found", id));
} else {
return new ModelAndView("application_detail", "app", appService.getAppById(id));
}
}
}
As you guess this didn't work because I couldn't get the models. So I put handleApplyForm() to JobController and changed a little bit:
#Controller
public class JobController {
private final JobService jobService;
private final AppService appService;
#Autowired
public JobController(JobService jobService, AppService appService) {
this.jobService = jobService;
this.appService = appService;
}
#RequestMapping(value = "/jobs/{id}", method = RequestMethod.POST)
public ModelAndView handleApplyForm(#PathVariable Long id, #Valid #ModelAttribute("form") ApplyForm form, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return getJobPage(id);
}
appService.apply(form, id);
return new ModelAndView("redirect:/jobs");
}
#RequestMapping(value = "/jobs/{id}", method = RequestMethod.GET)
public ModelAndView getJobPage(#PathVariable Long id) {
Map<String, Object> model = new HashMap<String, Object>();
if (null == jobService.getJobById(id)) {
throw new NoSuchElementException(String.format("Job=%s not found", id));
} else {
model.put("job", jobService.getJobById(id));
model.put("form", new ApplyForm());
}
return new ModelAndView("job_detail", model);
}
}
With this way, validations works but I still can't get the same effect here as it refreshes the page so that all valid inputs disappear and error messages don't appear.
By the way, job_detail.html is like this:
<h1>Job Details</h1>
<p th:inline="text"><strong>Title:</strong> [[${job.title}]]</p>
<p th:inline="text"><strong>Description:</strong> [[${job.description}]]</p>
<p th:inline="text"><strong>Number of people to hire:</strong> [[${job.numPeopleToHire}]]</p>
<p th:inline="text"><strong>Last application date:</strong> [[${job.lastDate}]]</p>
<div sec:authorize="isAuthenticated()">
<form th:action="#{/jobs/} + ${job.id}" method="post">
<input type="submit" value="Delete this posting" name="delete" />
</form>
</div>
<div sec:authorize="isAnonymous()">
<h1>Application Form</h1>
<form action="#" th:action="#{/jobs/} + ${job.id}" method="post">
<div>
<label>First name</label>
<input type="text" name="firstName" th:value="${form.firstName}" />
<td th:if="${#fields.hasErrors('form.firstName')}" th:errors="${form.firstName}"></td>
</div>
<!-- and other input fields -->
<input type="submit" value="Submit" name="apply" /> <input type="reset" value="Reset" />
</form>
</div>
Check thymeleaf documentation here
Values for th:field attributes must be selection expressions (*{...}),
Also ApplyForm is exposed then you can catch it in the form.
Then your form should looks like this:
<form action="#" th:action="#{/jobs/} + ${job.id}" th:object="${applyForm}" method="post">
<div>
<label>First name</label>
<input type="text" name="firstName" th:value="*{firstName}" />
<td th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}"></td>
</div>
<!-- and other input fields -->
<input type="submit" value="Submit" name="apply" /> <input type="reset" value="Reset" />
</form>

HDIV + Spring tag library (form) = Error, possible bug?

I'm finding troubles using HDIV with the tag Spring element: "< form:form >".
First, I'm going to explain the architecture of my application:
I'm using Spring framework 4.1.6, Spring Security 4.0.0 and HDIV 2.1.10.
So far I'm not having errors during the development, nevertheless now I 've found one in a jsp file, when I'm using the form tag from Spring:
<form:form
action="${pageContext.servletContext.contextPath}/newUser"
method="POST" class="form-horizontal" commandName="user">
I obtained this error in the line 34: "< form:form "
java.lang.NullPointerException at
org.hdiv.web.servlet.support.HdivRequestDataValueProcessor.processAction(HdivRequestDataValueProcessor.java:122)
at
org.springframework.web.servlet.tags.form.FormTag.processAction(FormTag.java:479)
at
org.springframework.web.servlet.tags.form.FormTag.resolveAction(FormTag.java:433)
at
org.springframework.web.servlet.tags.form.FormTag.writeTagContent(FormTag.java:349)
at
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at
org.apache.jsp.WEB_002dINF.jsp.newUser_jsp._jspx_meth_form_005fform_005f0(newUser_jsp.java:197)
at
org.apache.jsp.WEB_002dINF.jsp.newUser_jsp._jspService(newUser_jsp.java:137)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
and more at.....(if it's necessary, I can provide it)
When I try the same code, but exchanging the tag "< form:form >" for the tag "< form >" It works.
When I examined in detail the code from HDIV:
HdivRequestDataValueProcessor.class
public class HdivRequestDataValueProcessor implements RequestDataValueProcessor
protected LinkUrlProcessor linkUrlProcessor;
protected FormUrlProcessor formUrlProcessor;
if (this.innerRequestDataValueProcessor != null) {
String processedAction = this.innerRequestDataValueProcessor.processAction(request, action, method);
if (processedAction != action) {
action = processedAction;
}
}
String result = this.formUrlProcessor.processUrl(request, action, method);//line 122
return result;
}
I wondered that maybe due to the fact that 'form:form' has a different structure than 'form', HDIV cannot find some parameters such as 'action', 'method'...But I'm not sure.
Also I attached my config files to provide more useful information (Java-based Config):
WebApplicationInit.class
import javax.servlet.Filter;
import javax.servlet.ServletContext;
import org.hdiv.filter.ValidatorFilter;
import org.hdiv.listener.InitListener;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebApplicationInit extends
AbstractAnnotationConfigDispatcherServletInitializer {
// http://www.robinhowlett.com/blog/2013/02/13/spring-app-migration-from-xml-to-java-based-config/
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class, DatabaseConfig.class,
SecurityConfig.class, HdivSecurityConfig.class };
// , HdivSecurityConfig.class
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { MvcConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
//web.xml filter
#Override
protected Filter[] getServletFilters(){
return new Filter[] { new ValidatorFilter()};
}
// web.xml listener
#Override
protected void registerDispatcherServlet(ServletContext servletContext) {
super.registerDispatcherServlet(servletContext);
servletContext.addListener(InitListener.class);
}
}
HdivSecurityConfig.class
#Configuration
#EnableHdivWebSecurity
public class HdivSecurityConfig extends HdivWebSecurityConfigurerAdapter {
#Override
public void addExclusions(ExclusionRegistry registry) {
registry.addUrlExclusions("/login").method("GET");
registry.addUrlExclusions("/newUser").method("GET");
registry.addUrlExclusions("/newUser").method("POST");
registry.addUrlExclusions("/about").method("GET");
registry.addUrlExclusions("/resources/.*").method("GET");
registry.addUrlExclusions("/bst-lib/.*").method("GET");
registry.addUrlExclusions("/images/.*").method("GET");
}
#Override
public void configure(SecurityConfigBuilder builder) {
//the session has expired, go to login again
builder.sessionExpired().homePage("/").loginPage("/login");
//Execution strategy
builder.strategy(Strategy.CIPHER);
//error page
builder.errorPage("/error");
}
}
SecurityConfig.class
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DriverManagerDataSource myWebAppDataSource;
#Autowired
private MyWebAppSimpleAuthenticationProvider myWebAppAuthenticationProvider;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth)
throws Exception {
auth.authenticationProvider(myWebAppAuthenticationProvider);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resources/**", "/bst-lib/**", "/images/**",
"/about", "/newUser").permitAll().anyRequest()
.authenticated().and().formLogin().loginPage("/login")
.permitAll();
}
}
SecurityWebApplicationInit.class
public class SecurityWebApplicationInit extends
AbstractSecurityWebApplicationInitializer {}
Thank you in advance!!
Best Regards,
Alberto
----EDIT---
Following the given example, This is now my code:
WebApplicationInit.class
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebApplicationInit extends
AbstractAnnotationConfigDispatcherServletInitializer {
// http://www.robinhowlett.com/blog/2013/02/13/spring-app-migration-from-xml-to-java-based-config/
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class, DatabaseConfig.class,
SecurityConfig.class, HdivSecurityConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { MvcConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected String getServletName(){
return "myDispatcher";
}
}
HDIVSecurityConfig.class
import org.hdiv.config.Strategy;
import org.hdiv.config.annotation.EnableHdivWebSecurity;
import org.hdiv.config.annotation.ExclusionRegistry;
import org.hdiv.config.annotation.RuleRegistry;
import org.hdiv.config.annotation.ValidationConfigurer;
import org.hdiv.config.annotation.builders.SecurityConfigBuilder;
import org.hdiv.config.annotation.configuration.HdivWebSecurityConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
#Configuration
#EnableHdivWebSecurity
public class HdivSecurityConfig extends HdivWebSecurityConfigurerAdapter {
#Override
public void addExclusions(ExclusionRegistry registry) {
registry.addUrlExclusions("/login").method("GET");
registry.addUrlExclusions("/newUser").method("GET");
registry.addUrlExclusions("/newUser").method("POST");
registry.addUrlExclusions("/about").method("GET");
registry.addUrlExclusions("/resources/.*").method("GET");
registry.addUrlExclusions("/bst-lib/.*").method("GET");
registry.addUrlExclusions("/images/.*").method("GET");
registry.addParamExclusions("_csrf");
}
#Override
public void configure(SecurityConfigBuilder builder) {
// the session has expired, go to login again
builder.sessionExpired().homePage("/").loginPage("/login");
// Execution strategy
builder.strategy(Strategy.MEMORY);
builder.maxPagesPerSession(5);
// error page
builder.errorPage("/error");
}
#Override
public void addRules(RuleRegistry registry) {
//registry.addRule("safeText").acceptedPattern("^[a-zA-Z0-9#.\\-_]*$");
}
#Override
public void configureEditableValidation(
ValidationConfigurer validationConfigurer) {
validationConfigurer.addValidation("/.*");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>myWebApp</display-name>
<listener>
<listener-class>org.hdiv.listener.InitListener</listener-class>
</listener>
<!-- HDIV Validator Filter -->
<filter>
<filter-name>ValidatorFilter</filter-name>
<filter-class>org.hdiv.filter.ValidatorFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ValidatorFilter</filter-name>
<servlet-name>myDispatcher</servlet-name>
</filter-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://java.sun.com/jsp/jstl/core</taglib-uri>
<taglib-location>/WEB-INF/tlds/hdiv-c.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
newUser.jsp
<form:form
action="${pageContext.servletContext.contextPath}/newUser"
method="POST" class="form-horizontal" commandName="user">
<div class="form-group">
<label for="inputName"
class="col-sm-offset-2 col-sm-2 control-label">Name:</label>
<div class="col-sm-6">
<form:input class="form-control" id="inputName"
placeholder="Name" path="name" />
</div>
</div>
<div class="form-group">
<label for="inputSurname"
class="col-sm-offset-2 col-sm-2 control-label">Surname:</label>
<div class="col-sm-6">
<form:input class="form-control" id="inputSurname"
placeholder="Surname" path="surname" />
</div>
</div>
<div class="form-group">
<label for="inputOrganisation"
class="col-sm-offset-2 col-sm-2 control-label">Organization:</label>
<div class="col-sm-6">
<form:input class="form-control" id="inputOrganisation"
placeholder="Organization" path="organization" />
</div>
</div>
<div class="form-group">
<label for="inputEmail"
class="col-sm-offset-2 col-sm-2 control-label">Email:</label>
<div class="col-sm-6">
<form:input type="email" class="form-control" id="inputEmail"
placeholder="Email" path="email" />
</div>
</div>
<div class="form-group">
<label for="inputPassword"
class="col-sm-offset-2 col-sm-2 control-label">Password:</label>
<div class="col-sm-6">
<form:password class="form-control" id="inputPassword"
placeholder="Password" path="password" />
</div>
</div>
<div class="form-group">
<label for="inputRPassword"
class="col-sm-offset-2 col-sm-2 control-label">Repeat
Password:</label>
<div class="col-sm-6">
<form:password class="form-control" id="inputRPassword"
placeholder="Repeat Password" path="rPassword" />
</div>
</div>
<div class="col-sm-offset-4 col-sm-8">
<button type="submit" class="btn btn-default login-button">Sing
in</button>
<button type="button" class="btn btn-default login-button"
onclick="clearAll()">Clear All</button>
<button type="button" class="btn btn-default login-button"
onclick="comeBack()">Come Back</button>
</div>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form:form>
MvcConfig.class
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "com.ec.myWebApp" })
public class MvcConfig extends WebMvcConfigurerAdapter {
#Autowired
/*
* If I use this commented line, The application fails due to the fact that the bean "hdivEditableValidator" can't be found...If I don't use the tag "Qualifier" it does not fail
*/
// #Qualifier("hdivEditableValidator")
private Validator hdivEditableValidator;
// View Name -> View
#Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
// static resources
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations(
"/public-resources/");
registry.addResourceHandler("/bst-lib/**").addResourceLocations(
"/public-resources/lib/bootstrap-3.3.2-dist/");
registry.addResourceHandler("/images/**").addResourceLocations(
"/public-resources/images/");
}
#Bean
public MultipartResolver multipartResolver() {
HdivCommonsMultipartResolver resolver = new HdivCommonsMultipartResolver();
resolver.setMaxUploadSize(100000);
return resolver;
}
#Override
public Validator getValidator() {
return hdivEditableValidator;
}
}
I changed the way to add the HDIV to my Web Application, adding it in the xml file, instead of doing that in using java-based configuration. Additionally, I added the Qualifier tag (MvcConfig.class), using the example, but it does not work when I use it...(It can not find the bean...).
The null error hasn't disappeared...
The problem has been solved changing this line:
#ComponentScan(basePackages = { "com.ec.myWebApp" })
in the class: MvcConfing, for this:
#ComponentScan(basePackages = { "com.ec.myWebApp.controllers",
"com.ec.myWebApp.dao", "com.ec.myWebApp.services" })
My original line scanned twice the HDIV config class, first during the context creation and the second one by the "#ComponentScan". This gave place to an incorrect initialization. So, the config package was used twice, instead of once.
Thank you.

Resources