I have a jersey client class which is making a put request to a rest.
//JerseyClient
public void putRequest() throws Exception{
reloadUri();
Response response = target.request(MediaType.APPLICATION_JSON)
.accept("application/json;charset=UTF-8")
.header("Content-Type", "application/json")
.header("Authorization", "Basic OTA1MzAwNjY3MDg2OjZ4dDg5dk50VXdCbg==")
.put(Entity.entity(sub, MediaType.APPLICATION_JSON),Response.class);
System.out.println(response);
if(response.getStatus() == 200) {
System.out.println("put request using Json is Success");
}
}
It's working fine, but I wanted to call this function with a button click. And this button is placed on one of my jsp file. So, is there a way to call this request inside that jsp file when button clicked.And redirect the page into new jsp according to response of rest.
No directly by the jsp. If you include this code in the jsp, it will be executed while parsing the jsp page in the server.
You should include it in a Java component which will be called by a Servlet (or controller, filter, etc...). The button in your jsp will make a call to the URL which executes that component, and is there where you must do whatever you need with the result.
If you want to execute directly in the jsp while clicking the button, you must make it using javascript in client side.
You may call this method using URL reference:
define a path annotation for method:
#Path("/PATH")
#GET// or #POST
public void putRequest() throws Exception{
...
}
And then, from you jsp page you can define the button to redirect to this URL to initiate the above method.
You may read more about jersey annotations here.
Related
I've got two pages that link to the same new page. What I need to be able to do is pass the current page so that the new page can return to it after it has done what needs to be done.
Suppose I have two pages:
/user/46#updateInfo and
/child/993#updateInfo
Both pages have a button
<a id="upload-image" th:href="#{/documents/upload/__${id}__}" class="btn btn-primary"> Upload Image </a>
which triggers the controller:
#GetMapping({documentType}/{userId})
public ModelAndView uploadImage(ModelAndView mav,
#PathVariable(name="documentType") Optional<DocumentType> documentType,
#PathVariable(name="userId") Optional<String> userId,
#RequestParam(name="returnUrl") Optional<String> returnUrl) {
// do stuff here
mav.addObject("returnUrl", returnUrl);
mav.setViewName("uploadImages");
return mav;
}
I've tried adding in the script section of the pages with the upload button the following:
$(document).ready(function() {
$('#upload-image').prop("value", window.location.pathname + window.location.hash);
$('#upload-image').prop("returnUrl", window.location.pathname + window.location.hash);
}
But that value doesn't show up in the controller. And I'm thinking there has to be an easier way.
Again, the goal is when the new page is loaded (in this example uploadImages page), the user will either upload an image or click the Cancel button and then be returned to either the /user/46#updateInfo or
/child/993#updateInfo page, which ever page initially called the uploadImages page.
Add HttpServletRequest object to the list of arguments of your controller method and call getRequestURI() method on that object within that controller.That should do the job - the method returns a String containg a full path of requested URI
I have the following POST handler in Spring boot:
#PostMapping("/handlePostRequest")
public ModelAndView handlePostRequest(HttpServletRequest request, #RequestBody ApiRequest apiRequest) {
// ... Do some stuff with POST params ...
ModelAndView mav = new ModelAndView("myview);
mav.addObject("myProperty", myProperty);
return mav;
}
However, when it displays my very simple view, the Javascript onload function is never triggered.
<!DOCTYPE html>
<body onload="alert('hey');">
<p>hello</p>
</body>
</html>
I can see the "hello" line but the Javascript doesn't work.
Interestingly, if I do a GetMapping for the Spring method (using URL params instead of POST data), the Javascript does work! Anyone know why this is? Why would a POST vs. GET in the controller affect whether the Javascript loads or not? How can I force it to load? I really don't want to have to use a GET here.
UPDATE: Wanted to note that the POST method is being invoked by an ajax call via Javascript. That could make a difference.
As a followup to my earlier question about using Thymeleaf and preventing page refresh:
http://forum.thymeleaf.org/Preventing-page-refresh-Thymeleaf-amp-Spring-MVC-td4029155.html
Basically I had a working Spring MVC app that uses Thymeleaf to save form data. When the user saves the data the page would refresh (since I wanted to leave them on the page for more edits) and I wanted to eliminate the page refresh.
I have coded up some Javascript to use JQuery Ajax to post the data to my Spring MVC Controller. The trick seemed to be to not use a submit button, just a regular button and bind a JS function to it for sending the data to the server.
It all seems to work perfectly, but I want to make sure I understand what is happening. In particular I'm wondering if Thymeleaf is now redundant. I don't think it is because when I initially load the page Thymeleaf is still bound to the data bean. From using the debugger on the server side in the controller it looks like the post request calls the mapped method and passes in the data to the model.
I would appreciate your comments on whether or not this is the correct way to accomplish this.
Finally, how do I handle an error, say for example the repository fails to persist the data for any reason?
Thanks very much.
Here are the important parts of the form:
<FORM id="adminDataForm" action="#" th:action="#{/admin_ajax}" th:object="${adminFormAjax}" method="post">
<input type="button" value="Save Changes" id="post" onClick="sendData()" />
Here is the Javascript:
function sendData()
{
$.ajax(
{
type: "POST",
data: $("#adminDataForm").serialize(),
cache: false,
url: "/admin_ajax",
success: function(data)
{
alert("Your changes have been saved");
},
error: function()
{
alert("Error - Data not saved");
}
});
}
Here is the controller:
#SessionAttributes("adminFormAjax")
#Controller
public class TestController
{
final static protected long INDEX_RA = 2L;
#Autowired
private AdminDataRepository rep;
#RequestMapping(value="/admin_ajax", method=RequestMethod.GET)
public String adminFormAjax(Model model)
{
AdminData ad = rep.findById(INDEX_RA);
// If there is no configuration record, create one and assign the primary key
if(ad == null)
{
ad = new AdminData();
ad.setId(INDEX_RA);
}
model.addAttribute("adminFormAjax", ad);
return "adminFormAjax";
}
#RequestMapping(value="/admin_ajax", method=RequestMethod.POST)
public #ResponseBody AdminData adminSubmit(#ModelAttribute("adminFormAjax") AdminData ad, Model model)
{
rep.save(ad);
model.addAttribute("adminFormAjax", ad);
return ad;
}
}
So breakdown of answer.
Thymeleaf not redundant, it will still render the HTML page prior to sending to client. Ajax just does the further processing for you on client side.
You can use submit button as well, you just need to ensure your form is properly structured and you have javascript listening for your submit button click e.g.
$("#submitbutton").on('click', function (){//do stuff});
You handle any and all exceptions/issues within your Ajax controller as you would with standard controller. You need to separate issue handling at different levels. e.g. respository level issues should be managed at rep level, controller/pojo should be at controller level (or pojo if you using one for processing). You should also be capturing any exceptions through a global medium (e.g. ControllerAdvice).
Any issues/errors you pick up you should be communicating back via your return call in adminSubmit, and managing the relevant client response in ajax.
I am trying to do the following :
function redirectContactOnClick(contactId) {
var enc=<%= QueryStringModule.Encrypt("cont="+ contactId)%>;
alert(enc);
//window.location = "Contacts/AddEditContact.aspx";
}
QueryStringModule.Encrypt is a function inside a c# class, the page raise an error saying :The name 'contactId' does not exist in the current context
You won't be able to pass your javascript variable (contactId) to C# method. Suggest to look a different solution for that, for example, making Generic Web Handler (.ashx) and pass there your contactId via ajax and get back whatever you expect from your Encrypt call.
You can call Server side(C#) function from javascript.
First you have include your script inside a ScriptManager runnable at server.
Then the javascript function can call the c# function (which is having an attribute of ([System.Web.Services.WebMethod] and must be static) can be accessed.
eg.
PageMethods.QueryStringModule.Encrypt("cont="+ contactId);
on client-side, and
[System.Web.Services.WebMethod]
public static void Encrypt(string id)
{
// Do something
};
on server-side
(Source: http://www.codeproject.com/Questions/727256/how-to-call-server-side-function-from-javascript)
For to call the Server Side member the only mode is do a request HTTP or sync (POST Page) o async (AJAX)
you don't call a server function directly
in the you case
receive an error because contactId not is an page's member you can comunicate with these way
ASP.NET Client to Server communication
When I try to upload file in Wicket I've got the following exception:
"ERROR org.apache.wicket.RequestCycle.logRuntimeException(RequestCycle.java:1529) - ServletRequest does not contain multipart content. One possible solution is to explicitly call Form.setMultipart(true), Wicket tries its best to auto-detect multipart forms but there are certain situation where it cannot.
java.lang.IllegalStateException: ServletRequest does not contain multipart content. One possible solution is to explicitly call Form.setMultipart(true), Wicket tries its best to auto-detect multipart forms but there are certain situation where it cannot.
at org.apache.wicket.protocol.http.servlet.MultipartServletWebRequest.<init>(MultipartServletWebRequest.java:113)..."
However, when I set form.MultiPart(true) I can't get Javascript dialog by using:
target.appendJavascript("Some Message");
Does somebody know how to use Javascript when Form.Multipart(true)?
Thanks!
If you want to call the alert dialog as a response for an ajax request, you can use the appendJavascript() method (the argument is javascript code, not a simple string, like the code you posted):
target.appendJavaScript("alert('Some message');");
If you want to call the alert when the page loads, you could use a behavior:
add(new AbstractBehavior() { // or Behavior, on Wicket 1.5
#Override
public void renderHead(Component component, IHeaderResponse response) {
response.renderOnLoadJavaScript("alert('Some message');");
}
});
It's also possible use a Label, and render directly to a <script> tag. Just remember to call setEscapeModelStrings(false):
add(new Label("alert", "alert('Some message');").setEscapeModelStrings(false));
and
<script type="text/javascript" wicket:id="alert"></script>