Rectangle 27 3

Now you can to tell Spring that you'd like to handle this, by creating a new method, as follows:

@ExceptionHandler(MethodArgumentNotValidException.class)
public String handleValidation(MethodArgumentNotValidException e, ModelMap map) {
    List<ObjectError> errors = e.getBindingResult() .getAllErrors();
    // your code here...
    return "path/to/your/view";
}

Finally, have a read of the Spring docs wrt @ExceptionHandler. There's most likely some useful information there.

Thanks for the info. I am using Spring 3.0.3.. MethodArgumentNotValidException is available only in v3.1 I suppose.. I will not be able to change the spring version as there is a framework on top of the mvc development which is not in my control..Also, in my controller, I don't give the view name as such. I just set the attributes in the model map and the front end template reads the map for the necessary info. Does the return type of methods annotated with @ExceptionHandler should always be a String ?

String
ModelAndView
Map
@RequestMapping(produces="application/json")
@ResponseBody

oh ok... But I am not suign Spring 3.1. So, I wont be able to use MethodArgumentNotValidException. is there anything that I can do to catch the binding issues ?

You might be able to create your own binder for TestJSONRequest if it's the binding that's failing. Have a look at @InitBinder. As always with Spring, you'll be able to get a solution, but the challenge is finding the correct entry point in the Spring framework! Sometimes a bit of debugging is required.

Am not sure how to achieve this by InitBinder ... Should we write custom editor class for each type we use in the Input JSON request... Is there any other efficient way? When ever binding failed, it threw a org.codehaus.JSonMappingException. I tried to get this exception in the method annotated with @ExceptionHandler but the control never came to the method...

java - Data Binding Error Handling in Spring MVC - Stack Overflow

java spring java-ee spring-mvc spring-webflow
Rectangle 27 85

You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.

java - @RequestParam in Spring MVC handling optional parameters - Stac...

java spring spring-mvc
Rectangle 27 28

With Spring Boot 1.4+ new cool classes for easier exception handling were added that helps in removing the boilerplate code.

A new @RestControllerAdvice is provided for exception handling, it is combination of @ControllerAdvice and @ResponseBody. You can remove the @ResponseBody on the @ExceptionHandler method when use this new annotation.

@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse unknownException(Exception ex, WebRequest req) {
        return new ApiErrorResponse(...);
    }
}
@EnableWebMvc
spring.mvc.throw-exception-if-no-handler-found=true

That's really helpful, thank you. But I didn't get why we need to ` @EnableWebMvc ` with ` spring.mvc.throw-exception-if-no-handler-found=true ` . My expectation was to handle all exceptions via @RestControllerAdvice without additional configuration. What am I missing here?

java - Spring Boot REST service exception handling - Stack Overflow

java spring rest exception-handling spring-boot
Rectangle 27 40

As part of Spring 4.1.1 onwards you now have full support of Java 8 Optional (original ticket) therefore in your example both requests will go via your single mapping endpoint as long as you replace required=false with Optional for your 3 params logout, name, password:

@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,   
 produces="text/xml")
public String showLoginWindow(@PathVariable("id") String id,
                              @RequestParam(value = "logout") Optional<String> logout,
                              @RequestParam("name") Optional<String> username,
                              @RequestParam("password") Optional<String> password,
                              @ModelAttribute("submitModel") SubmitModel model,
                              BindingResult errors) throws LoginException {...}

Hi, @dimitrisli. I am using @PathVariable("idOfUser") Optional<String> idOfUser. Now I need to fetch/print the value of idOfuser. Can you kindly help me this, because right now after printing I am getting Optional[1234], but what I actually want is just 1234.

@VibhavChaddha you can use something like this: if (idOfUser.isPresent()){ System.out.println("idOfUser: "+ idOfUser.get()); }

java - @RequestParam in Spring MVC handling optional parameters - Stac...

java spring spring-mvc
Rectangle 27 29

Create 2 methods which handle the cases. You can instruct the @RequestMapping annotation to take into account certain parameters whilst mapping the request. That way you can nicely split this into 2 methods.

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"logout"})
public String handleLogout(@PathVariable("id") String id, 
        @RequestParam("logout") String logout) { ... }

@RequestMapping (value="/submit/id/{id}", method=RequestMethod.GET, 
                 produces="text/xml", params={"name", "password"})
