I need to send a particular parameters to Servlet from JSP page. E.g: if I click on the Facebook icon on the web page, then I should send "facebook" as parameter to my Servlet and my Servlet will respond according to the parameter received from JSP file or HTML file.
This is a very open ended question, but the easiest way is to specify parameters in a query string.
If you have the following servlet:
/mysite/messageServlet
Then you can send it parameters using the query string like so:
/mysite/messageServlet?param1=value1¶m2=value2
Within the servlet, you could check your request for parameters using getParameter(name) if you know the name(s), or getParameterNames(). It's a little more involved, specifically with consideration to URL Encoding and statically placing these links, but this will get you started.
String message = request.getParameter("message");
if ("facebook".equals(message))
{
// do something
}
Storing links with multiple parameters in the querystring requires you to encode the URL for HTML because "&" is a reserved HTML entity.
Send Messages
Note that the & is &.
Just wrap the icon in a link with a query string like so
<img src="facebook.png" />
In the doGet() method of the servlet just get and handle it as follows
String name = request.getParameter("name");
if ("facebook".equals(name)) {
// Do your specific thing here.
}
See also:
Servlets info page
One way is to have hidden form variables in your jsp page that get populated on click.
<form action="post" ....>
<input type="hidden" id="hiddenVar" value="">
<a hfref="#" onclick="doSomething();">Facebook</a>
</form>
<script>
function doSomething() {
var hiddenVar= document.getElementById('hiddenVar');
hiddenVar.value = "facebook";
form.submit();
}
</script>
This gives you flexibility to control what gets passed to your servlet dynamically without having to embed urls in your href
Related
I want to perform an action on a JSP if redirected from a specific servlet only else do nothing.Is it possible?
In my JSP there are different errors defined. This JSP calls a servlet (with contentType as application/pdf) which opens in a new tab and searches for a PDF for 25 seconds and then if PDF is not found redirects to same JSP which shows the error message "File not found". I want to show the error if called from servlet only else do nothing.
JSP Code:
<%}else if(hPP!=null && hPP.get("errorcode")!=null && hPP.get("errorcode").toString().equalsIgnoreCase("Issue")){%>
<c:if test="${cameFromServlet}">
<div class="SplInputField">
<label class="FontBlod">Download fail</label>
</div>
</c:if>
servlet code
if (content == null) {
request.setAttribute("cameFromServlet", true);
String redirectJspUrl = request.getParameter("homeRedirect");
String strReceiptPage =
redirectJspUrl.substring(0, redirectJspUrl.lastIndexOf("/")) +
"/GetQReceiptPage";
response.sendRedirect(strReceiptPage);
}
Add an attribute to the request in the servlet like this
httpservletRequest.setAttribute("cameFromServlet", true)
then in your JSP check for it
<c:if test="${cameFromServlet}">
DO STUFF HERE
</c:if>
EDIT:
What you have done in your edit will not work, since you are doing a redirect. Which means the browser is sent a 302 response to tell it to issue another request against the new url. Do you have a specific requirement to change the url for the user? If so you will need to add the cameFromServlet attribute to the session instead - like this:
req.getSession().setAttribute("cameFromServlet", true);
Bare in mind though, that cameFromServlet attribute will remain on the session until you unset it so if there was another time that jsp page is shown you will run into problems unless you do something to unset it - either by introducing another servlet in the middle and moving it from the session to the request - thus simulating Springs flash map behaviour or unset it in the JSP after you have used it - like this:
<c:remove var="cameFromServlet" scope="session" />
If you do not need the URL to change for the user, you can change your servlet code to make use of a request dispatcher (what I thought you were doing)
RequestDispatcher requestDispatcher = req.getRequestDispatcher("/yourjsp.jsp");
requestDispatcher.forward(req, resp);
I have a JSP file in which there are two textareas and a submit button all in a form ;
<form action="" method="post">
<textarea name="inConsole" id="in" cols="100" rows="10"> </textarea> <br/>
<input type="submit" name="Send Command"/> <br/>
<textarea name="outConsole" id="out" cols="100" rows="10"></textarea>
</form>
this page is supposed to work like any SQL program. so the user types a command in the first textarea and clicks submit, then the value of textarea will be extracted to a field and a method will take care of the command and return a log (1 row inserted, error:bad syntax etc) which will be displayed in the second textarea.
I know how for example make a login page and send data and redirect user to a new page(new jsp) file if user pass is correct.
what I can't find is how can I do all the things that I said above without going to a new page while using form action.
I have checked other questions that linked the action attribute to a servlet which was confusing for me( the way that a servlet was called). I'm looking forward to use a simple scriptlet for this purpose like the one I used for my login page:
<%
DatabaseLoginTest dbLogTest = new DatabaseLoginTest();
if (dbLogTest.DBLoginChecker(request.getParameter("user"), request.getParameter("pass")) == true){
%>
<p>Login Successful</p>
<% } else { %>
<p>Login Failed</p>
<% } %>
also I'm aware that adding java scripts(not Javascript scripts:) ) to html isn't a good practice(and the reasons for it) but I think this might be easier for a simple program that I'm working on.
p.s: I'm using tomcat and Intellij for developing this web application
and I have made a custom SQL so I only need the code that gives me the textarea value and the one that sets the other one's value
Update: now I know I should use javascript but I don't know how can I send the data extracted by javascript to a java method.
If you want to do this while remaining in the same page, you have to use Javascript. This is because if you want the server to be able to re-render the page, there has to be a page refresh.
You would need to write onClick handler for the submit button and make a Ajax call to your server to a specific URL with the user input. This URL would serve the data needed for the necessary UI changes.
You can use a scriptlet to generate the HTML that would be shown in the webpage but this would only suffice for a simple use-case and it would be a lot simpler if, say, your service returned just the data required to make the UI change and actual UI change is handled by the JS.
Also,I don't think it is a bad practice to embed JS in HTML. Sure, you can optimize this by including a JS source file but that's a separate optimization.
After submitting a form, calling an action and redirecting to show the jsp, the final url of the browser will show the action with the submit parameters as follows. Is it possible to hide the parameters ?
http://localhost:8080/myproject/login?username=aaa&password=123
Use "redirect" result type to send the redirect to the browser. The parameters should still be in your session/action context.
The comment by #sanbhat is right - use a POST request so that the parameters do not appear in the URL. Using browser dev tools or similar it's still possible to inspect the request and it's post data, there's nothing you can do about that.
In the final redirect to the result JSP, (which presumably shows what the user wrote on the form), then the fields can be populated by saving the results in session scope, so no need to have request parameters on the redirect URL.
i guess you are making a GET call here..
in the submit action make sure you specify method="post" so that password wont appear as parameter
You are using get method. Change it to post method. Example is:
form method="post" name="form name" action="Your action page"
use post method in the form , default is get so u always see the parameters in the url.
<form action="some.jsp" method="post">
I am new to JSP and I am dealing with a confusing issue. I have a JSP form located in a sub folder called "admin" in my web-app (named "CMS").
CMS/admin/display_content.jsp
My form has the following values for action and method attribute
<form action="/deleteContent" method="POST">
/deleteContent is the URL pattern for a servlet named DeleteContentServlet. It simply deletes from the DB the user selections. Anyway, my problem is once I click on submit I notice that I get the incorrect URL in my address bar. Instead of getting
http://localhost:8080/CMS/deleteContent
I get
http://localhost:8080/deleteContent
How can I fix this ? When I have sub folders, are the files only used for imports maybe ?
Thank you.
Use the JSTL <c:url> tag for all your URLs:
it prepends the context path (whatever it is) to absolute URLs
it writes the session ID in the URL in case the browser doesn't accept cookies:
<form action="<c:url value='/deleteContent'/>" method="POST">
For links, it also allows passing parameters to the URL, and encodes them properly (via the <c:param> inner tag).
According to this, you can use request.getContextPath() in your servlet to get the context path. And you need not specify the hostname for the action unless it is different than yours:
<form action="<%= request.getContextPath() %>/deleteContent" method="POST">
Hope that helps...
I'm using netbeans to create a web application that allows a cell phone user to scan a QR code and retrieve a journal's previous/next title information. The take home point is that there's no form that the user will input data into. The QR code will contain the search string at the end of the URL and I want the search to start on page load and output a page with the search results. For now (due to simplicity), my model is simply parsing an XML file of a small sample of MARC records. Oh, to top it off...I'm brand new to programming in java and using netbeans. I have no clue about what javabeans are, or any of the more advance techniques. So, with that background explanation here's my question.
I have created a java class (main method) that parses my xml and retrieves the results correctly. I have an index.jsp with my html in it. Within the index.jsp, I have no problem using get to get the title information from my URL. But I have no clue how I would get those parameters to a servlet that contains my java code. If I manage to get the search string to the servlet, then I have no idea how to send that data back to the index.jsp to display in the browser.
So far every example I've seen has assumed you're getting form data, but I need parameters found, processed and returned on page load...IOW, with no user input.
Thanks for any advice.
Ceci
Just put the necessary preprocessing code in doGet() method of the servlet:
String foo = request.getParameter("foo");
// ...
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
And call the URL of the servlet instead of the JSP one e.g. http://example.com/page?foo=bar instead of http://example.com/page.jsp?foo=bar in combination with a servlet mapping on an URL pattern of /page/*.
You can get the url parameter in servlet using request.getParameter("paramName");
and you can pass the attribute to page from servlet using forwarding request from servlet to jsp.
See Also
Servlet wiki page
Bear in mind that your JSP page will compile internally to a servlet. So you can retrieve the string and print it back in the same JSP. For instance assuming you get the string in a parameter called param you would have something like this in your JSP:
<%
String param = request.getParameter( "param" );
out.println( "String passed in was " + param );
%>
One last thing, you mentioned the main method -- that only gets executed for stand alone applications -- whereas you're talking web/JSP :O