How to start GWT from web service REST - java

Is it possible to run GWT application from web service REST?
#Path("/main")
public class RestService {
#GET
#Path("{name}")
public Response getUserByName(#PathParam("name") String name){
// return Response.status(200).entity("My name is " + name).build();
}
}
What is important for me, the URL which calls REST, must not be changed after GWT will run. So when the browser go to localhost:8080/application/main/adam, the REST runs and calls the GWT application which shows message box with My name is adam. After that, I can sill see the same URL in the browser.
Maybe I should explain the reason of my requirements.
I want to create application where the end-user will use only the URLs, example:
localhost:8080/application/somecommand/somedata
localhost:8080/application/anothercommand/anotherdata
No windows, no forms, only URLs.

Yes, it is possible. Just serve the HTML page with your GWT app.

If you can deal with Urls Like this:
localhost:8080/application#somecommand/somedata
localhost:8080/application#anothercommand/anotherdata
It is just the GWT History-API

Related

How seperate Front-End & Back-End machine in spring-boot?

I want to separate Back-End and Front-End(HTML Pages) machines.The back-end will be developed by Spring-Boot. How can return View in controllers to Front-End machine instead of "resources/template" in Back-End(Spring-Boot--->Apache Tomacat) machine?
For example :
#Controller
public class GreetingController {
#RequestMapping("/greeting")
public String greeting(#RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";
}
}
I want to put "greeting" view in another server (Front-End).
You didn't disclose which templating technology are you using (e.g. JSP, Thymeleaf, ...), but either way Spring needs to inject your variables from model into HTML templates.
AFAIK, there is no way to host views in one JVM and controller filling it on other JVM. You could extract your views into separate JAR, but it would need to be hosted on same Servlet container at the end of the day.
If you want true separation of client and server, investigate templating on client (Single Page Applications) and using just AJAX for fetch the data from REST back-end.
You can start two servers, one for backend and the other for frontend. The two would be communicating via REST call. The Backend server will give the data to frontend server, which will collect it and send it to html templates in the frontend server. The template engine integration would save you time in getting things done. Springboot has good integration with Thymeleaf so I would recommend you to use the same.
It's actually quite simple after you have the prototype ready. I have made the prototype for frontend and backend separated springboot applications. The template engine used here is thymeleaf, database is mysql and language is java. You can remove the unneeded part and start with your work!
You may need to implement a/the WebMvcConfigurerAdapter interface.
This is a code sample:
#Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Value("${spring.thymeleaf.prefix}")
private String thymeleafTemplatePath;
#Value("${node_modules.path}")
private String nodeModulesPath;
public void addResourceHandlers(ResourceHandlerRegistry registry){
if (thymeleafTemplatePath != null && !thymeleafTemplatePath.isEmpty()){
if (!registry.hasMappingForPattern("/**")) {
registry.addResourceHandler("/**")
.addResourceLocations(thymeleafTemplatePath);
}
}
if (nodeModulesPath != null && !nodeModulesPath.isEmpty()){
if (!registry.hasMappingForPattern("/node_modules/**")) {
registry.addResourceHandler("/node_modules/**")
.addResourceLocations(nodeModulesPath);
}
}
}
}
The following code is for a configuration variable in a property file.
This example has a Windows file path pattern. You may need to change the pattern for your environment.
spring.thymeleaf.prefix=file:///C:/Users/young.k.jun/workspaces/separated-front-end/front-end/src/
node_modules.path=file:///C:/Users/young.k.jun/workspaces/separated-front-end/front-end/node_modules/
I made a sample project to separate front-end and back-end workspace so as not to conflict with their work directories.
Please refer to this link. You can find a GitHub link on that page.
It's possible to do that with REST-Web-Service but the goal from Thymeleaf isn't to work alone as frontend App. If you absolutly need to have a separated frontend App you should user any moderne js framework such as Angular/React/Vue and use spring boot for rest api.

Jersey: How to redirect/forward WITHOUT URL changing in address bar

I am using Jerysey's implementation of JAX-RS to write a REST API. My POJO that handles the get requests eventually forwards it to a JSP. Everything is working fine, the problem is that the forwarding causes the URL in the browser's address bar to change to the URL that the request was forwarded to. How do I do a redirect WITHOUT this URL changing in the address bar? Current, I have tried 4 different ways:
return Response.seeOther(uri).build(),
return Response.temporaryRedirect(uri),
//thrown exception:
throw new WebApplicationException(response),
return Response.status(303).location(uri).build();
It doesn't sound like a Jersey issue per se. Jersey is doing its part to receive the request, do some processing, and return the response you are expecting.
It sounds more like a servlet container issue. Why don't you want the url to change in the browser?
Restful services can (and should) be built with no concern about templates/JSPs/consumers. Take a look at a library like RestAssured, write some tests for your work, and you will see that it is acting as expected.
Instead of rendering out to a JSP, consider using a rest client to make straight http requests against your service.
If you want the url to remain unchanged, consider making the http call using an AJAX library (JQuery or other Javascript-based solution).
I hope that helps!
A RESTful resource is identified by a URL. So if you redirect to another resource with another URL the URL in the address bar should change. That's good because you can e.g. bookmark this URL or send it per eMail.
The question here is are you really redirecting to another resource or do you only want to return a different representation (HTML instead of e.g. JSON). If the latter you should not redirect. Let your resource-class directly return text/html by using Jerseys Viewables.
You could make the entire website inside an iFrame and load the new site into that frame. It will maintain the page URL and load your content.
http://www.w3schools.com/tags/tag_iframe.asp

