Java Servlet Validation Confused

北战南征 提交于 2020-01-05 08:16:33

问题


I have noticed some problem when performing server side servlet validation given the form, i need to validate the firstname text field

     <form action="Test" method="POST">
        <input type="text" name="firstname" />
        <input type="submit" value="submit" />
    </form>

Servlet validation code that does not work for me. it always see firstname with length=0 not null

if(request.getParameter("firstname")==null)
    {
        out.println("Error");
    }`

but after modifying the form adding enctype="multipart/form-data" to be

<form action="Test" method="POST" enctype="multipart/form-data" >
        <input type="text" name="firstname" />
        <input type="submit" value="submit" />
    </form>

the validation code works ,,,

the question here is what is the function of enctype="multipart/form-data" ? also why request.getParameter("firstname") doesnot return null for empty field ? it returns empty string


回答1:


if(request.getParameter("firstname")==null)

This checks if the reference of the String points to null, which is not what you want to do I guess. If you want to check for an empty String, do:

if(request.getParameter("firstname")==null 
     || request.getParameter("firstname").isEmpty())

When using enctype="multipart/form-data", all parameters are encoded in the request body. That means that request.getParameter(...) will return null for all posted parameters then.



来源:https://stackoverflow.com/questions/16398374/java-servlet-validation-confused

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!