public String handleLogin(@PathVariable("id") String id, @RequestParam("name") 
        String username, @RequestParam("password") String password, 
        @ModelAttribute("submitModel") SubmitModel model, BindingResult errors) 
        throws LoginException {...}
!myParam style expressions indicate that the 	 * specified parameter is not supposed to be present in the request.

It will find the best match, it probably will try to use the handleLogin else it will give an exception stating no mapping can be found.

Just one note: from the security perspective logout should only accept POST requests, so there should be 2 methods and it doesn't make any sense to keep their URL the same then.

java - @RequestParam in Spring MVC handling optional parameters - Stac...

java spring spring-mvc
Rectangle 27 22

With Spring Boot 1.4+ new cool classes for easier exception handling were added that helps in removing the boilerplate code.

A new @RestControllerAdvice is provided for exception handling, it is combination of @ControllerAdvice and @ResponseBody. You can remove the @ResponseBody on the @ExceptionHandler method when use this new annotation.

@RestControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(value = { Exception.class })
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiErrorResponse unknownException(Exception ex, WebRequest req) {
        return new ApiErrorResponse(...);
    }
}
@EnableWebMvc
spring.mvc.throw-exception-if-no-handler-found=true

That's really helpful, thank you. But I didn't get why we need to ` @EnableWebMvc ` with ` spring.mvc.throw-exception-if-no-handler-found=true ` . My expectation was to handle all exceptions via @RestControllerAdvice without additional configuration. What am I missing here?

java - Spring Boot REST service exception handling - Stack Overflow

java spring rest exception-handling spring-boot
Rectangle 27 6

I use jersey2.11 with Tomcat and almost exception handle with ExceptionMapper. (In domain logic, only DB rollback process use try-catch code.)

I think ExceptionMapper with @Provider automatically choose correct ExceptionMapper. So I suppose this function is satisfied with "I want to catch more CMIS exception or default Exception or IO Exception etc."

@GET
@Produces("application/json")
public String getUser(@NotNull @QueryParam("id") String id, 
  @NotNull @QueryParam("token") String token) throws Exception { // This level throws exceptions handled by ExceptionMapper

  someComplexMethod(id, token); // possible throw Exception, IOException or other exceptions.

  return CLICHED_MESSAGE;
}
public abstract class AbstractExceptionMapper {
  private static Logger logger = LogManager.getLogger(); // Example log4j2.

  protected Response errorResponse(int status, ResponseEntity responseEntity) {
    return customizeResponse(status, responseEntity);
  }

  protected Response errorResponse(int status, ResponseEntity responseEntity, Throwable t) {
    logger.catching(t); // logging stack trace.

    return customizeResponse(status, responseEntity);
  }

  private Response customizeResponse(int status, ResponseEntity responseEntity) {
     return Response.status(status).entity(responseEntity).build();
  }
 }

ExceptionMapper.java (At least this mapper can catch any exception which is not define specify exception mapper.)

@Provider
 public class ExceptionMapper extends AbstractExceptionMapper implements
 javax.ws.rs.ext.ExceptionMapper<Exception> {

 @Override
 public Response toResponse(Exception e) {
 // ResponseEntity class's Member Integer code, String message, Object data. For response format.
 ResponseEntity re = new ResponseEntity(Code.ERROR_MISC); 

  return this.errorResponse(HttpStatus.INTERNAL_SERVER_ERROR_500, re, e);
 }
}
@Provider
public class WebApplicationExceptionMapper extends AbstractExceptionMapper implements
    ExceptionMapper<WebApplicationException> {

  @Override
  public Response toResponse(WebApplicationException e) {
    ResponseEntity re = new ResponseEntity(Code.ERROR_WEB_APPLICATION);

    return this.errorResponse(e.getResponse().getStatus(), re, e);
  }
}
@Provider
public class ConstraintViolationExceptionMapper extends AbstractExceptionMapper implements
    ExceptionMapper<ConstraintViolationException> {

  @Override
  public Response toResponse(ConstraintViolationException e) {
    ResponseEntity re = new ResponseEntity(Code.ERROR_CONSTRAINT_VIOLATION);

    List<Map<String, ?>> data = new ArrayList<>();
    Map<String, String> errorMap;
    for (final ConstraintViolation<?> error : e.getConstraintViolations()) {
      errorMap = new HashMap<>();
      errorMap.put("attribute", error.getPropertyPath().toString());
      errorMap.put("message", error.getMessage());
      data.add(errorMap);
    }

    re.setData(data);

    return this.errorResponse(HttpStatus.INTERNAL_SERVER_ERROR_500, re, e);
  }
}

