I know that it's bad idea to embed business logic in your servlets, it's accepted to do on application server's side. Sometimes you have a lot of parameters in your request, and all of them you need to send to classes that represents your business logic. How would be better to do it? (I thought about JavaBeans but they were designed for another purpouse.) Thanks.
You should separate your business logic into a separate class, which implements an interface, and the servlet class should simply be responsible for deserialising the input stream into some kind of request object, passing it to the business logic object, and then serialising the response. If you add a little bit of DI magic then it can become fairly simple to locate and construct the correct implementation of the business logic class to use.
Example
public interface TheBusiness {
MyBusinessResponse doProcess(MyBusinessRequest request);
}
public final class MyBusinessClass implements TheBusiness {
@Override
public MyBusinessResponse doProcess(MyBusinessRequest request) {
// all the complex logic goes here.
return response;
}
}
public class MyBusinessServlet extends HttpServlet {
private final TheBusiness theBusiness;
private final ObjectMapper objectMapper;
public MyBusinessServlet() {
theBusiness = // locate and construct implementation.
objectMapper = // Initialise Jackson deserialisation.
}
public void doGet(HttpServletRequest request, HttpServletResponse response) {
final MyBusinessRequest requestBody = objectMapper.readValue(
request.getInputStream(), MyBusinessRequest.class);
final MyBusinessResponse responseBody = theBusiness.doProcess(requestBody);
objectMapper.writeValue(response.getOutputStream(), responseBody));
}
}
The only tricky thing here is instantiating your MyBusinessClass. There are patterns for different DI frameworks which can help there. Mostly they involve using a framework-provided servlet to do all that marshalling and unmarshalling for you and you just need to code up the business logic and annotate a class appropriately. Both Spring-MVC and Jersey do that. The important thing is that the servlet class deals with all the HTTP-type interaction and with serialisation, while the logic is encapsulated elsewhere behind an interface - so each class can be well tested in isolation.