ajax call with java action in jsp (J2EE) - java

I am trying to make a login page in java J2EE. Actually, I succed in making a jsp page, called login.jsp, an ActionSupport class called LoginAction. In my jsp I've created some text area, password area and submit, allowing me to send informations entered in those areas and get them in my action. This works fine.
My problem is that I don't succed in using another function than execute. In my action I have several other functions and I can't call them in my ajax function :
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(function() {
$('#submit').click(function() {
var login=$("#login").val();
var password=$("#password").val();
$.ajax({
type: 'POST',
url: 'login.action/test', // -> here it fails.............
data: { login: login, password: password },
success: function() {
alert('YEAH'); },
error: function() {
alert('Request failed'); }
});
});
});
</script>
What should I put in url area, if I want for example to call test function in my LoginAction class? (I've done a test.jsp page, it doesn't change anything...)

OK I found the answer. So here it is :
It's called "dynamic method invocation" (with wildcard method), and you can find the doc here :
http://struts.apache.org/release/2.0.x/docs/action-configuration.html#ActionConfiguration-WildcardMethod

It is very important to use last struts2 release to avoid critical security bugs while using wildcard method - see https://struts.apache.org/release/2.3.x/docs/s2-015.html for details.

use "function nametest()" instead of "function()"

Related

Ajax not reloading the jsp on success

Environment: IE7, jQuery 1.1 , Struts 1
Context: Making an ajax call to a Java method which, and the end, reloads the same jsp.
The steps are: jsp A -->request to java method-->doing some stuff-->ActionForward to jsp A, which is returned in the response.
Actually I'm doing this with a single request using location.href and it's working properly.
Now I need to handle multiple requests and conditions and the only way I thought was by using nested ajax calls with async:false, but that's not the point.
The problem is ajax does not reloads the jsp like location.href does.
This jsp is just a smaller part of the main jsp, so I'm not reloading the whole jsp. I guess I have to handle the response in some way, but how?
Call with location.href:
<script>
function myFunction(){
location.href = 'path/to/java/method=with_some_parameters';
}
</script>
Call with ajax:
<script>
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
//nested ajax
}
});
}
</script>
There is a similiar question:
Reload a page after jquery ajax call,
but it didn't help.
Another: How to manage a redirect request after a jQuery Ajax call, this looks better. I'm trying some things.
As I got the full html in the response ('data' in my case), It worked using
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
document.open();
document.write(data);
document.close();
//nested ajax
}
});
}
Source Replacing Entire Page Including Head Using Javascript

How to send response through ajax from servlet back to jsp? [duplicate]

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

JSP not returning data to JQuery AJAX

Here is my function. I am trying to get the data from the JSP page below. Both files are at the same location. What is my mistake?
sample.js(included in some file):
function getUnits(){
$.ajax({
url:"../js/addunits.jsp",
success: function(returndata){
alert(returndata);
}
});
}
JSP Page addunits.jsp:
<%
out.print("hi");
>%
In a HTML page, I have a select list.
On change, this function getunits will be called.
$("#select").change(function() {
getUnits();
var e = document.getElementById("select");
var SelValue = e.options[e.selectedIndex].text;
document.getElementById('crs').innerHTML = SelValue;
});
You forgot to flush a buffer.
<%
out.print("hi");
out.flush();
%>
EDIT:
It was an assumption at the first place in case if you have a success status code for the ajax call and it might be in particular scenario like yours but not in all cases because if you used that javascript included in some file, then you might make the same mistake twice. When building some URL on the page don't use a relative path in the code, especially if the page is dispatched/included from different places. Next in the absolute path you should include a context path either ${pageContext.request.contextPath} or use JSTL's <c:url> tag. You can do it for loading sample.js but not inside it because you can use the JSP stuff only on JSP page. So, you can build the URL in the JSP and pass it as parameter to js function like that
sample.js:(included in some file)
function getUnits(theUrl){
$.ajax({
url: theUrl,
success: function(returndata){
alert(returndata);
}
});
}
So, in JSP page (you should use jsp folder where you should keep JSP pages) use
<script>
...
getUnits('${pageContext.request.contextPath}/jsp/addunits.jsp');
...
</script>

Spring MVC + JQuery + Ajax Issue

