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
Related
I have a jsp page having a 'submit' option for input.On clicking it i want to update the value of a table called tbIndividual.What can be the best approach to do it?
On jsp page i have somthing like this :
User Name : <%=rs.getString(2)%>
First Name : <%=rs.getString(4)%>
Last Name : <%=rs.getString(5)%>
Email Id : <%=rs.getString(6)%>
Contact : <%=rs.getString(7)%>
<input type="submit" value="ADD"></input>
And now i want to update the value of status of that particular individual from 'NO' to 'WAIT' state.On click of this submit button.
Is making new servlet for this task a good option or doing the code in jsp a better one ?
If i need to make a new servlet then what will be the code for it on jsp page .?Please help.
If you are trying to learn servlet with this project then you should create a separate servlet where you will perform your business logic (e.g addition of element in Db) and jsp should be kept away from business logic because role of jsp is to render the output not to produce the output.
If this is a project for production purposes, then you should ( IMO you must ) opt some web framework. As framework will reduce your effort, headache and increase productivity.
First of all, there are certain things you need to understand while developing web applications in Java. I have a few recommendations and inputs
Please don't use Scriptlets. Scriptlets are deprecated and they make your code clumsy and the maintainance will be hard. Use JSTL
You need to create a form in your html to have a set of variables to push them to the server on clicking submit button. The form will have an action attribute which contains the URL where the request should be sent
Create a Servlet and map with the action URL and write the doPost method which can receive the form parameters and do the business logic whatever changing the status from NO to WAIT or anything else
Please take a note that you need to have Session variables in order to have the store the data in between requests from the same client. eg browser.
Is making new servlet for this task a good option or doing the code in jsp a better one ?
Writing a new servlet is a good option, than doing the business logic in jsp page. jsp is meant for presentation, just view. They shouldn't be used to perform business logic
If i need to make a new servlet then what will be the code for it on jsp page .?
JSP should just have all the necessary html elements and attributes like form, action attribute etc.. to post the parameters in the request to the action URL. Please note the method attribute of form. You should use HTTP POST method for posting form parameters to the server
Note : Finally, Writing Servlets are also NOT recommended. Instead, you should opt for webframeworks like Spring MVC , Struts etc. Please go through the link to understand about web frameworks answered by #BaluC
Hope this clarifies.
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.
I have a web application in Java that performs title matching.
The Servlet is the controller and in one of the methods of the Servlet, I am comparing two list of titles. The first list is in a HashMap and the second is from a query ResultSet.
What I want to do is to automatically match those with same title and give the user the option to confirm the ones with some similarities (business logic). Basically, I need to get user input and then return at the same point to continue.
I tried JOptionPane dialog box and it didn't work.
Now I am trying to forward to another HTML page to get user input and then return to the Servlet.
Below is the Servlet code:
while (Querylist.next()) {
String title = Querylist.getString(1).trim().toLowerCase();
if (MyMap.containsKey(title))
{
// confirm match
} else
{
//some title2 is like title
request.setAttribute("Title1", title);
request.setAttribute("Title2", title2);
RequestDispatcher view = request.getRequestDispatcher("TitleMatch.jsp");
view.forward(request, response);
ResultMatch= request.getParameter("ResultMatch");
if (ResultMatch.equals("YES"))
{
// confirm match
}
}
}
HTML Page:
<B> <%= request.getAttribute("Title1")%></B>
<B> <%= request.getAttribute("Title2")%></B>
<FORM method="get" action="DataMerge">
<input type = "radio" name="MatchResult" value="YES" /> YES
<input type = "radio" name="MatchResult" value="NO" checked/>NO
<button type = "submit" formaction="DataMerge" > <b>CONFIRM</b>
</FORM>
EDIT: the loop works and I'm having a java.lang.IllegalStateException Exception.
Does anyone can help to figure out how to do that efficiently in plain Java?
I searched all over SO and haven't found something similar. Thanks in advance.
You might want to reconsider your approach as there are number of fundamental problems with the code you have written. For example:
The while loop test it not correct. Assuming that you are using an Iterator then the test should be list.hasNext();
The if test is nested and incorrect. You cannot use the identifier Map as it is the name of the class, you should use the name of the map object.
If the loop worked the view.forward(request, response); would result in an java.lang.IllegalStateException exception, on the second cycle, as its not possible to resend a response.
I suggest that instead of trying to send each title pair one at a time, that you display them all (or some if there are too many) on one JSP with a yes button next to each pair and as the user clicks the yes button an AJAX call is made to another servlet that updates the database (or an array to latter be used to update the database).
There are some good tutorial about using AJAX and JSP here of SOF and in YouTube.
Is it possible to use request.setAttribute on a JSP page and then on HTML Submit get the same request attribute in the Servlet?
No. Unfortunately the Request object is only available until the page finishes loading - once it's complete, you'll lose all values in it unless they've been stored somewhere.
If you want to persist attributes through requests you need to either:
Have a hidden input in your form, such as <input type="hidden" name="myhiddenvalue" value="<%= request.getParameter("value") %>" />. This will then be available in the servlet as a request parameter.
Put it in the session (see request.getSession() - in a JSP this is available as simply session)
I recommend using the Session as it's easier to manage.
The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.
You can do it using pageContext attributes, though:
In the JSP:
<form action="Enter.do">
<button type="SUBMIT" id="btnSubmit" name="btnSubmit">SUBMIT</button>
</form>
<% String s="opportunity";
pageContext.setAttribute("opp", s, PageContext.APPLICATION_SCOPE); %>
In the Servlet (linked to the "Enter.do" url-pattern):
String s=(String) request.getServletContext().getAttribute("opp");
There are other scopes besides APPLICATION_SCOPE like SESSION_SCOPE. APPLICATION_SCOPE is used for ServletContext attributes.
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
Try
request.getSession().setAttribute("SUBFAMILY", subFam);
request.getSession().getAttribute("SUBFAMILY");
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
i think phil is right request option is available till the page load. so if we want to sent value to another page we want to set the in the hidden tag or in side the session if you just need the value only on another page and not more than that then hidden tags are best option if you need that value on more than one page at that time session is the better option than hidden tags.
I need to get the value that a user has entered in a textbox on a JSP. I used JavaScript to obtain the value, but then I need to access that same variable outside the JavaScript later on in the page.
Here's what I have:
<script type="text/javascript">
var sp;
function setPolicy(){
sp = document.getElementById('policy').value;
if(sp != "")
alert("You entered: " + sp)
else
alert("Would you please enter some text?")
}
</script>
the textbox:
input type="text" id='policy' size="15" tabindex = "1" onblur="setPolicy()"
But I need to access the string entered in this "policy" textbox later on in a scriplet to call a function within my session bean. Is there any way I can pass that variable outside the JavaScript? Or is there another way to do this?
Thanks!
JavaScript execution happens at client side and Scriptlet executes at server side. You are trying to combine the two.
You should submit the form to the same page by passing a param which will have the value entered in the textbox. Your scriptlet should check if the param is present or not. First time coming on this jsp the param will not be present, it will be available only when user enter something in textbox.
May not be the best solution as I don't know the whole context.
I'm not sure you have the lifecycle of a jsp down quite yet. By the time that the javascript is running, all the scriptlets have been evaluated.
By this I mean, one the JSP is rendered, html and javascript are emitted on the response to the browser, and there is no more server to interpret the JSP.
So, you should think of your problem as how do I communicate back to the server, the result of the user action?
Probably by posting a form to an action on the server.
If you are asking how to get hold of text input value in a java session bean, it has nothing to do with your javascript code.
The session bean is server side code. To pass the input value to your session bean, you need to change server side code, a servlet, strut action, webwork action depending on which web framework you use.