I'm doing a project using jsp pages and servlets.
In my servlet I need to identify which jsp page is doing the request.
How can I do this?
The simplest way to identify the form from which the request come from would be to add a hidden field containing a form identifier. But this is a very uncommon requirement: if you post to same URL, it normally means that the origine of the post does not matter. If it matters (why?), the difference should be in posted data (hence the proposal of a hidden field), or you should post to different URLs. Servlet are not so expensive that you need to limit their number.
I have found a solution.
I set a name to the submit button.
<input type="submit" name="button" value="button1">
and then in the servlet I check with
String r = request.getParameter("button");
Doing that I know from where the request came from
For your servlet, i suppose you are using doGet/doPost to handle request and return response, then in your request from jsp, you can always add a hidden input field to let your servlet know which jsp you come from as follow:
In your jsp:
add a new hidden input textfield:
<input type="hidden" name="jspname" value="jspname" />
In your Servlet:
use getparameter method for doPost or getQueryString() for doGet:
in doPost:
String jspname = request.getParameter("jspname");
By making use of the jspname String, you can easily find out which jsp it is using.
Using hidden input is solution in other answers. But you can do that without hidden input.
String referer = new URI(request.getHeader("referer")).getPath();
referer String gives you full URI. Additionally for getting jsp page name you can use java code.
String[] uriNames = referer.split("/");
String jspPageName = uriNames[uriNames.length-1];
Also with regex you can get jsp page name.
Pattern pattern = Pattern.compile("(\\w+)(\\.)(jsp)");
Matcher matcher = pattern.matcher(mydata);
String jspPageName = "";
while(matcher.find()) {
jspPageName = matcher.group();
}
Related
I'm totally new in jsp/servlet and working with an application that I have many jsp pages and servlet.
In the first jsp page I choose a customer.
<select id ="sel" name="customer">
<option>customer1</option>
<option>customer2</option>
<option>customer3</option>
<option>customer4</option>
</select>
In the second jsp page it shows me the menu related to this customer(for example I choose configuration and goes to the third jsp page )
<% HttpSession session = request.getSession(true);
String chos_cust=request.getParameter("customer");
session.setAttribute("cust_menu",chos_cust); %>
....
<%= session.getAttribute("cust_menu")%>
In the third jsp page I choose cateories related to this customer(there are many categories for each customer)
An sql query runs here to show categories as radio buttons:
<input type="radio" name="chos_gr" value="${groups.group_name}"checked > ${groups.group_name}
In the forth jsp page according to the chosen category it will show subcategories. In this jsp page I have three div
in html form with hidden type.In the first div list of products has been shown , the second div is for adding a product and in the last div products can be deleted.
String config_gr = request.getParameter("chos_gr");
session.setAttribute("config_menu",config_gr);
I have used a servlet to do these operations(add, delete). It works well but when I add or delete a product and use requestDispstcher/forward in servlet to back to the last jsp to see the result(list of products) it
shows null for category and nothing in list of products.
If I should return the value of category in the servlet to the last jsp?
Could someone tell me what the problem is?
I can't add a comment for this post. As #underdog suggested I used ${sessionScope.config_menu} in the last jsp and it still shows null for category. It's weird because I get the customer value when I return to the last jsp to see the result but nothing for category.
You are adding all the object/values in a session attribute. With request dispatcher you forward the flow to a jsp with request & response objects. The request object contains no info of the customer you have set in the session object.
In the jsp try accessing the values from the session scope.
${sessionScope.config_menu} would give you the desired output.
Instead of using a response.sendRedirect(url), consider using following:
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request,response);
Above code with the getRequestDispatcher() will allow you to include your calling servlet's request by using dispatcher.forward, which will include the session attributes you were missing.
[NOTE: OP was already doing the above]
[UPDATE]
Based on the way you were suggesting to code certain parameters in <input type="hidden" name="myfield"> fields, I suspect, you did nothing else to store the values. Which means, the first time around, they might have been set using the parameters from the previous request, but when using the dispatcher.forward, this did not happen.
For fields to be initiated with the appropriate value, they require to be made available either through request parameters (e.g. GET parameters, encoded in the URL), or otherwise set within the JSP itself trough <input type="hidden" value="${whatever}" name="myfield"> or similar code. I am also missing that part of the code to be able to validate.
Using a dispatcher.forward(), you might not have required parameters set.
I am trying to get attribute of spanId and set Attribute by using request. Then I want to pass the output. Although the first input is has value, it still return me null.
Below are my codes. Help will be appreciate! :)
<input id="spanId" name="spanId">
<%
String spanId = request.getParameter("spanId");
request.setAttribute("spanId",spanId);
%>
<%= request.getParameter("spanId") %>">
Use the getAttribute method instead of getParameter() like
<%= request.getAttribute("spanId") %>">
Just think if you are setting an attribute to request object how you can get it? by using getAttribute.... String spanId = request.getAttribute("spanId").
Also request attribute has request scope (scope lasts only till 1 request).
More on this over here http://docs.oracle.com/javaee/1.4/api/javax/servlet/jsp/JspContext.html
Avoid using scripting elements in your JSP.. remember you are tightly coupling your presentation and business logic.
This is probably due to my misunderstanding and incomplete information of JSP and JSTL. I have a web page where I have input elements such as
<input name="elementID" value="${param.elementID}"/>
When I am trying to save the form, I check for that elementID and other elements to conform to certain constraints "numeric, less than XXX". I show an error message if they don't. All the parameters are saved and user does not need to type it again after fixing the error.
After saved, when I am redirecting to the same page for the object to be edited, I am looking a way to set the parameter like request.setParameter("elementID",..) Is there a way to do this ? However the only thing I can find is request.setAttribute.
HTTP responses does not support passing parameters.
JSP/Servelets allows you to either use request.setAttribute or session.setAttribute for that purpose. Both methods are available when processing the page you're redirecting to, So basically, you got it right...
Also, from what you describe, you may want to check client-side validation: don't submit the form until you're validating it using client-side scripting (javascript)
After the servlet processes the form, (ie. saves the user input in the database), have the servlet forward (not redirect, because that would lose the request params) the request to the same jsp which contains the form. So there is no need to set the params since the servlet is just passing back the same request object.
The jsp which contains the form should have inputs similar to this:
<form>
...
<input type="text" value="${elementid}"/>
...
</form>
The syntax ${varname} is EL. So if the elementid already has a value, it that textfield will contain that value. Alternatively if you have not used EL and/or JSTL, you use scriptlets (but that is highly unadvisable, EL and/or JSTL should be the way):
<form>
...
<input type="text" value="<%= request.getParameter("elementid") %>"/>
...
</form>
I had to include <%# page isELIgnored="false"%> to my jsp to allow code like ${elementid} to work
Alright cannot find this anywhere and I was wondering how to grab the values of a text box from a jsp or servlet and display it in another servlet.
Now my issue isn't passing the data and actually displaying it, my issue is that whenever a space is in the value I can only get that first bit of information. For example:
<form method="post" action="Phase1Servlet">
<p>Favorite Place:</p> <input type="text" name="place"></div>
<input id="submit" type="submit" value="Submit">
</form>
Say The user types in "The Mall"
in the Servlet I use:
String place = request.getParameter("place");
Then output the variable place somewhere in my code I only get the word "The"
Do I need to use request.getParameterValues("place"); instead? If so how do I pass the values from servlet to servlet through a hidden field? When I do this:
String [] placeArr = request.getParameterValues("place");
out.println("<input type=\"hidden\" name=\"place\" value="+ placeArr +">");
The hidden field actually stores [Ljava.lang.String;#f61f5c
Do i have to parse this or convert this somehow?
Should be
String placeArr = request.getParameterValue("place");
out.println("<input type=\"hidden\" name=\"place\" value=\""+ placeArr +"\">");
Escape the string in the hidden field
Are you really sure that when you use
String place = request.getParameter("place");
the place variable contains only word before first space? Because it is rather weird situation. If you want to pass a parameter to another servlet(assuming that another servlet is called from this servlet) you can set a request attribute in first servlet and then dispatch that request to another servlet, for example:
request.setAttribute("place", "The mail");
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( path_to_another_servlet );
dispatcher.forward( request, response );
and then in another servlet ypu can use it as:
String place = request.getAttribute("place");
I am pretty new to servlets and web development in general.
So basically I have a servlet that queries a database and returns some values, like a name. What I want is to turn the name into a link that opens a details page for that name (which another servlet would handle). How can I send the name to the other servlet so it can query a database for the relevant details?
Maybe I'm taking the wrong approach?
Edit: I am using Tomcat 5.5
Pass it as request parameter.
Either add it to the query string of the URL of the link to the other servlet which is then available by request.getParameter("name") in the doGet() method.
link
Or add it as a hidden input field in a POST form which submits to the other servlet which is then available by request.getParameter("name") in the doPost() method.
<form action="otherservlet" method="post">
<input type="hidden" name="name" value="${name}" />
<input type="submit" />
</form>
See also:
Servlets info page - contains a Hello World
Not sure if I understand correctly, but you may look at javax.servlet.RequestDispatcher and forward the url to the second servlet.
The url could be created using the name:
http://myhost.mydomain/my.context/servlet2.do?name=John
I would create the URL either in the first servlet or in a client using a configurable template for the URL. This way both servlets are clearly separated - you can even have each one on different machine.