lundi 20 avril 2015

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://ift.tt/1EjlMDd

@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://ift.tt/1EjlMDd

@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://ift.tt/ra1lAU"
xmlns="http://ift.tt/19L2NlC"
xsi:schemaLocation="http://ift.tt/19L2NlC     http://ift.tt/1drxgYl"
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://ift.tt/1vL9NML;
        <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...

Aucun commentaire:

Enregistrer un commentaire