I have a a JSP file in this format(two select tags)-
<%# page import="mypackage.*" %>
<all the main tags>...
<form>
<select> options... </select>
<select> options... </select>
<input type="submit" value="submit" />
</form>
<textarea></textarea>
There is a java method inside "mypackage" which should take arguments from the <select> tags after clicking on submit.
The method returns a string which I want to output in the <textarea>.
How do I go about this ?
Thanks a lot guys.
Send it as HTTP POST or HTTP GET to a servlet, and receive it via doGet() or doPost() methods. You can access it via HttpServletRequest.getParameter().
void doPost(HttpServletRequest request, HttpServletResponse response)
I see that you are importing the mypackage.* classes into your JSP. Indeed, you could include Java code inside your JSP and call the class directly. Something like:
<%
MyClass c = new MyClass();
String result = c.doSomething(request.getParameter("select"));
out.println("<textarea>" + result + "</textarea>");
%>
should be sufficient (but not good: the result should be escaped).
However, this code is not very maintainable and it can be done better (the answer of kaustav datta is one standard way of doing it).
It can be done in a more elegant way using the Spring framework's MVC part: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html
It needs some configuration at the beginning and takes some time to understand, but when you got it, it is very nice.
In your case, a controller of the following form would be sufficient:
#Controller
public class SelectController {
private final class MyClass c = new MyClass();
#RequestMapping(value="/select", method = RequestMethod.POST)
public String doSelect(#RequestParam("selection") final String selection, final ModelMap model) {
final String result = c.doSomething(selection);
modelMap.addAttribute("result", result);
return "yourJsp";
}
}
request.getParameterValues("select")
here getParameterValues is a method of the request interface which returns a string in argument of this method pass name of your controller
when you get value from text box use the method request.getParameter("name");
Related
I have the following code:
<c:forEach var="listValue" items="${upcomingMovieslists}">
div style="border:thin inset #6E6E6E; text-align: justify;> <p margin-left: 1em;"> <c:set var="movieName" scope="application" value="${listValue.key}"/><a href="/myapp/movie/SubmitMovie/" >${listValue.key}</a></p></div>
</c:forEach>
and movieName is going to be in #RequestParam String movieName in the page that it is going next.
So, When I run this code I am getting an error telling:
error:
message Required String parameter 'movieName' is not present
description The request sent by the client was syntactically incorrect.
Controller method:
My controller class to where the call is going:
#RequestMapping(value="/SubmitMovie", method = RequestMethod.GET)
public ModelAndView getSearchedMovie(#RequestParam String movieName, ModelMap model)
The URL currently is: /myapp/movie/SubmitMovie/
It should be /myapp/movie/SubmitMovie/?movieName=deadpool
in order to work
I should have /?movieName= to show the results in the next page but where as with the above jsp code I will not get the movieName in String format instead it comes in the form ${movieName} which cannot be accepted to a String present in the RequestParam and hence it throws an error.
I want to know how I can fix it to get the moviename in Stringformat in the URL so that I can populate the results
Thanks
There's not a whole lot of code there, so I don't know exactly what you're going for, but you can always add a required=false condition to a request parameter, like so:
#RequestParam(value = "movieName", required = false) String movieName
That should at least clear that error. If the logic in your model does require movieName, though, then you're going to need to refactor around that -- i.e., your link would need to look like href="/myapp/movie/SubmitMovie?movieName='${listValue.key}'" .
(Note: I'm inferring from your code that ${listValue.key} is the name of the movie. Whatever variable you want the controller to receive as the #RequestParam String movieName, place it after ?movieName= in the href string, after escaping it with single quotes (see how I did so above.)
If you're still stuck, maybe try showing the controller for the page with that parameter?
I am developing a LinkedIn login hook following this example but I got stuck at passing parameters from my .jsp file to the .java class implementing AutoLogin.
If I write a portlet, the values are sent correctly to a processAction method, however here the same approach is not working.
In my linkedin.jsp file i have the following (simplified) structure.
<%
PortletURL linkedInRegiserURL = renderResponse.createActionURL();
linkedInRegiserURL.setParameter(ActionRequest.ACTION_NAME, "linkedInRegister");
%>
<form id="linkedInForm" action="<%= linkedInRegiserURL.toString() %>" method="post"
name='<portlet:namespace/>linkedInForm'>
<input type="hidden" name='<portlet:namespace/>email' id="email" />
</form>
And then inside a javascript method, based on the LinkedIn API, I populate my input and then submit the form.
document.getElementById('email').value = member.emailAddress;
document.getElementById('linkedInForm').submit();
Everything is fine here. The problems start inside the login() function in my LoginHook implements AutoLogin class. If I do a print test, the following results are shown:
#Override
public String[] login(HttpServletRequest request,
HttpServletResponse response) throws AutoLoginException {
String email1 = ParamUtil.getString(request, "email");
String email2 = request.getParameter("email");
String email3 = request.getAttribute("email").toString();
System.out.println("email1 : " + email1); //empty value
System.out.println("email2 : " + email2); //null
System.out.println("email3 : " + email3); //null
//etc.
}
I guess that the problems start here <form id="linkedInForm" action="<%= linkedInRegiserURL.toString() %>", but I am not sure and I don't know how should I pass my email parameter.
PS: I am working with Liferay 5.2.3, so writing a class extending BaseStrutsPortletAction is out of the question.
Params Inside login hooks in Liferay are a bit tricky, you can try 2 things:
Use the following function to retrive the "real" request wich may contains your parameter (Although I´´m not really sure if it´s available in liferay 5.2.3, in Liferay 6 its works):
PortalUtil.getOriginalServletRequest((javax.servlet.http.HttpServletRequest request)
Try with a GET call , instead a POST.
Another way to do it is to save the email as a cookie( in javascript) and then recover it in the autologin hook.
Hope it do some help...
I'm not very familiar with JSP, so, let's make this question an example:
suppose I have a JSP file (index.jsp) which contain those statement:
<%
MyObject mO = new MyObject();
mO.sayHelloWorld();
%>
and in the MyObject.java:
public class MyObject(){
public void sayHelloWorld(){
//something like getJSPApplicationContext.getOut.println("<p>Hello World</p>");
}
}
is there a simple way to reach this goal (without passing the JSPApplicationContext to my class?)
Maybe I'm doing something really wrong, anyway, thanks for yout help :)
Let me use this opportunity to introduce you to the V (View) in MVC (Model View Controller).
You should generally put data into the view by putting a view bean into the session on your controller. You can think of your class MyObject as a view bean as it contains information you want to display in the view. The controller in this case is your servlet (you do have a servlet, right?) and would contain the following in its doGet or doPost method;
MyObject myObject = new MyObject("Hello world");
request.setAttribute("myObject", myObject);
The next step is to have your JSP display the data from the view bean. You are strongly encouraged to use JSTL for this, rather than by putting code snippets in. The JSTL tag <c:out> can be used for displaying data in a JSP. Your JSP might contain the following;
<p>
<c:out value="${myObject.message}"/>
</p>
This will call the getMessage() method on the session object 'myObject' and output it on the page.
Just for completeness, your MyObject view bean might look like this;
public class MyObject
{
String message;
public MyObject(String message)
{
this.message = message;
}
public String getMessage()
{
return message;
}
}
This isn't how it is used.
For the purpose you have demonstrated.
You should include a Servlet or jsp or static HTML just to print Hello World like
<jsp:include page="/staticfile/helloworld.html" />
in helloworld.html
just
hello world
or include servlet
<jsp:include page="/helloworldServlet" />
and in HelloWorld Servlet doGet()
out.println("hello world");
Also See
how-to-avoid-java-code-in-jsp-files
about jsp
Without passing the context to the class method, and without storing it in a ThreadLocal variable (which I think would be a bad idea), I don't see how you could do that.
If your class needs access to the JSP context it probably means that the class should be a JSP fragment or a custom JSP tag (<custom:sayHello/>).
I'm taking a class on JSP and I have an assignment... we have to write a JSP page that takes user input, validate the input and then forward it to a different web site. To be more precise, we were asked to implement a rudimentary version of the FareFinder functionality of Amtrak's web site.
There are 2 main purposes to this assignment:
(a) to write JSP which performs as middleware;
and (b) to write JSP which validates form data.
I have a general question about the principles of doing the validation. Currently I have a JSP that has a form and a submit button. When the user clicks on the submit button I forward them to Validate.jsp. The Validate.jsp will then validate the data and if the input is OK it will automatically redirect the request to the Amtrak web site with all the parameters filled out.
FareFinder.jsp -> Validate.jsp -> Amtrak
(click on the file name to see all my code in a pastie)
Briefly, the main thing that I'm doing FareFinder.jsp:
<FORM METHOD=POST ACTION="Validate.jsp">
<!-- all the input fields are up here -->
<P><INPUT TYPE=SUBMIT></P>
</FORM>
The main thing I'm doing in Validate.jsp:
<%# page import="java.util.*" import="java.io.*"%>
<%
// retreive all the parameters
String origin = request.getParameter("_origin");
String depmonthyear = request.getParameter("_depmonthyear");
String depday = request.getParameter("_depday");
String dephourmin = request.getParameter("_dephourmin");
String destination = request.getParameter("_destination");
String retmonthyear = request.getParameter("_retmonthyear");
String retday = request.getParameter("_retday");
String rethourmin = request.getParameter("_rethourmin");
String adults = request.getParameter("_adults");
String children = request.getParameter("_children");
String infants = request.getParameter("_infants");
String searchBy = request.getParameter("_searchBy");
// validate the data
// redirect to Amtrak or back to FareFinder.jsp
%>
I have several questions:
How do I return to FareFinder.jsp from Validate.jsp and reflect the errors found in the validation page?
Once I have found errors- do I redirect the response back to FareFinder.jsp?
How could I transmit the error(s) back to FareFinder.jsp?
A generic answer would be fine too, but I'm giving my code as an example.
Note: the validation must be performed on the server side and I can't use javascript.
OK, as per the comments, Servlets are covered as well. Now, create one and implement doPost() like follows (semi pseudo):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String> errors = new HashMap<String, String>();
String origin = request.getParameter("origin");
if (origin does not validate) {
errors.put("origin", "Put error message here.");
}
// Repeat for all parameters.
if (errors.isEmpty()) {
// No errors, redirect to Amtrak.
response.sendRedirect("http://amtrak.com");
} else {
// Put errors in request scope and forward back to JSP.
request.setAttribute("errors", errors);
request.getRequestDispatcher("FareFinder.jsp").forward(request, response);
}
}
Map this servlet in web.xml on an url-pattern of /validateFare so that you can invoke it by http://example.com/context/validateFare.
Now do in JSP something like:
<form action="validateFare" method="post">
<label for="origin">Origin</label>
<input id="origin" name="origin" value="${param.origin}">
<span class="error">${errors.origin}</span>
<!-- Repeat other fields here. -->
</form>
You see that the form action already points to the servlet. The ${param.origin} in input values will retain the submitted value by doing request.getParameter("origin") under the hoods. The ${errors.origin} will show any associated error message by roughly doing pageContext.findAttribute("errors").get("origin").
This must get you started :) Good luck.
I am having a web form(JSP) which submits the data to different application, hosted on different server. After submitting the form data, that application redirect back to same JSP page. Now, I want to save the entered the data. What are the different approaches to retain the submitted data in web form. I would not prefer to store the data in DB or any file.
PS: I would like to retain the submitted form data when request again redirected to same JSP page. Therefore, user need not to re-enter the data. Like, data can be stored in Session or Request etc.
Best what you can do is to submit to your own servlet which in turn fires another request to the external webapplication in the background with little help of java.net.URLConnection. Finally just post back to the result page within the same request, so that you can just access request parameters by EL. There's an implicit EL variable ${param} which gives you access to the request parameters like a Map wherein the parameter name is the key.
So with the following form
<form action="myservlet" method="post">
<input type="text" name="foo">
<input type="text" name="bar">
<input type="submit">
</form>
and roughly the following servlet method
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String foo = request.getParameter("foo");
String bar = request.getParameter("bar");
String url = "http://external.com/someapp";
String charset = "UTF-8";
String query = String.format("foo=%s&bar=%s", URLEncoder.encode(foo, charset), URLEncoder.encode(bar, charset));
URLConnection connection = new URL(url).openConnection();
connection.setUseCaches(false);
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("accept-charset", charset);
connection.setRequestProperty("content-type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), charset)) {
writer.write(query);
}
InputStream result = connection.getInputStream();
// Do something with result here? Check if it returned OK response?
// Now forward to the JSP.
request.getRequestDispatcher("result.jsp").forward(request, response);
}
you should be able to access the input in result.jsp as follows
<p>Foo: <c:out value="${param.foo}" /></p>
<p>Bar: <c:out value="${param.bar}" /></p>
Simple as that. No need for jsp:useBean and/or nasty scriptlets.
In JSP this kind of thing is usually handled by using a javabean to store the form values and then using the jsp:useBean tag. For example you would create the following javabean:
package com.mycompany;
public class FormBean {
private String var1;
private String var2;
public void setVar1(String var) { this.var1 = var; }
public String getVar1() { return this.var1; }
public void setVar2(String var) { this.var2 = var; }
public String getVar2() { return this.var2; }
}
In your form jsp you'd use the useBean tag and your form fields values would get their values from the bean:
<jsp:useBean id="formBean" class="com.mycompany.FormBean" scope="session"/>
...
...
<input type="text" name="var1" value="<%=formBean.getVar1()%>" />
In your jsp the form data is posted to (then redirects back) you'd have the following code that would push the posted form data into the bean.
<jsp:useBean id="formBean" class="com.mycompany.FormBean" scope="session"/>
<jsp:setProperty name="formBean" property="*"/>
Another option is to just stuff the form data into the session in your save page:
String var1 = request.getParameter("var1");
String var2 = request.getParameter("var2");
session.setAttribute("var1", val1);
session.setAttribute("var2", val2);
...
and reference it in your form (null checking omitted):
<input type="text" name="var1" value="<%= session.getAttribute("var1") %>" />
If I understand the problem correctly (big "if" there), you have a FORM that has a method of POST and an ACTION that is pointed directly to a remote server. When the user clicks "Submit" the browser isn't involving your host in that transaction, the data is going to the "ACTION" recipient. That would make your options limited to implementing a call back relationship with the remote service (possibly beyond your control), setting up a local proxy servlet to intercept the data and forward the POST along to it's intended recipient (which would make the POST originate from the server and not the client (this could likely cause problems)), or utilize some AJAX design pattern to send the form data to two places instead of just one which the FORM tag dictates.
Beyond that, you would need to have some form of local persistence like a database or a file.
Did I help at all?