I'm trying to make an Ajax call to my Spring MVC app using a Jquery Ajax. The app controllers are working fine but I can't get this Ajax test controller to work. The alert is triggered but the call to the controller is never made. I've also tried using load, get, post. None of them call the server. Which makes me think I'm doing something obviously wrong. If I put the URL directly on the browser address bar, the controller is called.
If someone can guide me in the right direction or tell me what I'm doing wrong, I'd be grateful.
JavaScript
<html>
<head>
<script type="text/javascript" src="jquery-1.8.1.min.js"> </script>
<script type="text/javascript">
function doAjax() {
alert("did it even get here?");
$.ajax({
url : "simpleRequestTest.do",
method: "GET",
success : function(response) {
$('#show').html(response);
}
});
}
</script>
</head>
<body>
<h1>Simple Test </h1>
Simple Test
<br />
<div id="show">...</div>
</body>
</html>
Controller
#RequestMapping("/simpleRequestTest")
public #ResponseBody String performSimple() {
return "Very Simple Test";
}
Can you check whether you use correct path for include the jquery-1.8.1.min.js.
I checked the code it's working file for me.
I think you are missing dataType in ajax call
try this
function doAjax() {
alert("did it even get here?");
$.ajax({
url : "simpleRequestTest.do",
method: "GET",
success : function(response) {
$('#show').html(response);
},
dataType: 'text'
});
}
Just change url : "simpleRequestTest.do", to url : "simpleRequestTest", and method: "GET", to type: "GET",
I think the method is removed in the jquery version 1.5 and latest

Updating div with post results using radio button and jquery/Ajax

I'm working with a third party that is generating div content based on a post response from my server (java servlet). One problem I have is that we have a list of radio buttons leveled in a form.
When I hit submit on that form, I need to make a post call to my server and re-render that div in the third party site. I have used different variations of jQuery to no avail.
I've included the most recent jQuery (also tried a sub 1.4 release of jQuery). When I hit the submit button on my form, I just render the same page and I do NOT render a call to the server.
How can I do this, update a div on the local page that renders my post results based on a form I write? Below is what I currently have:
Form:
<form action='\' id=\"form1\">... radio buttons ... </form>
<input hidden field name = value passed from Java method>
<input hidden field id = value passed from Java method>
<input hidden field the value of the selected checkbox>
HTML:
<script language='Javascript' type='text/javascript'>
$(\"#form1\").submit(function(event) {
event.preventDefault();
var $form = $( this ),
name2= $form.find( 'input[name=\"name\"]' ).val(),
id2= $form.find( 'input[name=\"id\"]' ).val(),
url = $form.attr( 'action' );
$.post( url, { name2:name, id2:id },
function( data ) {
var content = $( data ).find( '#content' );
$( \"#this_div\" ).empty().append( content );
});
});
</script>
Sending AJAX Requests from a Third Party site to your server:
Due to browser security requirements, it is not currently possible to make cross-domain AJAX requests to a third-party server. This means that the $.post request is limited to what is referred to as the same-domain policy.
Thus, if your server is example.com and the third party server is domain.com, domain.com cannot make AJAX requests to your server.
However, there is a technique you can use to circumvent this browser security. While it's not possible for XMLHttpRequests to be made cross domain, JavaScript <script> tag blocks can load JavaScript from any domain.
Script tag remoting, or JSONP, involves using a script tag to send a request to your server:
Script tag:
// from domain.com to your server, example.com, make a request using a script tag
var urlWithParams = "http://example.com/getHTMLForm.do?id2=" + id2 + "&name2" + name2;
var script = document.createElement("script");
script.setAttribute("type","text/javascript");
script.setAttribute("src", urlWithParams);
// create a script tag, which invokes your servlet
document.getElementsByTagName("head")[0].appendChild(script);
getHTMLForm.do is a hypothetical servlet that you're currently using to post the data and get HTML in the response. Instead of passing the parameters in the Request body using POST, you'll pass the data as query parameters.
Server response::
The server then responds with JSON that you generate on the server, but it's wrapped -- or padded -- inside a JavaScript function that is defined on the web page making the request.
// your response from your server
insertFormOnPage({"html":"<form action='#'><input name='name' /><input name='id' /></form>", "elem" : "#content"});
Third party Client side code:
For this technique to work, the third party site must have a function defined that matches the one your server will return:
function insertFormOnPage( data ) {
alert( data.html ); // prints the HTML for debugging
alert( data.elem ); // prints the selector you want to insert into
// inject the HTML into the #content DIV
$( data.elem ).html( data.html );
}
HTML on the third party site:
<!-- Let's just assume the third party site's DIV is empty for simplicity -->
<div id="#content"></div
Explanation:
Your server returns pure JavaScript to the client side, as JavaScript, as a function that executes immediately.
The function receives the following items as properties in a JavaScript object: The HTML, and the div id.
The function accesses the object's html and elem properties to access both the html string and the selector.
Using jQuery, the function injects the HTML inside the DIV#content element.
The last and final thing you should know about this technique is that it only supports GET methods, since that is how JavaScript is fetched from the server. This means that you'll need to make sure your server is configured to accept GET requests for this data and not POST requests.
JSONP Using jQuery:
While the above solution helps describe the concepts of what is happening under the hood, you may also want to check out jQuery getJSON. Specifically, look at the JSONP examples, which are the only way to make cross-domain requests without reloading the page.
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
tags: "cat",
tagmode: "any",
format: "json"
},
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
});

Categories