A Coder Gamer
A Coder Gamer

Reputation: 840

Reading parameter from the request in Servlet

I want to read a parameter from the HttpServletRequest and check to see if it matches certain conditions. So the three conditions are

  1. The value of the parameter can contain only alphanumerics (ASCII characters only), underscores, and dashes
  2. It cannot begin with the dash.
  3. It can be up to 200 characters long.

So I have written the following code to check if it matches the above conditions.

String tempParameter = request.getParameter("X");
if (tempParameter.matches("^[\\u0000-\\u007F]*$") 
    && tempParameter.length() <= 200        
    && !(tempParameter.substring(0, 1)).equals("-")) {
      A = tempParameter;
    }

So I run the servlet and pass the value of “X” as “-sample” in the request, variable “A” is null (which looks correct). Then I pass the value of “X” as “sample” in the request, variable “A” is assigned “sample” (still correct). But again if I change the value of “X” to “-sample”, variable “A” gets assigned “sample” (which shouldn’t happen). Dash seems to be ignored in the request. May I know what is the problem with my code here? Sorry if I’m missing something obvious. Thank you.

Update: The code seems to run fine if I restart the web app but it ignores the Dash after any request comes without a Dash.

Upvotes: 0

Views: 347

Answers (1)

Rohit Shedage
Rohit Shedage

Reputation: 25860

Where you have declared A ?

It seems code is correct but your variable is holding past result.

Try setting A = null in else block

Upvotes: 3

Related Questions