Mapping a RESTful URL to a static HTML page, in a Java web app

I have a Java web app that runs in JBoss. I'm adding a new web page for applying for a job, using AngularJS, and I'd like it respond to this (RESTful) URL: /job/<job id>/apply
Since I'm new to Angular, I'm trying to figure out how to route the user's request of a URL like:
GET /job/1/apply (where "1" is the job id)
to a static HTML page in my web app, like src/main/webapp/job/apply.html. My plan is to have an ng-app and ng-controller specified in the apply.html template, which will call back to the server to fetch JSON to render in the view.
So how do I configure routing in my Java-based web app, so that requesting /job/1/apply yields /job/apply.html, and my controller JS code that's loaded by apply.html has easy access to the URL parameter "1"?
I've come up with several potential ways of accomplishing this, but none of them seem very simple or straightforward:
Use Spring MVC, write an #Controller that listens to the RESTful URL, and forwards the request to apply.html. (I'm not even using Spring MVC in this web app... yet.)
Use Spring MVC and the <mvc:resources> or <mvc:view-controller> element, to map the requested URL to the HTML page.
Use a web filter to rewrite the incoming URL to /job/apply.html.
Give up on using a RESTful URL, make the job ID a query param instead, and rename my apply.html to just index.html (so it gets picked up automatically). E.g. the user requests /job/apply?jobId=1, which maps to webapp/job/apply/index.html.
The thing I'm most uncertain about is whether the job ID in the request URL will be available to my angular controller code, in order to fetch data from the backend about that job.
Redirect every request server-side to index.html when not requesting a file and use ng-route (http://docs.angularjs.org/api/ngRoute.$route) to load the correct template with something like
app.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/job/:jobid/apply', {
templateUrl: '/job/apply.html'
}).
otherwise({
redirectTo: '/'
});
}
]);
If you can make use of the "html5 mode" of ngLocation (http://docs.angularjs.org/guide/dev_guide.services.$location) that would be even cleaner for the end user.

How do I support localization with Jersey?

I am designing a REST API that I would like to be localizable in the future.
Therefore I am defining the URLs to be of the form
/en/<resource_url>
With the intention of being able to support
/fr/<resource_url>
In the future if need be.
However I only want to define each resource url service once. Therefore I figure I need to get the URL parsed and rewritten without the language piece of the URL before it is matched to services. Finally that language should be made available to the services somehow for them to localize if necessary.
How can I achieve this?
I am using Jersey 1.17 inside Jetty container embedded in a larger server process.
You can make the /en/ or the /fr/ part a variable. Then set your locale to the value of the variable. Here's an example:
#Path("/{locale}/username")
public class UserResource {
#GET
#Produces("text/xml")
public String getUser(#PathParam("locale") String locale) {
...
}
}
But that may not be the best way to go about it. After answering, I found this other SO question that is a better way to solve the problem: Getting the client locale in a jersey request With this way, you don't need to add this to the URL. Just make the client set a header.

How to get the POST/GET params in a java WebMethod?

I have created a java web service with netbeans 7.1 (glassfish3.1).
It is supposed to be visited via clicking a URL (like: http://localhost:8080/ImageService/GetImage?visitDate='2012-01-01') to generate an image for web users. And there are some parameters in the URL that I need to get to use inside the WebMethod.
#WebMethod(operationName = "GetImage")
public void GetImage() {
// Date visitDate = GET["visitDate"];
...
}
Or, how can I make the java web service invoked via http get method?
PS: In .net, this config will enable the feature - calling a web service via URL. I'm asking for a java version.
<webServices>
<protocols>
<add name="HttpPost"/>
<add name="HttpGet"/>
</protocols>
</webServices>
Is this doable? How can I get that work?
Thanks!
Finally, I have given up this, turn to use jsp to do that. But still hoping someone can tell me - if web-service way is possible or not.
Thanks!
The #WebParam annotation is defined by the javax.jws.WebParam interface. It is placed on the parameters of the methods defined in the SEI. The #WebParam annotation allows you to specify the direction of the parameter, if the parameter will be placed in the SOAP header, and other properties of the generated wsdl:part.
#WebMethod(operationName = "GetImage")
public void GetImage(#WebParam(name = "visitDate")String visitDate) {
//...
}

Categories

Resources