.. and other specify exception can create ExceptionMapper classes.

In my experience, Exception Mapper is high level idea for focus to domain logic. It could drive out boring scattered try-catch block code from domain logic. So I hope that you feel the "Yes i am" at Question 3 to resolve the problem at your environment.

you have not used try catch and throw anywhere across the application.

My code design use throws at method like this and this make to manage by ExceptionMapper classes.

public String getUser(@NotNull @QueryParam("id") String id, 
  @NotNull @QueryParam("token") String token) throws Exception

So in above approach I have created just 1 class for all the exceptions which I could expect and for any unknown exception the base Exception will be there to catch. Now wherever in my application if any exception occurs it comes to the CentralControllerException and appropriate response with http status code is sent back. Q.2. Do you foresee any issue in above approach.

I think if simple project or never update/modify project (project lifecycle short time), your one class exception mapper approach ok. But ... i never take this approach. Simply, if need to manage more exception, this method become big and complex, and hard to read and maintain becoming.

In my policy, OOP should use pleomorphism strategy any level code(class plan, DI plan) and this approach some part aim to drive out if/switch block in code. And this idea make each method short code and simple, clear to "domain logic" and code become to resistant to modify.

So i create implements ExceptionMapper and delegate to DI which ExceptionMapper class manage to exception. (So DI manage replace your single class If block manage which exception handling, this is typically refactoring approach similar Extract xxx http://refactoring.com/catalog/extractClass.html. In our discussion case, single class and one method too busy, so extract each ExceptionMapper class approaching and DI call suitable class & method strategy.)

from which lib does the 'Code' class in your example (Code.ERROR_MISC) comes from?

java - Global Exception Handling in Jersey & Spring? - Stack Overflow

java spring rest jersey-2.0
Rectangle 27 1

You should change the scope level of the two controller methods to public. Right now, they don't have any, so the methods are package local by default.

public String testPost(@RequestParam("param1") String param1, @RequestParam("param2") String param2) {
public String testGet(@RequestParam String param1) {

The problem is the Application is NOT even a Controller (or RestController for that matter), so changing the visibility would not have any effect. By the way, the default visibility is package local not protected.

RestController
Application

oh yeah, just saw that he is even missing the RestController annotation.

public
package local

RequestMapping GET and POST methods handling in Spring REST - Stack Ov...

spring rest spring-boot
Rectangle 27 1

Add a RestController or Controller stereotype annotation to your Application class like this:

@RestController
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
...
}

Note: You can use SpringBootApplication meta annotation instead of those three, so you would have:

@RestController
@SpringBootApplication
public class Application {
....
}

RequestMapping GET and POST methods handling in Spring REST - Stack Ov...

spring rest spring-boot
Rectangle 27 38

I used the solution also described in this post from Netgloo's blog.

The idea is to create a generic repository class like the following:

then I can write the three repositories in this way:

Moreover, to obtain a read-only repository for ARepository I can define the ABaseRepository as read-only:

@NoRepositoryBean
public interface ABaseRepository<T> 
extends Repository<T, Long> {
  T findOne(Long id);
  Iterable<T> findAll();
  Iterable<T> findAll(Sort sort);
  Page<T> findAll(Pageable pageable);
}

and from BRepository extend also the Spring Data JPA's CrudRepository to achieve a read/write repository:

@Transactional
public interface BRepository 
extends ABaseRepository<B>, CrudRepository<B, Long> 
{ /* ... */ }

In this example can you use use repository B to set attributes belonging to Class A that is extended by Class B? I wanted to use a system like this to update B via a spring-data-rest controller.

@ALM I'm pretty sure you can do it. Did you tried it?

Yes I am about to try right now. I am actually debating how I want to set it up but I think I will create a very simple test first then run that to see. I read the other article and after that I believe it should inherit what is for repository A and then be able to be used by B. A would also be setup as read-only

excellent , solves the problem

java - Best way of handling entities inheritance in Spring Data JPA - ...

java spring spring-data spring-boot spring-data-jpa
Rectangle 27 30

As described in the documentation on error handling, you can provide your own bean that implements ErrorAttributes to take control of the content.

DefaultErrorAttributes
@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            // Customize the default entries in errorAttributes to suit your needs
            return errorAttributes;
        }

   };
}

