How to send parameters from a servlet - java

I am trying to use a RequestDispatcher to send parameters from a servlet.
Here is my servlet code:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String station = request.getParameter("station");
String insDate = request.getParameter("insDate");
//test line
String test = "/response2.jsp?myStation=5";
RequestDispatcher rd;
if (station.isEmpty()) {
rd = getServletContext().getRequestDispatcher("/response1.jsp");
} else {
rd = getServletContext().getRequestDispatcher(test);
}
rd.forward(request, response);
}
Here is my jsp, with the code to read the value - however it shows null.
<h1>response 2</h1>
<p>
<%=request.getAttribute("myStation") %>
</p>
Thanks for any suggestions.
Greener

In your servlet use request.setAttribute in the following manner
request.setAttribute("myStation", value);
where value happens to be the object you want to read later.
and extract it later in a different servlet/jsp using request.getAttribute as
String value = (String)request.getAttribute("myStation")
or
<%= request.getAttribute("myStation")%>
Do note that the scope of usage of get/setAttribute is limited in nature - attributes are reset between requests. If you intend to store values for longer, you should use the session or application context, or better a database.
Attributes are different from parameters, in that the client never sets attributes. Attributes are more or less used by developers to transfer state from one servlet/JSP to another. So you should use getParameter (there is no setParameter) to extract data from a request, set attributes if needed using setAttribute, forward the request internally using RequestDispatcher and extract the attributes using getAttribute.

Use getParameter(). An attribute is set and read internally within the application.

In your code,
String test = "/response2.jsp?myStation=5";
You are adding myStation=5 as query string.As the query string parameters are stored
as request parameters in Request Object.
Therefore you can use ,
It works fine.Thanks.

Related

How can I get the URL paramter dynamically in Java?

A url is hit from browser now I want to get that url in my dataBean to extract its parameters for some checks.
How can I get that URL dynamically in that particular databean?
for instance :
someone hit
https://someAddress/AjaxForm?id=someid
I need to capture this url and get value of Id. How to do it?
you can do something likewise,
request.getRequestURL() // gives your current URL
where request is an instance of HttpServletRequest.
UPDATED :
If you are trying to find parameter which are comes along with URL, then
rather then do above mentioned my trick,
directly do likewise,
request.getParameter("id");
String url=request.getRequestURL()
String id=request.getParameter("id");
To get the parameter from url
request.getParameter("id");
And to insert it, in javascript add the parameter by attaching it to url
var url=baseurl+"?id="+id;
in the doGET method you write
String idValue=request.getParameter("id");
so the method will look like this
protected void doGET(HTTPServletRequest request,HTTPServletResponse response){
//some code here
String idValue=request.getParameter("id");//idValue will hold the value you passed in URL
//some more code here
}

How would I pass a form value to a servlet

