I have a question about whether or not something is possible. I have a spring mvc webapp that will have a button that links to an external website which returns an Excel document. The name of the excel document returned is rubbish and I would like to rename the document as it comes in before the user is prompted to save.
Is this possible using spring mvc. I'm on a really old version. The version compatible with Java 1.4.2.
So far I'm thinking that I'll extend org.springframework.web.servlet.mvc.AbstractController, override handleRequestInternal and then do something like this....
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
urlBuilder.setServerName(batchServerName);
urlBuilder.setPort(Integer.parseInt(batchServerPort));
urlBuilder.setContextPath(batchReportRoot);
urlBuilder.setServletPath(reportNameServletPath);
urlBuilder.setPathInfo(reportNamePathInfo);
urlBuilder.setScheme(HTTP);
String transitionUrl = urlBuilder.getUrl();
ModelAndView modelAndView = new ModelAndView(new RedirectView(transitionUrl));
return modelAndView;
But how do i take it further to rename the document as it comes in etc...
thanks
Perhaps another approach you might consider is that you have a Controller implementation that proxies the request onto the external website. Rather than interacting with the external website directly, your users interact with your Controller. This will give you the opportunity to re-name the file before it is served to your users. It also means that should things change in the future, you only need to change the implementation of your Controller.
So a proposed work flow could be:
User clicks link to your controller /downloadExcelReport
The request is handled by ExcelReportController
ExcelReportController makes an HTTP request to the external website and fetches the Excel document
Before returning the Excel report to your user, ExcelReportController sets the correct HTTP headers to ensure that the file is named according to what you need.
This way you're only providing a normal Controller implementation rather than having to override the internals of Spring.
Related
I'm new to jquery and SpringMVC. I'm using jquery to submit a request after a user clicks a href. After the server processes the request, a modal popup is displayed with the details from the server.
$.post(taskSrchURL, function(data) {
$('#popupmodal').modal('show');
});
Here is the Controller:
#RequestMapping(value = "/api/task/{id}", method =
{RequestMethod.POST})
public ModelAndView searchDetails(#PathVariable("id") String
id,
HttpServletRequest request, HttpServletResponse response)
throws SearchException, ApplicationException {
Details details = service.getDetails(id, request, response);
prepareResponse(request, response, taskDetails);
ModelAndView modelAndView = new ModelAndView("details ");
modelAndView.addObject("details ", details);
return modelAndView;
I'm expecting to have access to the "details" object when the response returns, however, I'm not sure how to access it. I'm expecting to be able to use jstl tags to reference the data as it is complex and needs to be dispalyed on several tabs.
However,
<c:out value="${details.id}"/>
does not work. I have seen a lot examples that set the 'data' from the ModalAndView to the html element of a div, but I don't want to do that.
Is there a way to do this?
Thanks in advance!
You basically have 2 choices:
Client-side rendering:
If the data you need from the server can be inserted into your page with javascript without too much hassle, you should return it as JSON from your Controller method using #ResponseBody. Convertion to JSON can be done by Jackson automatically.
You could then use an existing Javascript template engine library to render your data to html on the clients browser and insert it into the page or just insert it manually (for example with jQuery).
Server-side rendering:
If you want to render the part of the page with the data on the server-side to then send the ready-made part of your page back to the client, you need a template engine which allows you to render your templates anytime anywhere (in your controller method in this case). You could then send the html String back again as JSON using #ResponseBody and insert it into the page.
I don't think JSP/JSTL can do this (or it is very difficult/hacky). I recommend FreeMarker instead.
You could still use JSP/JSTL for your "complete" pages, and FreeMarker for the parts. FreeMarker is not too different from JSP/JSTL, so you could probably translate the part of your page without too much problems.
Besides my comment, I would highly recommend using the #ResponseBody annotation instead of using ModelAndView
Be sure to have jackson-databind on your classpath, this will cause Spring to automatically serialize your POJO into JSON, which can be directly used as Javascript objects in the ajax callback function
See a quick tutorial here:
http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program
This approach decouples the Application Server from your view, thus liberating you from having to rely on JSTL templating and you can choose a front-end workflow that is intuitive for you (checkout AngularJS).
I am learning JAVA and Spring Framework. I wanted to know that is it possible in java to create Dynamic URL in spring framework using values from url and fetching from database.
I am trying to make URL Shortner in Java and I will need to lookup for url's short code in my database and as we all know, url shortner will look like "url/ShorTCode" and my script will look for "ShorTCode" keyword in database and will redirect to associated weblink.
So I wanted to know that is it even possible in JAVA and Spring? And one more thing, if I make something like this "url/yt/VIdeoCode" or "url/fb/UserProfile"
So it will look at yt object which will redirect to youtube link only and fb object which will redirect to facebook user profile.
I want to clarify that I am still learning JAVA, JSP and Spring but I want to keep this thing in my mind while I am learning so I can focus on some particular things.
Thank you all fro helping me.
If you're asking how your controller could respond with a dynamic redirect, the answer is either:
(1) Have the controller return a "redirect:" result instead of view name. It must be followed with an absolute url, and behavior might depend on your spring version and configuration, but basically it looks like this:
#RequestMapping(...)
public String myMethod(){
String url=... // database lookup, e.g. "http://myUrl"
return "redirect:"+url;
}
(2) Less elegant but sometimes useful: get direct access to the response. If your controller method has a parameter of type HttpServletResponse spring will automatically inject it. So:
#RequestMapping(...)
public String myMethod(HttpServletResponse resp){
...
response.sendRedirect(...)
}
Right now based on the site name in the URL parameter, we decide the appropriate actions to take(method calls etc) in the Java (Standard Jsp/Servlet web applications). For example, the request would be something like www.oursite.com?site=Ohio
Wondering what would be the alternative of doing this without having to provide URL parameter.
You could use POST instead of GET.
GET appends request parameters to the end of the URL.
POST sends encoded data using a form.
http://www.tutorialspoint.com/jsp/jsp_form_processing.htm
Why not just code it into the path?
www.oursite.com/Ohio
If you're just using straight servlet api, you can just do something of this nature:
String path = request.getPathInfo();
String site = path.split("/")[0];
That being said, most web frameworks have some support for helping with this.
For example, in spring mvc:
#RequestMapping(value="/{site}/blah/blah", method=RequestMethod.GET)
public ModelAndView blahBlah(HttpServletRequest req,
HttpServletResponse resp,
#PathVariable("site") String site) {
// do stuff here
}
Of course you could do this at the controller level too if all your methods need that sort of mapping:
#Controller
#RequestMapping(value="/{site}")
public class MyController {
#RequestMapping(value="/blah/blah", method=RequestMethod.GET)
public ModelAndView blahBlah(HttpServletRequest req,
HttpServletResponse resp,
#PathVariable("site") String site) {
// do stuff here
}
}
I believe this is cleaner than a query param, though it still shows up in your URL. There's other, more complex methods like using apache's reverse proxying and virtual host capabilities to switch based on site names. You could do something at login, and store the site in session. It all depends on your requirements.
You could use an alternate URL, like ohio.oursite.com. This process could be automated by having your server respond to *.oursite.com. I would probably set up a filter that looked at what the subdomain was and compared that with a predefined list of allowed sites. If it didn't exist, you could redirect back to the main (www) site. If it did, you could set a request attribute that you could use in a similar way that you currently use the request parameter now.
is their a neat way to pass a model to jsp, render the jsp and return the html as string using Spring. The html is then used in an e-mail that is fired off programmitcally, I do not want to use freemarker, but maybe I should ?
The url being requested is part of the same app.
I want one of my service layer classes to be able to call a view and use the html as a String.
You can call requestDispatcher.include(request, response) method.
You will need to implement the request and response objects. The request object will provide all information to the dispatcher which page should be rendered, the response object you will pass to the call will then capture the result to a string (using e.g. a StringBuilder).
See e.g. this tutorial for more info.
I'm guessing a servlet filter will do the trick? Not really a Spring solution, but easy enough to do.
Also this answer seems relevant, although it is DWR that you may not necessarily want to use in this instance.
You can use Velocity to create an email template:
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "emailTemplate.vm", model);
There is a complete chapter in the Spring reference docs of how Spring can be used to send emails of various types.
I have started learning GWT and I would like to know if it is possible to create a form in GWT for a process such as user registration and then, handle the logic of the registration(extra validation, adding the data to the database, etc) in a spring controller. I have so far been unable to find resources on the web to do this, so I am guessing that what I am after might not be possible. Can this only be done using classes which extend the RemoteServiceServlet as shown in this video tutorial?
I have tried to access the data from my spring controller using the request.getParameter() method calls, what I noticed was that when I used the Post method, I was unable to access the form parameters, but when I use Get, I can access them. This is some of the code I am using:
GWT:
HorizontalPanel hrzPnlname = new HorizontalPanel();
hrzPnlname.add(new Label("User Name: "));
final TextBox txtUserName = new TextBox();
txtUserName.setName("userName");
hrzPnlname.add(txtUserName);...
Spring:
#RequestMapping(method = RequestMethod.POST)
public ModelAndView helloWorldFromForm(HttpServletRequest request)
{
Map<String, Object> model = new HashMap<String, Object>();
System.out.println("------>\n\n\n\n\n\n" + request.getParameter("userName") + "\n\n\n\n\n<-------");...
I am using GWT 2.4. Any information on this would be highly appreciated.
Thanks!
You can share data between GWT client and spring controllers in a several ways:
REST/JSON request
See how:
Calling REST from GWT with a little bit of JQuery
See also original GWT documentation(section "Communicating with the server/JSON")
This is the best way to communicate with a server in my opinion, because JSON is a pure standard protocol and it can be used by 3-rd party plugins(jQuery for example) and other web services.
Async GWT RMI(Remote method invocation), provided by Google
I think this is not the best idea to use GWT RPC, see why:
4 More GWT Antipatterns
Submit forms directly to spring controller as POST/GET request (as you trying to do).
See com.google.gwt.user.client.ui.FormPanel
I can reconmmend you to use forms submitting only for file uploading, because the browser will only upload files using form submission. For all other operations, form is not required in GWT, any request possible to implement using ajax.
Here are links to some resources - http://technophiliac.wordpress.com/2008/08/24/giving-gwt-a-spring-in-its-step/ and Experiences with integrating spring 3 mvc with GWT? .