Thanks for the reply! I have tried to use the ErrorAttributes but i seem to be unable to get this unit tested. See [stackoverflow.com/questions/29120948/ Any idea how this can be done?

Modify default JSON error response from Spring Boot Rest Controller - ...

json spring rest spring-boot
Rectangle 27 1

Usually when Spring MVC fails to read the http messages (e.g. request body), it will throw an instance of HttpMessageNotReadableException exception. So, if spring could not bind to your model, it should throw that exception. Also, if you do NOT define a BindingResult after each to-be-validated model in your method parameters, in case of a validation error, spring will throw a MethodArgumentNotValidException exception. With all this, you can create ControllerAdvice that catches these two exceptions and handles them in your desirable way.

@ControllerAdvice(annotations = {RestController.class})
public class UncaughtExceptionsControllerAdvice {
    @ExceptionHandler({MethodArgumentNotValidException.class, HttpMessageNotReadableException.class})
    public ResponseEntity handleBindingErrors(Exception ex) {
        // do whatever you want with the exceptions
    }
}

Disadvantage here is that you don't get the BindingResult when a binding error occurs. I.e. you can do ex.getBindingResult() on MethodArgumentNotValidException exception, but not on a HttpMessageNotReadableException exception.

The latter seems reasonable, because when binding is failing, we could not have a binding result. There is no binding.

In my view binding errors like putting a String in a int field or a wrong Enum value should be treated as validation errors. Using DataBinder standalone also binding field errors are in the BindingResult so the service can return a more detailed error response.

I agree. I'm having an issue trying to properly show a GOOD error message when someone provides an invalid value for an enum. Jackson wraps it and I end up with a very generic HttpMessageNotReadableException. The message in there includes java package and class information in it. Not acceptable. I want to know the field that failed and why, but I can't find any way to do that. I've tried turning off the WRAP_EXCEPTIONS setting but that doesn't seem to have any effect

Spring Boot binding and validation error handling in REST controller -...

spring validation spring-mvc spring-boot spring-restcontroller
Rectangle 27 29

As described in the documentation on error handling, you can provide your own bean that implements ErrorAttributes to take control of the content.

DefaultErrorAttributes
@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            // Customize the default entries in errorAttributes to suit your needs
            return errorAttributes;
        }

   };
}

Thanks for the reply! I have tried to use the ErrorAttributes but i seem to be unable to get this unit tested. See [stackoverflow.com/questions/29120948/ Any idea how this can be done?

Modify default JSON error response from Spring Boot Rest Controller - ...

json spring rest spring-boot
Rectangle 27 26

Step 1 - Create a standalone class, storing MessageConverters

This is a very interesting problem that Spring Security and Spring Web framework is not quite consistent in the way they handle the response. I believe it has to natively support error message handling with MessageConverter in a handy way.

I tried to find an elegant way to inject MessageConverter into Spring Security so that they could catch the exception and return them in a right format according to content negotiation. Still, my solution below is not elegant but at least make use of Spring code.

I assume you know how to include Jackson and JAXB library, otherwise there is no point to proceed. There are 3 Steps in total.

This class plays no magic. It simply stores the message converters and a processor RequestResponseBodyMethodProcessor. The magic is inside that processor which will do all the job including content negotiation and converting the response body accordingly.

public class MessageProcessor { // Any name you like
    // List of HttpMessageConverter
    private List<HttpMessageConverter<?>> messageConverters;
    // under org.springframework.web.servlet.mvc.method.annotation
    private RequestResponseBodyMethodProcessor processor;

    /**
     * Below class name are copied from the framework.
     * (And yes, they are hard-coded, too)
     */
    private static final boolean jaxb2Present =
        ClassUtils.isPresent("javax.xml.bind.Binder", MessageProcessor.class.getClassLoader());

    private static final boolean jackson2Present =
        ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", MessageProcessor.class.getClassLoader()) &&
        ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", MessageProcessor.class.getClassLoader());

    private static final boolean gsonPresent =
        ClassUtils.isPresent("com.google.gson.Gson", MessageProcessor.class.getClassLoader());

    public MessageProcessor() {
        this.messageConverters = new ArrayList<HttpMessageConverter<?>>();

        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter());
        this.messageConverters.add(new SourceHttpMessageConverter<Source>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());

        if (jaxb2Present) {
            this.messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
        }
        if (jackson2Present) {
            this.messageConverters.add(new MappingJackson2HttpMessageConverter());
        }
        else if (gsonPresent) {
            this.messageConverters.add(new GsonHttpMessageConverter());
        }

        processor = new RequestResponseBodyMethodProcessor(this.messageConverters);
    }

    /**
     * This method will convert the response body to the desire format.
     */
    public void handle(Object returnValue, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
        ServletWebRequest nativeRequest = new ServletWebRequest(request, response);
        processor.handleReturnValue(returnValue, null, new ModelAndViewContainer(), nativeRequest);
    }

    /**
     * @return list of message converters
     */
    public List<HttpMessageConverter<?>> getMessageConverters() {
        return messageConverters;
    }
}