I am fairly new to programming so please bear with me .
I am trying to get values from a form ( in a JSP ) using javascript and do a post request to a servlet . My form has 6 values and I get the values in javascript using
var value 1 = document.getElementByID(" value of a element in the form).value
var value 2 = document.getElementByID(" value of a element in the form).value
etc
my question is I am using a POST request using the javascript Ajax call . How do I combine all these disparate values into a single element which I could then read and assign to a POJO using the POJO'S setter methods in the servlet . I cannot use a JSON because my project cannot use an external library such as Jersey. Any pointers to this would be appreciated .
There are more elegant ways to do this, but this is the most basic. You'll want to combine your javascript variables into a standard post body.
var postData = 'field1=' + value1;
postData += '&field2=' + value2;
postData += '&field3=' + value3;
/* You're concatenating the field names with equals signs
* and the corresponding values, with each key-value pair separated by an ampersand.
*/
If you're using the raw XMLHttpRequest facilities, this variable would be the argument to the send method. If using jQuery, this would be your data element.
In your servlet, you get the values from the HttpServletRequest object provided by the container.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
MyObject pojo = new MyObject();
pojo.setField1(request.getParameter("field1"));
pojo.setField2(request.getParameter("field2"));
pojo.setField3(request.getParameter("field3"));
/* Now your object contains the data from the ajax post.
* This assumes that all the fields of your Java class are Strings.
* If they aren't, you'll need to convert what you pass to the setter.
*/
}

Editing response content on doView()

I have a simple JSR 286 Portlet that displays a user manual (pure HTML code, not JSP).
Actually, my doView method, just contains this :
public class UserManualPortlet extends GenericPortlet
{
#Override
protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException
{
PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher(
"/html/usermanual.html");
rd.include(request, response);
}
}
This works as expected, however I'm having trouble when including images. I'm aware that the path to images should be something like :
<img src='<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/html/image.jpg")%>'/>
However, my HTML file containing the user manual is used elsewhere, so I would like to preserve it as a pure HTML file.
Is there a way to dynamically replace my classic images urls by something like the example above ? Perhaps using the PrintWriter of the response ?
If such thing is not possible, I thing I would need to generate a JSP file during my Maven build.
Any solution or ideas are welcome.
With JSR-268 portlets you have a better way of referencing resources: create ResourceURL using renderResponse.createResourceURL() and then you set the resourceID in the ResourceURL. That should give more consistent results across all portlet containers.
That said, if you want to modify the generated content from your usermanual.html but you don't want to convert it to a JSP then, instead of using a request dispatcher, I would load the file contents on my own, parse it at the same time that I do the URL replacements and then print all the contents to the portlet's response.

How should I send the response in Servlet to Front end?

I have written a Servlet something like this
public class ServletUtil extends HttpServlet {
private static final long serialVersionUID = 1571172240732862415L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String acInfo = request.getQueryString();
someDao dao = new someDao();
ArrayList<String> resultAutoComplete=dao.someResults(acInfo);
out.close();
}
}
I have an auto complete Object/wizard in front end and as the user types in it is making Ajax call to back end to grab the list of results. So I have written a Servlet and I am pulling the user input and getting my results from DAO layer.
My question here is how should I send this list(resultAutoComplete) to Front end in the Servlet?
I'd expect you to serialise this in some fashion such that the client understands it. e.g. perhaps using JSON or similar.
I note that your response content type is text/html. So why not simply write each element of your list to your Writer out, separated by (say) a <li> element (with the appropriate unordered/order list entities surrounding this)
Try this,
for (String str : resultAutoComplete)
{
out.println(str);
}
By serializing it to a String and writing it to out...
Seriously though, I wouldn't code at the low level Servlet spec. For this kind of return-this-pojo call I would use Spring 3's RESTful service libraries, or something similar.
No json! instead of going through a list in javascript, return a completed <li> lists and replace innerHTML of <ul>.The reason to do so is to give a better performance. Unless you want to do something more flexible, leave things to the back-end.
When do json, you gotta parse string into json object and then loop through and generate html, that's just an extra step. Keep things simple, plus, parsing string could be costly.
If you don't loop through the list and instead do out.println the list object, you would likely see the address. also, you need to generate html, so:
StringBuilder sb = new StringBuilder();
for(String option: options){
sb.append("<li>").append(option).append("</li>");
}
out.println(sb);

REST request to JAVA Servlet

I have some JavaScript which I want to perform a REST Request (GET) to my servlet.
The format of the record I want to send is in the following format ...
/id1/vara/varb/varc/timedelta1,timedelta2,timedelta3,....,timedeltaN/
So basically there would be 5 attributes in each record I send. I need to batch these up - I'm sending multiple records in a single GET Request. My Get URL might look a little like the following.
myservletname/id1/vara/varb/varc/timedelta1,timedelta2,timedelta3/id2/vara/varb/varc/timedelta1,timedelta2,timedelta3/id3/vara/varb/varc/timedelta1,timedelta2,timedelta3/
I'm aware on the limit of around 2000 chars in the URL String so to keep things safe I'll ensure the length of the URL is less than this.
In the above example 3 records were sent to the servlet.
I'm wondering how I might process these on the server end. Havent really worked with REST before in Java. What do I need to do on the server end to process these URLs to extract the data ?
Thanks
Basically
public class RestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getPathInfo();
Pattern p = Pattern.compile(
"/([^/]+)/([^/]+)/([^/]+)/([^/]+)/(\d+)(?:,(\d+))*/"
);
Matcher m = p.matcher(uri);
if (m.matches()) {
String id = m.group(1);
String vara = m.group(2);
String varb = m.group(3);
String deltas = m.group(4);
// etc
}
}
}
It's not a very good model for how to do it, but it is simple and understandable for someone not familiar with Servlets
You can use JAX-RS or Restlets instead of a servlet
You should seriously consider using POST instead of GET for this. REST (and URLs) weren't designed for this purpose.

Categories