Java如何检查servlet请求中是否存在参数?
ServletRequest或HttpServletRequest对象具有用于映射参数名称及其值的映射对象。通过访问此映射,我们可以检查servlet请求中是否传递了参数。让我们看下面的例子。
package org.nhooo.example.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class ParameterCheck extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //检查用户名参数是否存在 if (req.getParameterMap().containsKey("username")) { String username = req.getParameter("username"); } //检查密码参数是否存在 if (req.getParameterMap().containsKey("password")) { String password = req.getParameter("password"); } } }