Simple AJAX support for Wicket 1.5.4 - java

I'm new to wicket and AJAX and trying to set up a simple page that passes messages from the html page via jQuery & ajax to a wicket servlet. The page then updates a label with an appropriate response.
I tried to use the code below from Marrying Wicket And jQuery UI Autocomplete Ajax but the code does not compile using Wicket 1.5.4. getParameterMap(), setRequestTarget and StringRequestTarget are all unrecognised in wicket 1.5.4.
Any help would be much appreciated.
add(aab = new AbstractAjaxBehavior() {
#Override
public void renderHead(Component component, IHeaderResponse response) {
super.renderHead(component, response);
response.renderJavaScript("var callbackUrl = '" + aab1.getCallbackUrl() + "';", "callbackurl");
}
// handle the ajax request
#Override
public void onRequest() {
System.out.println("ajax request received");
RequestCycle requestCycle = RequestCycle.get();
Request request = requestCycle.getRequest();
IRequestParameters irp = request.getRequestParameters();
String json = getJSON();
requestCycle.scheduleRequestHandlerAfterCurrent(new TextRequestHandler("application/json", "UTF-8", json));
}
});

This was solved as the tutorial code was updated.

Related

How do I redirect users after successfully submitting form data?

I have a website through which you can create bundles and add custom or predefined tasks to them.
Everything works okay, I can change all these fields whenever I want. Once all these fields look alright to you, you have to click the "Save" button. Once you click it, the fields are validated through several methods. If all the fields were validated successfully, Ajax sends a post request to my Spring controller which then stores everything into a database. After that, I would like to redirect user to the page which displays all the existing bundles.
I have already tried to do this:
#RequestMapping(value = "/bundle", method = RequestMethod.POST, consumes = {"application/octet-stream", "multipart/form-data"})
public void bundle(MultipartHttpServletRequest request,
HttpServletResponse response) throws IOException {
// Code to store bundles to a database.
// Redirect
response.setHeader("Location", "http://localhost:8080/bundles");
response.setStatus(302); //302 Found
// I have also tried to replace above two statements with this
response.sendRedirect("http://localhost:8080/bundles");
}
The above code does execute and the request is sent to /bundles
But I seem to be stuck on the initial page, no redirect was made.
I had the same problem as you have. I solved the issue by redirecting in the Front-End with Angular.
You can use the answer from your HTTP-Request in javascript and then redirect from there.
My Server-Side code:
#PostMapping(AdminToolConstants.MAPPING_CHECK_USER)
public ResponseEntity checkUser(HttpServletResponse response, #RequestBody UserDto userDto) throws IOException{
if (userService.checkUser(userDto)) {
return new ResponseEntity(HttpStatus.OK);
} else {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
Client-side javascript:
angular.module('admintool.services', []).factory('UserService', ["$http", "CONSTANTS", function($http, CONSTANTS) {
var service = {};
service.checkUser = function (userDto) {
return $http.post(CONSTANTS.checkUser, userDto).then(function (value) {
window.location.href = "/";
}).catch(function (reason) { window.location.href = "/register" });
};
return service;
}]);
Inside .then I redirect the user when the, for example, login was successfull and inside .catch if the login wasn't successfull.

htmlunit can not call post ajax requests

I have a webpage that fills a datagrid with post ajax requests like this
$.ajax({
type: "POST",
url: "http://bss.bimser.com.tr/Handlers/eBADataGridHandler.ashx",
data: '{"ID":"dgSearchTickets","Type":0,"Page":"2","FilterInput":[],"QuickFilterText":null,"SortedColumn":""}',
success: function(msg){
console.log(msg);
}
});
When i try this with the below code i cant get html result; my code;
webClient.getOptions().setJavaScriptEnabled(true);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
UnexpectedPage upage = webClient.getPage(webRequestPost);
HtmlPage page = HTMLParser.parseHtml(upage.getWebResponse(), webClient.getCurrentWindow());
WebRequest webRequestPost2 = new WebRequest(new URL(".../DataGridHandler.ashx"), HttpMethod.POST);
webRequestPost2.setAdditionalHeader("Content-Type", "application/x-www-form-urlencoded");
webRequestPost2.setRequestBody(DefaultValues.searchPagingJson2);
page = webClient.getPage(webRequestPost2);
this code returns an error webpage. How can i get html info ?
EDIT:
page.executeJavaScript("var request = new XMLHttpRequest();\n" +
"request.open('POST', 'http://bss.bimser.com.tr/Handlers/eBADataGridHandler.ashx', true);\n" +
"request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');\n" +
"request.onload = function() {\n" +
" document.getElementsByTagName(\"body\")[0].innerHTML = request.responseText;\n" +
" console.log(request.responseText);\n" +
"};\n" +
"request.send('{\"ID\":\"dgSearchTickets\",\"Type\":0,\"Page\":\"%s\",\"FilterInput\":[],\"QuickFilterText\":null,\"SortedColumn\":\"Sent Date\"}');\n");
I was able to solve the problem by executing the code above. Now the problem is without manual waiting htmlunit does not wait for the result. I tried this below
WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
webClient.getOptions().setJavaScriptEnabled(true);
webClient.setAjaxController(new AjaxController() {
#Override
public boolean processSynchron(HtmlPage page, WebRequest request, boolean async) {
return true;
}
});
In general HtmlUnit can do ajax requests.
Creating you own web request is not the design idea of HtmlUnit. Think about HtmlUnit more like a browser automated by your code. Have a look at the samples on the HtmlUnit homepage.
If you really like to create your own requests you are responsible for the whole request. This includes various headers for security or session information. Install a web proxy like Chares and watch the communication of the real page. Then you might be able to create a similar request. And have a look at the returning webpage maybe there is a hint for you (like the login is missing).

Interacting the JSP page with the Servlet doGet() method through AJAX call

Am doing the JAVA code found below, to call the servlet doGet() method from JSP page through AJAX call.
Here is my AJAX call..
Am sending the clicked text captured by ng-click of Angular js as a querystring to Servlet's doGet() method .
In my JSP file,
$scope.requestFunc = function (clickData) {
var urlquerystring = clickData;
jQuery.ajax({
type: 'GET',
url: "/Charts/testExecution/"+"?"+ urlquerystring,
dataType: 'html',
success: function(respnsedata)
{
window.location.assign(respnsedata);
}
});
}
In my Servlet's doGet() method,
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.err.println("In TestExecutionESO servlet..");
String teamnametextfield= req.getParameter("teamnametextfield");
System.out.println("Teamname is.."+teamnametextfield);
try {
dcmanager = DataCollectorManager.getInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String selectedteam= req.getQueryString();
String testexeclistofobjectsjson = null;
if(selectedteam!=null)
{
String release=selectedteam.replace("%20"," ").toString();
testexecutionobjlist = dcmanager.getRallyDcMgr().gettestExecutionobjlist(release);
}
Gson gson = new Gson();
testexeclistofobjectsjson = gson.toJson(testexecutionobjlist);
System.out.println(testexecutionobjlist);
System.out.println(testexeclistofobjectsjson);
req.getSession().setAttribute("testexeclistofobjectsjson", testexeclistofobjectsjson);
resp.sendRedirect("TestExecutionESO.jsp");
}
Am getting the querystring perfectly..After the processing, I will do SetAttribute() and redirect to next JSP page..
Redirect is not working..
Here is my error code,
Failed to load resource: net::ERR_TOO_MANY_REDIRECTS..
http://10.112.81.95:9000/Charts/testExecution/TestExecutionESO.jsp.... Failed to load resource: net::ERR_TOO_MANY_REDIRECTS
Please help me resolve the problem..
how to redirect to next JSP page by doing the setAttribute() .??
resp.sendRedirect("TestExecutionESO.jsp");
This is the culprit in your code. when you call sendRedirect(), it will issue a 302 response containing the location-header, URI of the new resource. When the browser sees this header, it will issue a new request for that new URI.
All of this works well for a synchronous request but in case of AJAX calls, we use an XMLHttpRequest, which will not handle redirects so well.
I'd suggest you to use a RequestDispatcher instead to forward to the JSP like this
RequestDispatcher rd = req.getRequestDispatcher("path-to-ur-jsp");
rd.forward(req,res);

Access server side text in ajax jQuery

I am creating a jsp application in jsp.I am trying to redirect to login page on ajax request if user is not signed in.
My approach
The request is send from javascript that pass some parameters to
url.The server side code checks is user is signed in or not.
The server side code has a function to build sign in url
The Problem where i am stuck is i have to pass this text to client side from server to javascript so that i can use something like window.location.href=url;
Can anyone please explain how do i pass this url and access it in callback function in ajax success function.
Is there any other approach?..
Checking the user is logged in should probably be handled by your JSP code.
That way you can send redirect headers before the page is rendered, rather than having to wait for a ajax response to be returned before redirecting the user. Using ajax will mean they see the page they don't have access to before you redirect them.
There are tons of ways to handle ajax request. The simplest way (not necessarily best) is to create a servlet to handle your ajax request. Below servlet example will return the json string { status: 'not logged in'}:
package mycompany;
public CheckLoginServlet extends HttpServlet {
protected doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("application/json");
HttpSession session = req.getSession();
// do your stuff to check if user logged in here ..
PrintWriter writer = res.getWriter();
writer.append("{ status: 'not logged in' }");
}
}
Declare & map this servlet on your web.xml deployment descriptor file:
<web-app>
<servlet>
<servlet-class>mycompany.CheckLoginServlet</servlet-class>
<servlet-name>CheckLoginServlet</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>CheckLoginServlet</servlet-name>
<url-pattern>/checklogin</url-pattern>
</servlet-mapping>
</web-app>
The servlet is now mapped to http://myhost/myappname/checklogin. You can then send ajax post request to this servlet via jquery:
$.ajax('checklogin', {
type: 'POST'
}).done(function(res) {
console.log(res.status); // will give you 'not logged in'
});
This approach is ofcourse an old and obsolete approach, but it's good for you to understand servlet basics. If you're building real-life enterprise application consider using web frameworks such as Spring or JSF.
You can send the user status and the sign-in URL in the response as JSON. Let us create a model for your response.
public class Result {
private boolean status;
private String url;
Result() {
}
Result(boolean status, String url) {
this.status = status;
this.url = url;
}
// getters and setters
}
Now in your action where you check the user status and build the sign in url, initialise your model.
Result res = new Result(status, url);
Now we need to send this model as json response. There are many ways to do that but I will be using the Google GSON to serialize the model into json string.
private String result;
public void getResult() {
return this.result;
}
public void setResult(Stringresult) {
this.result = result;
}
Gson gson = new Gson();
result= gson.toJson(res);
==> json is {"status": true,"url":"www.example.com"}
The last part is checking the response in your client side and taking the appropriate action.
$.ajax({
// ...
success: function(response) {
var responseJson = JSON.parse (response.responseText);
if (!responseJson.status) {
window.location.href = responseJson.url;
}
}
});
References : https://sites.google.com/site/gson/gson-user-guide

GET request using GWT to retrieve XML data?

Oh hello there, fellow SO members,
I have a web service that returns XML data using a simple get request that goes like this :
http://my-service:8082/qc/getData?paramX=0169&paramY=2
the service returns raw xml in the page according to the parameters' values.
I am trying to retrieve this data from a GET request in GWT using RequestBuilder, Request, etc.
However, the response gives me empty text, a Status code of ZERO (which doesn't mean anything and isn't supposed to happen), and so on.
Here's the simplified code that doesn't work.
public class SimpleXML implements EntryPoint {
public void onModuleLoad() {
this.doGet("http://my-service:8082/qc/getData", "0169", "2");
}
public void doGet(String serviceURL, String paramX, String paramY) {
final String getUrl = serviceURL + "?paramX=" + paramX + "&idTarification=" + paramY;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, getUrl);
try {
Request response = builder.sendRequest(null, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
response.getStatusCode(); // Gives me 0 (zero) :(
}
#Override
public void onError(Request request, Throwable exception) {
// ... doesn't matter for this example
}
});
} catch (RequestException e) {
// ... doesn't matter for this example
}
}
}
I don't get why this wouldn't work, since this is REALLY simple, I've seen tutorials and they all show me this way of doing things..
Thanks in advance
The reason is, that browsers do not allow cross-site requests with AJAX (see Same Origin Policy).
This means, that you can only call a service on the same server, same port (using the same protocol) as your HTML page. If you want to perform cross-site requests, you can use JSONP, as explained in http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html.

Categories

Resources