As in many tutorials, this class is essential to implement custom error handling.

public class CustomEntryPoint implements AuthenticationEntryPoint {
    // The class from Step 1
    private MessageProcessor processor;

    public CustomEntryPoint() {
        // It is up to you to decide when to instantiate
        processor = new MessageProcessor();
    }

    @Override
    public void commence(HttpServletRequest request,
        HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {

        // This object is just like the model class, 
        // the processor will convert it to appropriate format in response body
        CustomExceptionObject returnValue = new CustomExceptionObject();
        try {
            processor.handle(returnValue, request, response);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}

As mentioned, I do it with Java Config. I just show the relevant configuration here, there should be other configuration such as session stateless, etc.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint(new CustomEntryPoint());
    }
}

Try with some authentication fail cases, remember the request header should include Accept : XXX and you should get the exception in JSON, XML or some other formats.

Handle spring security authentication exceptions with @ExceptionHandle...

spring spring-mvc spring-security
Rectangle 27 2

There's a similar situation convered in the excellent "Exception Handling in Spring MVC" post on the Spring blog, in the section entitled Global Exception Handling. Their scenario involves checking for ResponseStatus annotations registered on the exception class, and if present, rethrowing the exception to let the framework handle them. You might be able to use this general tactic - try to determine if there is a might be a more appropriate handler out there and rethrowing.

spring mvc - Setting Precedence of Multiple @ControllerAdvice @Excepti...

spring-mvc exception-handling
Rectangle 27 2

@RequestParam is most suited for situations when parameters are generated by your application rather than entered by the user.

If you want to provide feedback to the user it would be better to use conventional form handling approach with @ModelAttribute and BindingResult. This way you can perform arbitrary validation and also provide meaningful error messages for type mismatch errors.

What do you mean by saying:"for situations when parameters are generated by your application"? How can my app generate requestParam? You mean by forwarding requests?

@ApollonDigital: I mean situations when user follows a link (with parameters) generated by your application rather than enters values in a form.

In any case you can't be sure for any request that can come to server. Anyone can create and send a custom request. I don't think that implementations should vary. Anyway ... Im relatively new to Spring, so any additional details would be appriciated. I search a little and found something like JSR-303 ... I don't know what is it and if has any relation with javax.validation package ...

Spring: Handling errors when type mismatch in @RequestParam - Stack Ov...

spring spring-mvc error-handling
Rectangle 27 16

It looks like you have the most of the answers in your question itself :)

Have the controller like this

Declare the exception class in NotFoundException.java,

@ResponseStatus(value=HttpStatus.NOT_FOUND, reason="Id Not Found")
public class NotFoundException extends Exception {

    public NotFoundException(String msg) {
        super(msg);
    }
}

This exception class need not be every controller class. Declare it as public class and import it in every required controller.

This is one way of doing it. If you like the non-spring style, declare HttpServletResponse in every controller arguments and do

