Sparkjava: Do you need routes mainly?

I am new to sparkjava and love it in general. However, should new routes / endpoints be defined in the main method? For any significant web application, this will lead to a very long main method, or I need to have several main methods (and therefore share server resources between multiple instances).

It seems that these two pages of spark system documentation define the routes in the main method: http://sparkjava.com/documentation.html#routes and here http://sparkjava.com/documentation.html#getting-started .

Is there any other way to do this that I don't see? A quick google search didn't show me a better way ...

==========

Here is the complete decision I made based on Andrei’s answer. In my opinion, adding endpoints outside the main method should be part of the sparkjava documentation page:

The main method:

public static void main(String[] args) { //Do I need to do something more with the Resource instance so that sparkjava notices it and/or reads the routes? Resource resource= new Resource(new Service()); } 

My resource:

 import static spark.Spark.*; class Resource{ private Service service; Resource(Service service){ this.service = service; setupEndpoints(); } private void setupEndpoints() { get("/user/:id", "application/json",(request, response) -> service.find(request.params(":id")), new JsonTransformer()); get("/users", "application/json", (request, response) -> service.findAll(), new JsonTransformer()); } } 

My service:

 public class Service { public Object find(String id) { return null; } public Object findAll() { return null; } } 

My JsonTransformer:

 import spark.ResponseTransformer; public class JsonTransformer implements ResponseTransformer { @Override public String render(Object model) throws Exception { return null; } } 
+5
source share
4 answers

You can set routes wherever you want. You just need a method for setting up a call in the main thread. eg.

  public static void main(String[] args){ Resource resource= new Resource(new Service()); } class Resource{ private Service service; Resource(Service service){ this.service = service; setupEndpoints(); } private void setupEndpoints() { get("/user/:id", "application/json",(request, response) -> service.find(request.params(":id")), new JsonTransformer()); get("/users", "application/json", (request, response) -> service.findAll(), new JsonTransformer()); } } 
+7
source

Here is a design idea that you can use when setting up multiple endpoints:

First create the builder interface:

 public interface EndpointBuilder { void configure(Service spark, String basePath); } 

Now, let's say you have one of many other leisure endpoint resources to configure:

 public class CustomerEndpoint implements EndpointBuilder { private final CustomerService customerService; public CustomerEndpoint(CustomerService service) { this.customerService = service; } @Override public void configure(Service spark, String basePath) { spark.get(basePath + "/customer", (req, res) -> { return "hello"; }); } } 

Finally, create a RestContext class that will contain the spark instance and allow you to configure any routes you want:

 public class RestContext { private static final Logger logger = LoggerFactory.getLogger(RestContext.class); private final Service spark; private final String basePath; public RestContext(int port, String basePath) { this.basePath = basePath; spark = Service.ignite().port(port); // import spark.Service; } public void addEndpoint(EndpointBuilder endpoint) { endpoint.configure(spark, basePath); logger.info("REST endpoints registered for {}.", endpoint.getClass().getSimpleName()); } // Then you can even have some fun: public void enableCors() { spark.before((request, response) -> { response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.header("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization"); }); logger.info("CORS support enabled."); } } 

You should be able to use this context class in your main method (and possibly in your test classes):

 public static void main(String... args) { RestContext context = new RestContext(8080, "/api"); context.addEndpoint(new CustomerEndpoint(new CustomerService())); context.addEndpoint(new AnotherEndpoint()); // you can add or remove as many as you want. context.enableCors(); } 

Ob .: Starting with version 2.5 , spark java supports multiple instances through the Service.ignite () api.

+7
source

You can also integrate Spring into your Spark application. This is how I set up my routes.

 @Configuration public class RoutesConfiguration { RoutesConfiguration() { get("/hello", (req, res) -> "Hello World!"); } } 

This allows me to avoid the installation invocation step in the main SparkApp method.

+3
source

Well, I think spark-java is for people who don't need tons of extra tweaks.

So, I just add and add an extra method to the controllers named DeclareRoutes, where I put the declarations.

For an example application:

 public class LoginController { public static void declareRoutes(){ get(Path.Web.LOGIN, LoginController.serveLoginPage); post(Path.Web.LOGIN, LoginController.handleLoginPost); post(Path.Web.LOGOUT, LoginController.handleLogoutPost); } public static Route serveLoginPage = (Request request, Response response) -> { Map<String, Object> model = new HashMap<>(); model.put("loggedOut", removeSessionAttrLoggedOut(request)); model.put("loginRedirect", removeSessionAttrLoginRedirect(request)); return ViewUtil.render(request, model, Path.Template.LOGIN); }; 

So, in my application, I initialize all routes as follows:

  // Routes Class[] controllers = { IndexController.class, LoginController.class, SandboxController.class, ServicesController.class }; for (Class controller: controllers) { Method m = controller.getMethod("declareRoutes"); m.invoke(m); } // Catch all declareCatchAllRoute(); 

DeclareCatchAllRoute () is simple:

 private void declareCatchAllRoute() { get("*", ViewUtil.notFound); } 

It works well enough for my needs, it does not require any new abstraction.

NTN

0
source

Source: https://habr.com/ru/post/1241353/


All Articles