1

Environment :

Spring MVC 3

Angular JS

Tomcat 6

Issue :

We are migrating a legacy application from struts2 to spring MVC REST with angular JS as UI. This is a typical SPA.

The typical application flow is : Angular JS + Spring REST controller + Servicelayer

The business logic in struts2 actions is moved to service classes.

My question is - What is the correct way to make HttpServetRequest object available to Service classes in Spring ?

Two options available are :

1)Pass HttpServletRequest to Spring MVC controller method. Pass the same HttpServetRequest to Spring service layer. But this will result in HttpServletRequest being part of Service interface like -

public ProductDto getProductDetails(HttpServletRequest req,int productId)

Is this a correct way ? Can HttpServletRequest be part of Service interface ?

2)Use Spring provided API :

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

Please guide on this ?

2 Answers 2

4

In addition to those mentioned options, you can introduce a class or another abstraction into your service layer, then populate it with the required parts of the HttpServletRequest and use that abstraction inside the Service Layer.

For example (Borrowed from Spring Data), Suppose you want to access to page, size and sort and user related query strings from the HttpServletRequest. Instead of passing the request to the service layer methods, you can also encapsulate those parameters into an abstraction, say, Pageable or UserFilterCriteria:

public interface Pageable {
    int page();
    int size();
    List<Sort> sorts();
}

Then instead of passing the HttpServletRequest to the service layer:

public interface UsersService {
    List<User> filterUsers(HttpServletRequest request);
}

You can pass those new abstractions:

public interface UsersService {
    List<User> filterUsers(UserFilterCriteria criteria, Pageable pageable);
}

This way you can easily define abstractions in the same level of abstraction as your service layer.

Sign up to request clarification or add additional context in comments.

1 Comment

If we want finer grain access to request object like getting/setting request/session attributes , then above approach would be dufficult
1

You should rather not make HttpServletRequest/-Response be part of your service-layer, as HttpServletRequest/-Response are classes specific to your user interface/view technology. Introducing them to your service layer will make your service layer depend on the technology used for the user interface, thus making it harder to change the UI/View technology later.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.