How to set request attribute in free marker template - java

I am developing spring batch web application in java that uses SPRING MVC. It uses free marker templates.
I need to set userid in request attribute in javascript written on FTL page.
I am using below javascript to retrieve username. I want to set(WinNetwork.UserName) it in request attribute and want to retrieve this attribute on my servlet.
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
alert(WinNetwork.UserName);
</script>
Please provide help on this.

Related

Cross origin iframe overwrites sessionid

I have a Springboot/angular component (this is an angular component that is authenticated by Spring security and loads its data from a Spring REST API) . This springboot/angular component is being loaded within an iframe of a JAVA EE application.
They are also loaded on separate contexts, localhost:8080 and localhost:7001 respectively.
Problem is, whenever the springboot/angular component is loaded and authenticated in the iframe, it overwrites the Jsessionid, such that the next HTTP request I make on the JAVA EE application, is no longer the original Jsessionid and hence results in an error.
How can I avoid the Jsessionid from being overwritten in this manner while using a cross-origin iframe?
Code in localhost:7001 (JAVA EE application) containing the iframe:
basically, what happens is I call a custom post request to my spring processLogin controller in order to authenticate the spring/angular component, and have the request display in the iframe.
<body>
<script>
function sendForm(){
var username = document.getElementById("sessionUser").value;
var password = document.getElementById("sessionPw").value;
var param = {};
param['username'] = username;
param['password'] = password;
post('http://localhost:8080/processLogin', param );
}
</script>
<iframe id=menuFrame frameborder="0" style="overflow:hidden;" src=""></iframe>
</body>
In fact you are in two separated contexts, so you have two different sessionId. In order to share your sessionId you should implement load balancing or another mechanisms that allow to share sessions at server level.

send json and html at the same time

I implemented a SOA service using other services(I'm using java language). I use servlet to display an html table with the processed results. Is it also possible to send json with html? or in other words is it possible to send two different things in the response of the doPost method of httpservlet?
If you want your html page to access the json you could embed the data within a script tag:
<script type="application/javascript">
var mydata = {"foo":"bar"};
</script>

Spring MVC ajax re-rerendering user interface duplication

First of all I am mainly with a JSF background.
I have started recently studying Spring MVC. One thing that is bothering me is the ajax re-rendering when using Spring MVC and JQuery.
Let's imagine that I have defined a complex form in my people.jsp view:
<c:forEach var="person" items="${people}">
<table>
<tr class="trPersonClass">...</tr>
<tr>...</tr>
</table>
</c:forEach>
And I have a refresh button below. When the refresh button is clicked I want with ajax the people to rerender.
function refreshButtonClicked() {
$.ajax({
type: "GET",
url: "ajax/loadPeople.do"
}).done(function( msg ) {
//WHAT SHOULD I DO HERE???
}
});
So what I should do there? I have already defined how the people rendering should like with the c:forEach tag in my jsp. I don't want to repeat it again. I don't want to duplicate user interface code at both places - in the JQuery done callback and with JSP tags in my views. This is error prone in my opinion.
Please explain me kindly what I am missing here.
First of all, Spring MVC is very flexible. You can have backend handlers that return HTML generated by a view engine, you can have a handlers that returns JSON/XML/ProtocolBuffers/etc. and use client side rendering engines like Mustache etc. to display the page in the browser, or you can combine the two in the same application.
If you want to generate HTML on the server, Spring MVC allows you to use different template engines to do that. You can use JSP, Freemarker, Velocity etc. In order to do that, it uses a ViewResolver abstraction, and in your code you only have to deal with the ModelAndView API.
More details on ViewResolver can be found here: http://static.springsource.org/spring/docs/3.0.x/reference/mvc.html
Based on your question it sounds like you have a backend that use JSP to create the html server side. In order to update only the table and not reload the entire page when a user clicks a refresh button, you could for example have a handler that returns only the html table like so:
#RequestMapping("/table")
public ModelAndView renderTable() {
List<People> people = peopleService.findAllPeople();
return new ModelAndView("/people", "people", people);
}
I'm also assuming you have another handler that returns the main page where the table is embedded via ajax.
<body>
...
/* Content of div will be populated via ajax*/
<div id="myTableContainer" />
...
</body>
The javaScript for this would be something like:
$(function() {
var myTableContainer = $("#myTableContainer");
var renderTable = function(container) {
$.get("/table", function(data) {
container.empty().html(data);
}
};
/* This is called on document ready */
renderTable(myTableContainer);
/* Use the same renderTable function when the refresh button is clicked */
$("#refreshButton").click(function() {
renderTable(myTableContainer);
});
}
Basically, I see 2 options:
Always load the table using ajax, even on the first rendering (table creation code only in your javascript function)
Modify ajax/loadPeople.do to return an already rendered table instead of a Json list. You could then factor the people table rendering code in a JSP Tag file or use some templating library (tiles, etc.) to reuse that JSP fragment.

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;
});
});

Redirect to different page from inside c:import

Is there any way I can redirect to a different page from a Spring Controller that gets called from a JSP using <c:import>?
Scenario is as follows: I have a Spring WizardFormController, that handles a multi-page form and is included into the website using a JSP and <c:import>. After the wizard is finished, I would like to redirect to a different page, but that seems to be impossible from the Controller. At least, if I could get a message to the surrounding JSP, it would already help.
It seems, the only way is to use JavaScript to create a client-side redirect like this:
<script type="text/javascript>
window.location.href = '<URL of Target>';
</script>

Categories