Can I write methods in JSPs? (Java Server Pages)
I tried writing a method within the body of the JSP, but my IDE doesn't seem to like it.
JSP can only show information to user, if you want to do some elaboration you have to re-call a servlet that to that for you.
Analize and try using this:
Everything in your jsp.
But i recommend you that if your a gonna use methods, use classes instead. They are safer and loads quite faster when calling them.
<%
//Your main logic
out.print(myMethod());
%>
<html>
your client side content
</html>
<%!
public String myMethod(){
return "Method called successfully";
}
%>
Related
There are many similar questions but I am not clear about one thing as mentioned below-
I have ajax call
var url = '/test/testjsp.do?param1=' + xyz;
$.ajax({
type:'GET',
dataType:'html',
url:url,
success:function (data) {
alert("Success");
}
});
which is calling an JSP page
and in that file, I am calling method from SM class
<%# page import="com.testAjax.SM" %>
<%
if (null != request.getParameter("
SM.randomMethod(request.getParameter("param1"));
}
%>
So my question is ,
I there any alternative method where I don't have to create extra Jsp file and call java method directly from Ajax call
Please help and Advise
As javascript is a client side script, it cannot invoke java methods directly which resides on the server.
To do that you have to create a web service or jsp like you did.
But I have seen vaadin gives option to call java code from javascript without writing a service or jsp. I dont know how it will help you.
https://vaadin.com/tutorials/calling-java-from-javascript
There are some concept like java adaptors and javavm to combine javascript and java try them to find it suits your need.
How can pass json values from jsp to javascript as object via ajax?
I can not use global js variables in jsp because this will lead to json content to be visible in page's source
Here is the scenario that I want to achieve:
url of jsp is opened in browser.
Data is being created in scriptlet and coverted to JSON format
json is "sent" to javascript as object
From above scenario, i understand that javascript must initiate the ajax call to jsp.
The issue with this, that jsp's code will be invoked 2 times:
When page is opened in browser - data is prepared
on each ajax call same code will be called again
Constrains: No jquery, no other libs, no servlets, no additional jsps. :(
EDIT:
There is additional problem, I need to pass multiple json objects to javascript.
I wont be able to do it with response.getWriter().write();
I don't think concatenating all json objects and sending is the correct solution.
The parsing of the received object in javascript http.responseText will be overwhelming.
Why do you need ajax here? If you know that you need to populate some things from server onto jsp page you can do that through scriplets itself:
EX
<%# page import="com.mypackage.PersonDAO" %>
<html>
<body>
<table>
<th>Name</th><th>Email</th><th>Contact</th>
<%
List<Person> myList = PersonDAO.getAllPersons();
for(Person person:myList)
{
%>
<tr>
<td><%=person.getName()%></td>
<td><%=person.getEmail()%></td>
<td><%=person.getContact()%></td>
</tr>
<%}%>
</table>
</body>
</html>
This is a very simple example. You can do more complex things using JSTL.. :)
So there is no jquery, no Servlets, no ajax and no extra jsp's :)
UPDATE
Since you want data in your javascript before page loads you can use jQuery's holdReady() method.
$.holdReady( true );
$.get( url, function() {
// Perform something
$.holdReady( false );
});
See but all modern browsers have developer tools like firebug for mozilla, so any ajax call made will be trapped by them. The only way you can secure them is my encrypting them.. which will complicate things for you... IF you can explain the scenario you are trying to implement may be I can come up with it..
I'm pretty new to Java and I apologize in advance if I'm wording this incorrectly. I've got a small code snippet that has multiple opening and closing delimiters because I've got some HTML mixed with JSP. Without the HTML this can be done in just a few lines of code but I need the HTML to render and it leads to almost double the lines of code. I'm wondering if there is a better way to do this as opposed to having so many opening and closing delimiters. I know I can use a templating library but I'm trying to stay away from that and would like if at all possible to do this inside a JSP (not a separate class). Thanks for the help!
<%
try {
List<Page> children = properties.getPath("getChild", "");
%>
<ul>
<%
for (Page children : e) {
if (children != null) {
%>
<li>Show a link</li>
<%
}//end if statement
}//end for loop
%>
<li>Another link goes here</li>
</ul>
<%
} catch (NullPointerException e){
%>
//show some content here
<% } %>
I think that this kind of problem can really be solved by using templating libraries or the included view convention for a framework.
These libraries were created to solve these kinds of problems and to organize the view as a whole. It will not only clear up the clutter in your view, it will also adhere to the MVC pattern.
In struts, for example, we will do something like this:
<s:textfield name="myParameter" />
and this:
<html:link page="/linkoutput.jsp" paramId="id" paramName="name"/>
For more reasons why you should be using templating or frameworks visit this question. As what Dave Newton said:
Attempting to do it all in jsp is precisely the wrong approach.
Hope this clears it up.
Use JSTL instead of all that Java code you have in your JSP. You can read about JSTL here - http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html
Never catch NPE just to catch NPE.
Consider using JSTL http://jstl.java.net/getStarted.html It provides plenty of tags for iteration and so on.
You'd be much better of using something like JSF. Just as JSP, this is also included in Java EE.
I have a web-app running on the App Engine Java SDK 1.7.2. The app has no filter and no servlets besides the defaults for serving static content and JSP.
In a JSP file, I have a single line with something like:
<% request.getRequestDispatcher( "a.html" ).include( request, response ); %>
This is throwing a java.lang.IllegalStateException: "getOutputStream has already been called".
If I change the "a.html" for a dynamic content like "a.jsp", everything works fine. The documentation says a RequestDispatcher should work for dynamic and static content.
OBS: I am still learning Servlets and everything related, but I know there are other ways to achieve what I am doing here - this is just an example, not a real world scenario. I just would like to know if this is the expected behaviour and why. Or is it just a bug?
After googling, I learned that this bug has been around for a long time. Look at
http://www.coderanch.com/t/165116/java-Web-Component-SCWCD/certification/RequestDispatcher-include-throws-IllegalStateException
Strange as it might seem, the following works.
<%#page buffer="none"%>
<%
request.getRequestDispatcher("a.html").include(request,response);
%>
Why on earth you are putting scriplets in JSP, it is a horrible way of making your JSP's maintenance nightmare. Anyways looks like your request is already being sent before you are calling this method.
I need to call from one JSP to another, do some stuff over there..
I am inside the caller jsp, inside his handleReqeust(HttpServletReqeust request)
method I am trying to forward the request to another JSP, to call the other JSP file to his handleRequest(HttpServletReqeust request) off course with the request object
I tried it:
RequestDispatcher dispatcher = request.getRequestDispatcher("/theSecondJspFile.jsp");
if (dispatcher != null)
dispatcher.forward(request, response);
but to make it work I need for it the object response, but I don't have it,
I am sure I missed something basic, but what?
From my question you can see, I don't have solid backround in java, so please correct me, or refer me to good guide if you feel it necessary
Thanks.
-------------------Edit--------------------------------------
I don't need a redirect, I just want to call another JSP file to his handleRequest method
I think it relate to HTML
What I can make out of your question is that you need to redirect to a secondpage.html from firstpage.html with some data. You can use both GET or POST method to send the data.
For the GET method just redirect to secondpage,html?data=value. The data will be available in the HttpRequest parameter in the controller of the secondpage.html where it can be used as required.
For the POST method you would need to post the data (using a form on firstpage.html) to secondpage.html. In the controller of the secondpage.html the data should be available in a similar way as before.
To include another JSP in a jsp :
<jsp:include page="foo.jsp"/>
You can find some reference material here.
I can not be sure, but what I think you are trying to do is to include a jsp page on to your jsp page and use the the objects and other variables declared in the first jsp page in your second.
<%# include file="mypage.jsp" %> should help you do this.
If this is not what you are looking for, please make your question tad bit more clear. some code will help really.
JSPs are supposed to be used to present the final result. JSPs are not supposed to be part of business tasks leading to this result. There you use normal Java classes for, starting with a servlet class. Let the HTTP request (the one which you enter in browser address bar or specify in some HTML link or form) point to the URL of the servlet instead. This way you can write Java code in the servlet the usual way to invoke other Java classes/methods and finally forward the request to a certain JSP file based on the outcome of the result and then just let that JSP present the final result.
To start with servlets, I'd suggest to read our Servlets info page.
I just added empty Iframe, and set his URL when I needed to call him