In many of the tutorial or example I saw. Most people put down the html code right in the java file. I was wondering if there is another way or better practice instead of writing something like this.
#Path("/someExample")
public class SomeExample{
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello World RESTful Jersey"
+ "</title>" + "<body><h1>" + "Hello World RESTful Jersey"
+ "</body></h1>" + "</html> ";
}
I am new to the webservice and I was wondering instead of above can I do something like return from a html file itself?
If you're looking to return dynamic HTML, you're probably better off using an MVC framework (like Spring MVC), rather than a REST framework. If you want to stick with using the same REST Framework you are using, if you are using Jersey, Jersey has MVC Support
The general idea of how MVC frameworks work, is by using templates and controllers to populate models used in the templates. In pseudo code, you might have something like
template (index.html)
<html>
<body>
<h1>Hello {{ name }}</h1>
</body>
<html>
controller method
public Viewable index() {
Map<String, String> model = new HashMap<>()
model.put("name", "Peeskillet");
return new Viewable("index", model);
}
This is example code that you might use with Jersey (and its MVC support), but using Spring MVC, the concept would still apply, just the classes used would be different.
The basic concept is that you fill the model inside the controller, and tell the framework which template should be used. The framework will take the template, and inject the variables wherever you request them, and then return the converted view to the client.
You should decide on which framework you want to use and read the documentation linked to above for more details. Spring MVC was made specifically as an MVC framework, where Jersey is a REST framework that added MVC support as an afterthought. So you will get more features with Spring MVC. But for basic MVC functionality, using Jersey would work.
As an aside, if you are already coming from an MVC framework (like Spring MVC) background, then you need to shift your thinking a little bit. With REST API (or web services as you call it), normally you won't be sending HTML page responses. Normally it will be a lighter weight data format like JSON. If you are creating a web application that interacts with the REST API, you would normally using AJAX (Javascript) to request the JSON, and it use the JSON data to update the DOM. That's generally how it works.
Related
I am a Java developer, I want to write my own blogging application (that bloggers use to write their blogs with) i know it may sound crazy but i want it just for learning purpose, i am using JSF EJB Hibernate and RESTeasy tools,i started it i have created the database and the view.
From the information that i collected it is recommended to store the blog content in database(in html text), i find that i can use for that Javascript editor like CKEditor after the blogger write his blog in CKEditor i will concatenate it with a prepared header and footer after that i will store it in the database, and i found out that i can get blog post using RESTeasy API.
As an example(sorry):
after the blog is stored in the database
i want to present it to visitors like this:
link containing a path and the id of the article
<div>
Read More...
</div>
when the visitor press the link a REST Controller handle the request, fetch the article from the database using the provided id in the link and return an html page (without creating it statically).
The RESTeasy part perhaps something like this:
#Stateless
#Path("/article/")
public class ArticleResource {
#EJB
private ArticleService articleService;
#GET
#Path("/{id}")
#Produces(value = MediaType.TEXT_HTML)
public Response getArticleById(#PathParam("id") Long id){
//get article post from the database
Article article = articleService.findById(id);
//something here i didn't know
//return article post as an html page
}
}
Please if there is anything here that you see is wrong feel free to inform me, i am just learning here. And if there is an even better approach that you see is good, i really appreciate it.
I know perhaps using Spring it can be better but i want just to learn here how to do it.
I want to know how to get an html page stored in database using JAXRS,
the html page has no file in the application it is just stored in the database something like this:
"<html><head>...</head> <body>...content of the blog here</body> </html>"
Thank you in advance.
Use Jersey's MVC Templates
You can use freemarker as template engine to produce HTML with context
Your template will be similar to:
<html><head>...</head> <body> ${article.toString()}</body> </html>
You can follow example:
In this example, the FruitResource JAX-RS resource class is the controller. The Viewable instance encapsulates the referenced data model which is a simple String.
Furthermore, we also include a named reference to the associated view template – index.ftl.
In this example, we’ve used the #Template annotation. This avoids wrapping our model directly in a template reference via Viewable and makes our resource method more readable.
There is this typical traditional JAVA Spring + JSP application that I am working on. It's a full fledged working application with more than 50 pages. The client feels its slower and wants to make it faster by using ReactJs for new pages. From performance point I understand his concerns. Now I am not a JAVA expert and I am new to ReactJS but i have worked on AngularJs(SPA) applications extensively before.
Right now the way the application works is when we call a url say http://example.com/mycontroller/myaction.do, the app maps the url to certain controller and action in a JAVA controller.
#RequestMapping(value = "/mycontroller/myaction.do", method = RequestMethod.GET)
public ModelAndView myfunction(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView mav = new ModelAndView("myJSPPage");
mav.addObject("pageDetails", myPageDetails);
return mav;
}
Once the action gets executed the html page is rendered in the browser along with server data and jQuery takes care of the UI part.
Now speaking of ReactJs,
React is just a UI, Lots of people use React as the V in MVC.
Which comes to my questions:
Can i use React in Java JSP Pages and access Java variables in React ?
If not what are other options/ways to use React with these kind of applications.
If its not possible to use React in current application, do i need to write the whole application from scratch using React. What are the challenges i might face?
Yes. Its possible to pass the Java objects and lists to your javascript application using Nashorn which comes bundled with java 8.
Second option is to do the rendering on client and fetch the required data using ajax/websockets.
I believe sticking to using JSP’s along with React won’t benefit you much in terms of performance. Because the main benefit of using SPA’s is that you don’t need to re-render the whole web page when some data changes or when actions are dispatched.
If performance is your main concern then I encourage you to implement a React application (the V) and make Spring your controller (the C) and make them communicate JSON objects (the M (data)).
I'm trying to redirect without parameters being added to my url. I mean after a redirect, my url looks like this: .../success/?param1=xxx¶m2=xxx.
This issue is exactly the same as this Spring MVC Controller: Redirect without parameters being added to my url
The response https://stackoverflow.com/a/16841663/384984 is what I'm looking (ignoreDefaultModelOnRedirect). The problem is that I'm using Spring 3.0. How can I solve it with this Spring version?
You can simply clear the Model map in your Controller method before redirect .
model.asMap().clear();
return "redirect:" + yourURL;
Don't expose the model attributes at all.
RedirectView view = new RedirectView(yourURL, true);
view.setExposeModelAttributes(false);
return new ModelAndView(view);
Hope this link helps you in finding a better solution, specially point (4) HandlerInterceptor for common reference data within the entire web application
What AJAX libraries work well with Spring MVC?
I'm new to developing with Spring and Spring MVC. From the documentation at http://www.springsource.org I'm not yet understanding what AJAX framework Spring MVC has built-in or what third party APIs and tooling might be suggested as working well with developing a Spring MVC application.
All recommendations are appreciated.
I did search through previous SO discussions on this subject, but I didn't get any clear direction.
Spring is super easy to use with Ajax. If Jackson is on the classpath Spring can use it for returning JSON to the caller. Something like this:
#RequestMapping( "/my/path" )
public #ResponseBody MyObject doSomething( #RequestParam Long myVal ) {
MyObject result = new MyObject( myVal );
// do something interesting
return result;
}
Then you can use jQuery (or your other favorite javascript library) to make a request to http://myserver/my/path and handle the resulting JSON object.
Google's GSON is also easy to use. As in:
#RequestMapping( "/my/path" )
public ResponseEntity<String> MyObject doSomething( #RequestParam Long myVal ) {
MyObject result = new MyObject( myVal );
// do something interesting
HttpHeaders headers = new HttpHeaders();
headers.set( "Content-Type", "application/json" );
String json = gson.toJson( result );
return new ResponseEntity<String>( json, headers, HttpStatus.CREATED );
}
Please go through the following link. It clearly explains how it needs to be done.
http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/
Here is another approach to let Spring MVC to work with ZK UI components - Rich Web Application with Spring MVC CRUD Demo
In that article, it used Spring MVC controller to communicate with ZK UI components. (all in Java code)
Spring JS has support of Dojo JavaScript framework.
Spring Js
Spring doesn't deal with Javascript frameworks, per se. I don't know if Springsource does any advocacy for any particular Javascript framework or whether they are agnostic. Ajax is really just a technique enabled by browser technology in combination with the Javascript language and what matters is the ability to pass some kind of serialized data between client and server. It isn't that difficult to cook up your own basic AJAX framework and you could even design your own data encoding and not use JSON or XML. It is wise to adopt an existing framework and standards because you don't want to maintain a lot of ancillary code or worry about it, and instead focus on the problem you are trying to solve. So that is why there are many Javascript frameworks out there that can do asynchronous requests and some have some really nice features and capabilities that make your life easier, for example jQuery provides excellent DOM manipulation and browser-neutral functionality. I think that using Spring MVC in conjunction with the Jackson JSON library on the server side, and jQuery on the client side, is the basis for a very decent end-to-end solution. I have had a lot of success with jQuery and jQuery-UI, but other Javascript frameworks can work just as well. For complex applications, you basically end up needing what amounts to a second MVC on the client side because you need that breakdown between UI widgets and the data that has to move between client and server.
I am newbie in spring. using spring 3.0 mvc.
I am creating a spring application, I have a login form,Any one please suggest what controller i should use, as when I am using SimpleFormController its saying deprecated,
Any specific controller I can use.
First of all as everybody already told you use annotation-base controller
secondly for creating a form you can use spring form taglib
thirdly you can create method like this
public String updateHouse(House house, #RequestParam("file") MultipartFile file, Model model) {
this is from my sample application. House object is auto generated from form. In my form I have fields of my House object and it is send to the method as object. #RequestParam allows me to fetch the file witch is uploaded via form (POST), Model is my view model.
As you can see it is easy :)
Why don't you try annotation-based controllers? They are easy and fun to use.
You can try annotation based controller. Please refer below link:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html