I am fairly new in JSP and I am trying to figure out how to pass data entered in the form on a JSP page to the java class and send this data back to the JSP page on click.
My index.jsp looks a bit like this:
<%# page import="mypackage.*" %>
<% myClass c = new myClass();
c.setString("String"); %>
<p>This is a test: <%= c.getString(); %></p>
The above code will output "String". I can access my class with no problems if I set the value on page load. I tried using servlets after some research. I modified my form to add the servlet "testServlet" on form action:
<form method="POST" action="testServlet">
Then on the doPost() method in testServlet I added in this:
String myString = request.getParameter("myString"); //myString is also the name of my textbox
System.out.println("Entered string: " + myString);
However, I am clearly missing a crucial part of the flow of how this should work and I am most probably wrong with this one as well as all the form does after I press submit is redirect to testServlet so I get the error that the resource is not available since it isn't a JSP/html page.
So my questions are, how exactly can I pass data from JSP to java and vice versa? Also, is there a possible way to do this without servlets? And what are good tutorials/examples for studying JSP and its behavior such as passing data? Please help.
After some more research, I am now able to transfer data set on index to detail using jsp:useBean however, as I've read in all the forums I've visited, servlets should be used to handle this but this really confused me more as a beginner so I really want to figure out what I'm missing here.
I've made sure that the servlet is registered on web.xml and I didn't change anything in there.
Update: I've tried re-creating the project from scratch and somehow managed to make the servlet work. As it turns out, I was missing something on the doGet() method. But now my question stands, is there a way to process the form without using servlets or page import in the JSP file? I was shown a sample code that didn't use servlets or page imports. I did take notice at tag.
use the java beans with getters and setters for there class member variables.
Related
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
I'm making a small web application using servlets and JSPS. (All the code will be shown in screenshots as the code keeps messing up when I try to put it in normally).
This is a snippet of the servlet class:
http://prntscr.com/irm32y
This is a snippet of the output JSP file:
http://prntscr.com/irm40z
And this is a snippet of the form JSP:
http://prntscr.com/irm4d7
For some reason, I'm not allowed to use the "polygon.digits" EL. I can only put numbers in there. (It's to specify how many decimals the user wants the answer to)
I am brand new to all of this, I like servlets and java on a whole so far but I'm having some growing pains.
Servlet Question: Just starting to learn servlets and I'm having an issue with Attributes/Parameters, Sessions and jsp.
Basically, I have a very basic
form. My servlet code states:
println("Hello, " + request.getParameter("name") + "!!!");
..and my .jsp states:
<form action="SimpleServlet" method="POST">
<input type="text" name="name">
<input type="submit"/>
</form>
So now what I need to do is take the last name input into this servlet, save it in session and then send it to a different .jsp that states:
'Hello, '
For example, if I input JIM into the servlet and it returns 'Hello, Jim!!!' in my first .jsp I would then need to click on a link on that page that re-directs me to another .jsp that takes the 'Jim' input and also displays 'Hello, Jim!'.
So I created a 2nd .jsp and have tried many different combinations of code on both to try and get this to work and I keep on getting null or screwing up the output of the first part of the form.
Could someone guide me in the right direction, I would greatly appreciate it.
if you want to show your last name JIM in multiple jsp pages you can use session to store your last name add following code in your servlet.
String name = request.getParameter("name");
HttpSession session=request.getSession();
session.setAttribute("name",name);
then in all your jsp you need to do is put following scriplet where you want to print your name.
<%
String name = request.getSession().getAttribute("name");
out.print(name);
%>
You can do exactly what you want using a single .jsp page, you don't have to create a different one. Just create a link that will POST different parameters to the same .jsp
But as an advice/direction to you, I think the first thing you must understand well is how can you pass and receive parameters and attributes to deal with at server side. Understanding what a request can carry has a huge importance in server-side development.
Just an addon to Mitul's answer
I'd advice you to use EL. It is a simplified approach.
Instead of String name = request.getSession().getAttribute("name"); use
${sessionScope.name} It would give you the desired output.
The best part is that scope resolution is done automatically. So, here name could come from page, or request, or session, or application scopes in that order. If for a particular instance you need to override this because of a name collision you can explicitly specify the scope as
i work on JSP and i want to call a java method(Function) on Click on a html button without using<script></script>.how?
i try to write this code:
<button onclick="<%po.killThread();%>">
<font size="4">Kill</font>
</button>
but it doesn't work... so please help me.
thanks
You're misunderstanding how server-side programming works. When you load that page, the webserver will get to the line <button onclick="<%po.killThread();%>"> and will immediately parse and execute the JSP snippet, in your case po.killThread(), and replace everything between the <% and %> with the return value of that method, if any. And all these happens on server side, before client receives any thing. (Note that this will only happen if that page is not already been loaded and compiled into a Servlet by the server.)
Thus, the HTML that client receives, will be something like, <button onclick="some return value or nothing">, which means that nothing will happen when you press the button. If you want to execute further JSP commands on the button press you will need to make a new request to the server - for example, by redirecting the page.
This will call the function killThread when you open the website.
Try to redirect to another jsp which calls the function.
this will not run at all because after the jsp page is compiled it will return the po.killThread() value but will not call this method
You can see this by viewing the page source
JSP is a server-side technology. Did I say server-side?
In order to understand how JSP works and to clear any misconception, JavaRanch Journal (Vol. 4, No. 2): The Secret Life of JavaServer Pages is a very good read.
An excerpt from the same,
JSP is a templating technology best-suited to the delivery of dynamic text documents in a format that is white-space agnostic.
Template text within a JSP page (which is anything that is not a dynamic element), to include all white-space and line terminators, becomes part of the final document.
All dynamic elements in a JSP are interpreted on the server and once the document is sent to the client, no further dynamic interaction is possible (short of requesting the same or another document).
If you are using JSPs, then to perform some method calles, you will have to write a servlet and then call the method in doPost or doGet method of servlet.
On the other hand, if you want to make things simpler, use JSF framework which will help you achieve your objective as JSF supports event handling.
I've come across a few other questions that describe a similar, but not identical situation, to mine. This question, for instance, shows pretty much the same problem, except that I'm not using portlets - I'm just using boring ol' JSP+JSTL+EL+etc.
I have two application contexts, and I'd like to import a JSP from one to the other. I know how do that:
<c:import context="/" url="/WEB-INF/jsp/foo.jsp"/>
However, I also want to pass a parameter to the imported foo.jsp. But this code:
<c:import context="/" url="/WEB-INF/jsp/foo.jsp">
<c:param name="someAttr" value="someValue"/>
</c:import>
does not seem to properly send the parameter to foo.jsp; if foo.jsp is something like*
<% System.out.println("foo.jsp sees that someAttr is: "
+ pageContext.findAttribute("someAttr")); %>
then this gets printed out:
foo.jsp sees that someAttr is: null
whereas I want to see this:
foo.jsp sees that someAttr is: someValue
so, obviously, someAttr can't be found in foo.jsp.
How do I fix this?
*(yes, I know, scriplets==bad, this is just for debugging this one problem)
You're setting it as a request parameter, so you should also be getting it as request parameter.
Since you seem to dislike scriptlets as well, here's an EL solution:
${param.someAttr}
Note that <c:import> doesn't add any extra advantages above <jsp:include> in this particular case. It's useful whenever you want to import files from a different context or an entirely different domain, but this doesn't seem to be the case now. The following should also just have worked:
<jsp:include page="/WEB-INF/jsp/foo.jsp">
<jsp:param name="someAttr" value="someValue" />
</jsp:include>
This way the included page has access to the same PageContext and HttpServletRequest as the main JSP. This may end up to be more useful.