0

I'm looking to write a request gathered from a simple HTML form to an HTTPRequest object in Java; ultimately, I'm looking to reload a page to print out different data based on the selections the user makes from a form - without relying on a servlet. The Java code portion of the JSP looks something like this:

if (request.getAttribute("month") == "January") {
    getSomeData;
}
else {
    getSomeOtherData;
}

The actual HTML code looks something like this:

<form name="month" method="post">
    <select name="monthField"
        <option value="January">January</option>
        <option value="February">February</option>
    </select>
    <input type="submit" value="Submit">
</form>
SHOWSOMEDATA

I omitted the action field, which reloads the page just fine, but it doesn't seem to be writing to the request; the original code (can't post it - it's for work) has a more complex if/show test, and the page loads with the ("month"==null) case every time, so it obviously isn't posting correctly. What can I do to perform the POST option properly?

rainydaymatt
  • 594
  • 3
  • 10
  • 21

2 Answers2

1

If you are submitting your page then use monthField as field name as that is the name assigned to select input box. Also you need to use equals method to compare the Strings as:

   if ("January".eqauls(request.getParameter("monthField")) {

If you want case insensitive comparison then use equalsIgnoreCase method as:

   if ("January".equalsIgnoreCase(request.getParameter("monthField")) {

If you have set the value in the request using attribute as month, then

   if ("January".eqauls(request.getAttribute("month")) {

or

   if ("January".equalsIgnoreCase(request.getAttribute("month")) {

Please Note: Putting the string literal e.g. "January" as first argument in comparison is preferable to avoind unwanted NullPointerException when request.getAttribute("month") is null.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • Works like a charm! For whatever reason, I've been using Attribute so long that I've stuck with it, despite everyone at work using Parameter. And I should've know better tha to use the form name. :) Thanks! – rainydaymatt Dec 26 '12 at 03:24
-1
  1. You cannot set request attributes from the client, only request parameters.

  2. It looks like your parameter is called monthField in the HTML.

  3. You cannot use == to compare Strings.

So maybe you want

if ("January".equals(request.getParameter("monthField")) {
Thilo
  • 257,207
  • 101
  • 511
  • 656