@RequestMapping("/test") 
public String verifyAuth(HttpServletRequest request, HttpServletResponse response) {
   ...
   try {
    response.sendError(..)
   catch(..) {}
}

Or you can use views to show error message,

@RequestMapping("/test") 
public String verifyAuth(HttpServletRequest request, Map<String, Object> map){
    String id = request.getParameter("id");

    if (id == null)  {
        map.put("status", HttpStatus.NOTFOUND);
        map.put("reason", "Id Not Found");

        return "error"
     }
      return "success";
}

Make sure your viewResolver is configured correctly and in the error.jsp to get the error string, you could say.

<body>
${status} ${reason}
</body>

Define error.jsp with nice css for all kind of errors you would expect. These are not the only ways. With spring you have freedom to do anything. I have seen few ppl rendering json object for error message.

To answer your another question of if the error happens in the service called by the controller is depend on your scenario. For example you are trying to read the user store, if the user store not available error happens, I would handle there itself to read from another replica user store if one available and If I found user does not exist I would leave the exception to the controller to throw.

Thanks - I was overthinking the problem. Sometimes that happens when I work with Spring...I get too many ideas in my head and can't sort them out.

exception handling - Returning an error and message from a Spring cont...

spring-mvc exception-handling
Rectangle 27 8

Spring for DI and Event handling. DDD-ish approach of model objects. Longer running jobs are offloaded with SQS in worker-modules.

Repository model with Spring JDBC-templates to store Entities. Redis (JEDIS) for Leaderboards, using Ordered Lists. Memcache for Token Store.

This is something similar to what we follow in our projects too! In addition JBPM for business workflow. Why no spring I wonder?

I should do an update with our current arch: Currently we use Spring DI and JDBC-templates for the data-access layer.

Describe the architecture you use for Java web applications? - Stack O...

java architecture java-ee
Rectangle 27 8

Spring for DI and Event handling. DDD-ish approach of model objects. Longer running jobs are offloaded with SQS in worker-modules.

Repository model with Spring JDBC-templates to store Entities. Redis (JEDIS) for Leaderboards, using Ordered Lists. Memcache for Token Store.

This is something similar to what we follow in our projects too! In addition JBPM for business workflow. Why no spring I wonder?

I should do an update with our current arch: Currently we use Spring DI and JDBC-templates for the data-access layer.

Describe the architecture you use for Java web applications? - Stack O...

java architecture java-ee
Rectangle 27 12

This is a problem with the default way that Spring Security sends redirects back to the client. The default method of sending a redirect to the client is the HTML approach of sending a 302 Temporarily Moved response, however this does not work for AJAX clients. The AJAX client will interpret this as a redirect to a new location to post/get its data and not as a page redirect. The correct way to get the AJAX client to redirect the browser to a new page in the same way as a normal HTML request is:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<partial-response>
  <redirect url="http://your.url.here/"></redirect>
</partial-response>

To override the default invalid session strategy used by Spring Security, you need to create a SessionManagementFilter bean in your Spring config, and pass it a class that implements InvalidSessionStrategy and sends the correct redirect response when a request is received either via HTML or AJAX:

<bean id="sessionManagementFilter" class="org.springframework.security.web.session.SessionManagementFilter">
  <constructor-arg name="securityContextRepository" ref="httpSessionSecurityContextRepository" />
  <property name="invalidSessionStrategy">
    <bean class="yourpackage.JsfRedirectStrategy">
       <constructor-arg name="invalidSessionUrl" value="/your_session_expired_page.xhtml" />
    </bean>
  </property>
</bean>
<bean id="httpSessionSecurityContextRepository" class="org.springframework.security.web.context.HttpSessionSecurityContextRepository"/>
<security:http use-expressions="true">
    <security:custom-filter ref="sessionManagementFilter" before="SESSION_MANAGEMENT_FILTER" />
    ...
</security:http>

The custom session management filter will now be created when your application starts, and the invalid session strategy class provided will execute whenever an expired session is found.

A good example of how to implement the invalid session strategy can be found here: https://gist.github.com/banterCZ/5160269

One note from my (successful) implementation of your answer here: Don't clear your cookies then trigger the ajax request as a way of testing this method! The new, session-less request isn't considered "invalid" the same way an expired session is!

jsf 2 - Redirect handling PrimeFaces Ajax requests on session timeout ...

ajax jsf-2 primefaces spring-security session-timeout