How to pass javascript variable in jstl function to managed bean? - java

I want to use javascript value in jstl function on jsp page which call function in managedbean. anyone help.
Javascript code:
alert(document.getElementById('data').value);
'${mapBean.testfunc(document.getElementById('data').value)}';
managedbean:
public void testfunc(String a) {
System.out.println("my function test is printed"+a);
}

I don't work with JSP, but I don't think this is possible. Websites use a Client-Server-Model. The Java-Code (Beans) are executed on the server, the Javascript-Code is executed in the browser on the client (AFTER the website already left the server).
To communicate back from javascript-code on a webpage to the server, you have to use AJAX-Calls. This is a new HTTP-Request which doesn't reload the page but gets processed by your own javascript-code.
Maybe this tutorial can help you: http://howtodoinjava.com/2013/06/21/complete-ajax-tutorial/

Related

Call controller method from JSP button in Spring MVC

I would like to call a controller method using a button on a JSP page in Spring MVC, but I would like it to stay on a current page, don't reload it or anything, simply call a method. I found it difficult. My button is on cars.jsp page. In order to stay on this page I have to do something like this:
#RequestMapping(value="/start")
public String startCheckingStatus(Model model){
System.out.println("start");
model.addAttribute("cars", this.carService.getCars());
return "car\\cars";
}
button:
Start
But this is not a good solution because my page is actually reloaded. Can I just call controller method without any refreshing, redirecting or anything? When I remove return type like so:
#RequestMapping(value="/start")
public void startCheckingStatus(Model model){
System.out.println("start");
}
I got 404.
Add an onclick event on your button and call the following code from your javascript:
$("#yourButtonId").click(function(){
$.ajax({
url : 'start',
method : 'GET',
async : false,
complete : function(data) {
console.log(data.responseText);
}
});
});
If you want to wait for the result of the call then keep async : false otherwise remove it.
As mentioned elsewhere you can achieve this by implementing an Ajax based solution:
https://en.wikipedia.org/wiki/Ajax_(programming)
With Ajax, web applications can send data to and retrieve from a
server asynchronously (in the background) without interfering with the
display and behavior of the existing page. By decoupling the data
interchange layer from the presentation layer, Ajax allows for web
pages, and by extension web applications, to change content
dynamically without the need to reload the entire page.
To achieve this you will need to make changes to both the client and server side parts of your app. When using Spring MVC it is simply a case of adding the #ResponseBody annotation to your controller method which:
can be put on a method and indicates that the return type should be
written straight to the HTTP response body (and not placed in a Model,
or interpreted as a view name).
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-responsebody
Thus, for example, to return a simple String in the Ajax response we can do the following (without the #ResponseBody the framework would try and find a view named 'some status' which is obviously not what we want):
#RequestMapping(value="/start")
#ResponseBody
public String startCheckingStatus(Model model){
return "some status";
}
For the client part you need to add some javascript which will use the XMLHttpRequest Object to retrieve data from your controller.
While there are various frameworks which can simplify this (e.g. JQuery) there are some examples at the below using vanilla javascript and it might be worth looking at some of these first to see what is actually going on:
http://www.w3schools.com/ajax/ajax_examples.asp
If we take this specific example:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
and [1] copy the <button/> and <script/> elements to your JSP, [2] change the URL to point to your controller and, [3] create an element <div id="demo"></div> in your JSP then, on clicking the button in your page, this <div/> should be updated to display the String returned by your controller.
As noted this is a lot of code for one action so you can use some JS framework to abstract a lot of it away.

wicket url parameters with stateful pages

on an application i develop i'm trying to keep a nice and readable url for the application's pages.
i start with url as follows:
http://somedomain.com/context/?param1=value&param2=value
where context is the application mount path and param1 and param2 are some parameters passed to the application.
the problem is that when i move to another page the url changes to be as follows:
https://somedomain.com/?wicket:bookmarkablePage=:something&Title=something&group=something
the way i'm moving between pages is as follows:
getRequestCycle().setResponsePage(new otherPage(obj1, obj2,
pageParameters)
where obj1 and obj2 are objects required for the initialization of the page.
as i understood from this post using
RequestCycle().setResponsePage(Page page)
creates a stateful page which is not bookmarkable and does not display the parameters, while using
RequestCycle().setResponsePage(Class<C> pageClass, PageParameters
pageParameters)
creates a stateless page which displays the parameters.
the problem is that i use the first one, as i must create the page myself so i could pass the two objects to it.
is there any way to keep the url in its original bookmarkable format and remove wicket's parameters from it?
i tried almost every suggestion posted on this site and others but none of them fits my case, as they suggest to let wicket create the page itself (with the second option of setResponsePage).
any help will be much appreciated.
thanks
from your url example i see you are using Wicket 1.4. I believe 1.5 will do what you want out of the box. in Wicket 1.4 you can achieve a similar result by mounting the page using HybridUrlCodingStrategy.

JSP and Java Servlet problems

I am new to JSP and Java Servlet. I am quite confusing about Session object. I saw session When I learned PHP session and cookie. Are there complete different things? And how a Session object is created, structured and used. This object is in JSP or Java Servlet? could somebody tell me this by words(like concept). In addition, in what situation a JSP page would be appropriate for?(when should I use a Java Servlet and when should I use a Java Servlet Page).For Java Servlet object, for example, ran an email site. There will be a lot of users. How does one Java Servlet object deal with interactions from so many browsers?(like hundreds of logging, reading, etc.)I know there should be only one copy of Java Servlet object exists. But why? If only one there, when is it created and destroyed. Ah... So many questions. If someone can help me I will really grateful for this. Thanks a million!
? And how a Session object is created, structured and used.
It depends on the implementation of it, here is the contract
This object is in JSP or Java Servlet?
This is as an implicit object in jsp and it can be retrieved from request instance from servlet's service method
what situation a JSP page would be appropriate for?(when should I use a Java Servlet and when should I use a Java Servlet Page).For Java Servlet object, for example, ran an email site. There will be a lot of users. How does one Java Servlet object deal with interactions from so many browsers
Use jsp as view servlet as controller, See MVC
now there should be only one copy of Java Servlet object exists. But why? If only one there, when is it created and destroyed.
each request is served in different thread so why to create different instance, we can have one instance of servlet doing all this for us. and its alive until garbage collection clears it
See : Head First
You can think about a session object as a file . every user have a session with id called jsessionid , the structure of a session is normally a map data structure which store key value
in Servlert you can construct a session object like this
HttpSession session = request.getSession(true);
then you can add item to the session like this
session.setAttribute(string ,object); ex : session.setAttribute("username","foo");
the session object exist in servlet and jsp , and btw jsp eventually is a servlet
but the difference is that when u want to use session in a jsp page there is no need to construct it. its defeind by default just use it
session.setAttribute(string,object);
JSP page used when a page contains a lot of html element and have a lot of design
and jsp let you maintain the page easily on the other hand you can use servlet as jsp page
but you will deal with every line o html source code
JSP is preferred as a view in the MVC model
and the servlet as controller .
the server keeps one object for each servlet and when a new request come the servlet object put the new request (client ) in a new thread so if you have 100 client at a time the is
100 thread in server . but you can configure the server to construct more than one object of a servlet .
i hope i could help u ..
I think many of your questions would be answered if you had a look at the Java Servlet Life Cycle.

JSF & Facelets Flow

I have a dynamic Facelets page that needs to show information from database when the page loads. At this point in the flow, there have not been any form submissions. Every JSF example I can find only shows a form submission with dynamic results on the next page.
Every call I make to our database is currently takes place after an action has been triggered by a form submission. Where should this code go if there hasn't been a form submission, and how do I trigger it? A code snippet would really help me out!
You should be able to do your initialization work in the constructor (or lazily in one of your accessors) of your managed bean.
If you're using Spring integration (see here also), it's easy.
In your backing bean, simply use something like:
public class BackingBean implements InitializingBean
{
public void afterPropertiesSet()
{
loadInitialData();
}
}
If you're not integrating with Spring there are two options:
Load the initial data in the class constructor;
In your faces-config.xml, you can set properties to be injected. Properties are guaranteed to be set in the order they're specified in the config file. So, just create a dummy property and then within that method load up your default data. i.e. create a method public void setLoaded(boolean loaded) { loadInitialData(); }, and in your faces-config.xml have 'loaded' being set as a property on that backing bean.
Hope this is all clear!
You write (with my emphasis added):
Every call I make to our database is currently takes place after an action
has been triggered by a form submission. Where should this code go
if there hasn't been a form submission, and how do I trigger it? A
code snippet would really help me out!
It sounds to me that you want to retrieve information from the database prior to form submission.
It seems to me that you want to make an Ajax call to query the database. The Ajax call can fire on a different event than the form submisson event. This will probably entail using Javascript rather than the Faces framework.

How do I call Java code from JavaScript code in Wicket?

If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket.
erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java.
For example, from AjaxLazyLoadPanel:
component.add( new AbstractDefaultAjaxBehavior() {
#Override
protected void respond(AjaxRequestTarget target) {
// your code here
}
#Override
public void renderHead(IHeaderResponse response) {
super.renderHead( response );
response.renderOnDomReadyJavascript( getCallbackScript().toString() );
}
}
This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered.
To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js.
Check out the mailing list for lot's of conversation on this topic:
http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438
Excerpt from https://cwiki.apache.org/WICKET/calling-wicket-from-javascript.html
If you add any class that extends AbstractDefaultAjaxBehavior to your page, wicket-ajax.js will be added to the header ofyour web page. wicket-ajax.js provides you with two basic methods to call your component:
function wicketAjaxGet(url, successHandler, failureHandler, precondition, channel)
and
function wicketAjaxPost(url, body, successHandler, failureHandler, precondition, channel)
Here is an example:
JavaScript
function callWicket() {
var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { });
}
$url$ is obtained from the method abstractDefaultAjaxBehavior.getCallbackUrl(). If you paste the String returned from that method into your browser, you'll invoke the respond method, the same applies for the javascript method.
You can optionally add arguments by appending these to the URL string. They take the form &foo=bar.
you get the optional arguments in the Java response method like this:
Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();
or this:
String paramFoo = RequestCycle.get().getRequest().getParameter("foo");
http://www.wicket-library.com/wicket-examples-6.0.x/index.html/ has plenty of examples to get you going.
Or have a Have a look at DWR
http://directwebremoting.org/
DWR allows Javascript in a browser to interact with Java on a server and helps you manipulate web pages with the results.
As Dorward mentioned this is done via AJAX
Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.
This is known as Ajax, and there are a number of libraries that help you do it..

Categories

Resources