开发者

servlets checking params

开发者 https://www.devze.com 2022-12-13 21:05 出处:网络
So I have a big long query string that can either be ... //url=z&surl=y&time=z&codec=a264&acodec=mp3&width=400x100

So I have a big long query string that can either be ...

//url=z&surl=y&time=z&codec=a264&acodec=mp3&width=400x100 or //url=z&surl=y&time=z&optlevel=w

Im us开发者_高级运维ing request.getQueryString("url") to check if a) the qs is there and b) make sure its not null. This is all leading to a big messy set of if statements. I was just wondering if there is a better way to do it.

example..

if(request.getParameter("originalURL") != null &&
        request.getParameter("originalURL").equals("") && ................) 

Thanks guys


Sure, just refactor the duplicated code into methods or make use of an existing framework.

Basic kickoff example of refactored code:

String field1 = getField(request, "field1", true);
String field2 = getField(request, "field2", true);
String field3 = getField(request, "field3", false);

...

public static String getField(HttpServletRequest request, String fieldName, boolean required) throws ValidatorException {
    String fieldValue = request.getParameter(fieldName);
    if (fieldValue == null || fieldValue.trim().isEmpty()) {
        if (required) {
            throw new ValidatorException("Field is required");
        } else {
            fieldValue = null; // Make empty string null so that you don't need to hassle with equals("") afterwards.
        }
    }
    return fieldValue;
}

You can of course go a step further and adopt an existing MVC framework with validation (and conversion) capabilities, such as Sun JSF or Apache Struts.


I don't know if you are using any framework but, as other mentioned, most of them are providing utility classes for this purpose. If you aren't, you should maybe create such a class.

Personally, I like Spring's ServletRequestUtils which exposes several strong typed static methods to get parameters from the request, allowing fallback values and checking for required parameters. If I had to code something equivalent (sigh), I'd mimic this class.


Frameworks such as JSF and Struts offer nicer abstractions for dealing with requests. When I do work with the raw Servlet APIs I use a little utility library to deal with this, and also parsing ints and dates etc.

 getStringParam( request, "originalUrl" ) {}

which would throw an exception if the param is not found, or more often I use a varient that provides a default value if the param is missing:

 getStringParam (request, "origanlUrl", "http://someusefulDefault") {}

 getIntParam(request, "howManyRivers", 93);


if("something".equals(request.getParameter("originalURL")))

No need for null checks, because equals will always return false if you pass a null as atribute

0

精彩评论

暂无评论...
验证码 换一张
取 消