No Spring WebApplicationInitializer types detected on classpath

Wah, what a stupid error it was!

My Spring web app, which was running smoothly, refused to start. I don’t find any logs in log4j or tomcat log. Only clue I had was –

No Spring WebApplicationInitializer types detected on classpath

Here is how I solved it –

  1. Stop the tomcat
  2. Clean and build all eclipse projects
  3. Goto server tab and select the tomcat server. Press clean. Press clean work directory.
  4. Right click on the tomcat and remove it.
  5. Delete the tomcat from the eclipse run times
  6. Add tomcat server to the eclipse servers again
  7. Start the application

 

Advertisements

Spring Security

I have written about integrating Spring Security with Spring MVC earlier – https://javashine.wordpress.com/tag/spring-security/

Here is another step by step by instructions. This blog post assumes you already have a Spring MVC working in your workspace. This one uses annotation based configurations.

I have a simple test web application with two URLs.

/ (root URL)

/add_expense

While I’ll leave my / url unprotected, I want to secure /add_expense. Here is how we do it.

Adding Spring Security to Spring4 MVC

This is my project structure.

springmvc_spring_security

I wrote very simple MVC controller and it is working.

Add the following to Maven project dependencies.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.config.version}</version>
</dependency>

Under properties I’ve added this.

<spring.security.version>4.0.0.RELEASE</spring.security.version>

<spring.security.config.version>4.0.0.RELEASE</spring.security.config.version>

Following is the controller I’m going to secure. I’ll leave / open and protect /add_expense

springmvc_spring_security_1

Define a Spring security configuration. I have only one user admin.


package org.grassfield.gaja;


import org.springframework.beans.factory.annotation.Autowired;
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 {

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/add**").access("hasRole('ROLE_ADMIN')")
.and().formLogin();
}
}

Initialize security filter chain.


package org.grassfield.gaja;

import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends
AbstractSecurityWebApplicationInitializer {

}

Load the spring security to Spring MVC Application config. Check the highlighted path.

springmvc_spring_security_2

 

And finally load everything

package org.grassfield.gaja;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpringMvcInitializer extends
AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { ApplicationContextConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}

@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}

Capture

 

Capture

 

Capture

Capture

Way to go!

And, finally, here is the pic of the day.

CYmwbxbUQAAWCGH.jpg large
Learning something is a time machine that can bring you back to your school days!

Happy Pongal.
Happy Sankaranti.Happy Utarayan.

The request sent by the client was syntactically incorrect

This seems to be a common error during form submission in Spring WebMVC. Hence finding the root cause behind this may be difficult.

I verified step by step and confirmed that my call reaches my controller. But it breaks with the following error.

400 The request sent by the client was syntactically incorrect

Rightly pointed out at http://stackoverflow.com/questions/20616319/the-request-sent-by-the-client-was-syntactically-incorrect-spring-mvc-jdbc-te this is my date issue. I had a date field in my form. You can check my previous post on how to add jQuery date picker.

Hence, I need to make some modifications.

I added the following initBinder() method in the controller.

@RequestMapping(value="/add_expense", method=RequestMethod.POST)
    public String addExpense(@ModelAttribute ExpenseDetail expenseDetail, Model model) {
        try {
            System.out.println("===> returning add_expense"+expenseDetail.getExpenseCurrency());
            model.addAttribute("expenseList", new ExpenseDAO().getExpenseRecords());
            model.addAttribute("expenseDetail", new ExpenseDetail());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "home";
    }
    
    public void initBinder(WebDataBinder binder){
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        sdf.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

28-1406550815-malarmalaikal

Enjoy!

Spring mvc and jQuery DatePicker

We have added a simple CSS using the ResourceHandlers.  Now, it is the time to test jQuery on a Spring MVC. First Step is to display the calendar object on the jsp.

Spring mvc and jQuery DatePicker

Insert the scripts and CSS to head part of jsp

http://code.jquery.com/jquery-1.10.2.js
http://code.jquery.com/ui/1.11.0/jquery-ui.js

		<sc ript type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></sc ript>
		<sc ript type="text/javascript" src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></sc ript>
		<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">

Add the following javascript. Replace expenseDate with your field id

$(document).ready(function() {
$(function() {
$("#expenseDate").datepicker();
});
});

Thats all. The calendar object should rendered on the browser window.

Adding css ResourceHandlers in Spring

Task

CSS to be added to the Spring 4 JSPs

Steps

  1. Create folder called resources\theme1\css under webapp. (I use maven project)
    Adding css ResourceHandlers in Spring.PNG
  2. Create main.css under css folder
  3. Add the resource handler in the Application context config
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "org.grassfield.gaja" })
public class ApplicationContextConfig extends WebMvcConfigurerAdapter {
    @Bean(name = "viewResolver")
    public InternalResourceViewResolver getViewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        System.out.println("---> returning viewResolver");
        return viewResolver;
    }
    
    @Override
    public void addResourceHandlers(final ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").
        addResourceLocations("/resources/theme1/").
        setCachePeriod(31556926);
        System.out.println("---> returning resourcehandlers");
    }
}

21BGMCUBE_1904636e

 

 

Neither BindingResult nor plain target object for bean name ‘command’ available as request

Problem:

A JSP with spring form is not rendered properly.

<form:form action=”add_expense”>
<form:label path=”expenseDate”>Expense Date</form:label>
<form:input path=”expenseDate” />
<input type=”submit” />
</form:form>

28-1406551309-touristplaces

Error Message:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘command’ available as request attribute

Solution

I set the request attribute in a different name in the Controller bean.

modelAndView.addObject(“expenseDetail”, new ExpenseDetail());
return modelAndView;

I set the required parameter by name expenseDetail. Hence the form tag was re-written as given below.

<form:form action=”add_expense” commandName=”expenseDetail”>

ModelAndView object is not printed on JSP

I am bundling my ModelAndView with my output as below.

modelAndView.addObject("expenseList", new ExpenseDAO().getExpenseRecords());

When I try to retrieve it in jsp as ${expenseList}, it is just printed as ${expenseList}, not the real value.

WR_20140702011432

Thanks to mkyong who mentioned that it is disabled in jsp 1.x. We need to enable EL explicitly with the follwing tag.

<%@ page isELIgnored="false" %>