JAVA - How to check if a request parameter is present in url or not?

Hi there

suppose I am getting call to my webpage from different server side scripts which contain different request parameters.
how can I check that a particular parameter is present in request or not
2)How to check if it is present is null or not?

Thanks

1 Like

You would check the location object to see if your particular parameter is there.
A handy one that I’ve been using for a while now is this getUrlParam function:

function getUrlParam(name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return (results && results[1]) || undefined;
}

With the above function you would use:

var particular = getUrlParam('particular');
if (particular) {
    // do stuff here with particular
} else {
    // particular wasn't found
}

Can you give an example querystring that differs from how the first example would be handled?

@Paul_Wilkins
Suppose I am receiving an class Object from my persistance database.Their might be case that I pass wrong id so in that case null value will be return from database(I am not sure but i think so).

So in that case I want to show some custom message like “Id not present in database”.

Here is something that I have try so far

this is my web page

   <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
   <%@ include file="/jsp/include.jsp" %>
   <%@page import="formdemo.model.Address" %>
   <%@page import="formdemo.model.HighSchool" %>
   <%@page import="formdemo.model.InterSchool" %>
   <%@page import="formdemo.model.Mobile" %>
   <%@page import="formdemo.model.PastEmployment" %>
   <%@page import="formdemo.model.Person" %>
   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Search </title>
  <link href="<c:url value="/resources/css/jquery-ui.css" />" rel="stylesheet">
  <link href="<c:url value="/resources/css/mainfile.css" />" rel="stylesheet">
  <script src="<c:url value="/resources/js/jquery.js" />"></script>
 <script src="<c:url value="/resources/js/jquery-ui.js" />"></script>
 <script src="<c:url value="/resources/js/jquery.validate.js" />"></script>
<script src="<c:url value="/resources/js/registration.js" />"></script>
<script type="text/javascript">
 $(document).ready(function(){
 function getUrlParam(name) {
 var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
 return (results && results[1]) || undefined;
 }

 var status=getUrlParam('person');
 if(status){
 var id='${person.id}';
 var firstname='${person.firstname}';
 var lastname='${person.lastname}';
 $("#userlastname").val(lastname);
 var dob='${person.dob}';
  var joindate='${person.joindate}';
  var email='${person.email}';
  var params={"userid":id,"firstname":firstname,"lastname":lastname,
 "dob":dob,"joindate":joindate,"email":email};
  for (labelId in params){
   if (!params.hasOwnProperty(labelId)){ continue; }
  $('#'+labelId).val(params[labelId]);
  } 
  }
  else{
  $("#userid").val("Id do not exists");
   }
   });
   </script>
   </head>
   <body>
   <div id="page-wrap">
   <ul class="dropdown">
   <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/registration.jsp">Add Employee</a></li>
   <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/searchemployee.jsp">Search Employee</a></li>
   <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/deleteemployee.jsp">Delete Employee</a></li>
   <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/updateemployee.jsp">Update Employee</a></li>
   </ul>
  </div>
  <div id="main_container">
  <br>
  <br>
  <form action="http://localhost:8080/WebFormSpringHibernate/search" method="get">
  <label style="font-size: 20px; margin-left: 40px;">Id</label><input type="text" id="userid" name="userid"/><br>
  First_Name<input type="text" style="margin-left: 53px;" name="firstname" id="firstname"><br>
  Last_Name<input type="text" style="margin-left: 53px;" name="lastname" id="lastname"><br>
  DOB<input type="text" style="margin-left: 92px;" name="dob" id="dob"><br>
  Joining Date<input type="text" style="margin-left: 55px;" name="joindate" id="joindate"/><br>
  Email<input type="text" style="margin-left: 93px;" name="email" id="email"/><br>
 <input type="submit" value="Submit"/>
 </form>
 <div id="main_block"></div>
 </div>
</body>
</html>

this is always giving output like this

In that case, the querystring will just have no content, for example:

content.html?id=&page=4

With no value, the id will result in an empty string which is a case that you can easily check for.

var id = getUrlParam('id');
if (id > "") {
    // do stuff with the id here
} else {
    // the id was empty
}

I have did something like this

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
 <%@ include file="/jsp/include.jsp" %>
 <%@page import="formdemo.model.Address" %>
 <%@page import="formdemo.model.HighSchool" %>
 <%@page import="formdemo.model.InterSchool" %>
 <%@page import="formdemo.model.Mobile" %>
 <%@page import="formdemo.model.PastEmployment" %>
 <%@page import="formdemo.model.Person" %>
 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>Search </title>
 <link href="<c:url value="/resources/css/jquery-ui.css" />" rel="stylesheet">
 <link href="<c:url value="/resources/css/mainfile.css" />" rel="stylesheet">
 <script src="<c:url value="/resources/js/jquery.js" />"></script>
 <script src="<c:url value="/resources/js/jquery-ui.js" />"></script>
 <script src="<c:url value="/resources/js/jquery.validate.js" />"></script>
 <script src="<c:url value="/resources/js/registration.js" />"></script>
<script type="text/javascript">
$(document).ready(function(){
function getUrlParam(name) {
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return (results && results[1]) || undefined;
}

var status=getUrlParam('person');
if(status>""){
var id='${person.id}';
var firstname='${person.firstname}';
var lastname='${person.lastname}';
$("#userlastname").val(lastname);
var dob='${person.dob}';
var joindate='${person.joindate}';
var email='${person.email}';
 var params={"userid":id,"firstname":firstname,"lastname":lastname,
"dob":dob,"joindate":joindate,"email":email};
for (labelId in params){
if (!params.hasOwnProperty(labelId)){ continue; }
$('#'+labelId).val(params[labelId]);
 } 
 }
 else{
 $("#userid").val("Id do not exists");
  }
  });
  </script>
  </head>
  <body>
  <div id="page-wrap">
  <ul class="dropdown">
  <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/registration.jsp">Add Employee</a></li>
  <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/searchemployee.jsp">Search Employee</a></li>
   <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/deleteemployee.jsp">Delete Employee</a></li>
  <li><a href="http://localhost:8080/WebFormSpringHibernate/jsp/updateemployee.jsp">Update Employee</a></li>
  </ul>
  </div>
  <div id="main_container">
  <br>
  <br>
  <form action="http://localhost:8080/WebFormSpringHibernate/search" method="get">
  <label style="font-size: 20px; margin-left: 40px;">Id</label><input type="text" id="userid" name="userid"/><br>
  First_Name<input type="text" style="margin-left: 53px;" name="firstname" id="firstname"><br>
  Last_Name<input type="text" style="margin-left: 53px;" name="lastname" id="lastname"><br>
  DOB<input type="text" style="margin-left: 92px;" name="dob" id="dob"><br>
  Joining Date<input type="text" style="margin-left: 55px;" name="joindate" id="joindate"/><br>
  Email<input type="text" style="margin-left: 93px;" name="email" id="email"/><br>
  <input type="submit" value="Submit"/>
 </form>
 <div id="main_block"></div>
</div>
</body>
</html>

but its still not working always printing else part id there is person is present

We do not have your development environment and so cannot run the above code.

Can you simplify the example so that it is only HTML, CSS, and JavaScript, with no JSP?

1 Like

can you tell me any online editor or environment like jsfiddle.net where I can pass request parameter before run on any web page

so that I can explain without jsp only with the request parameter I will explain

I think what you may need to do is post the view-source that the JSP file is creating to get a feel for the mark-up and CSS
And then
post the server-side code that is dealing with the submitted form.

It’s hard to pinpoint the problem now, but one step at a time and you’ll get there.

Ok I am using Servlet At Backend for operations this is my code

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    System.out.println("Inside doget() on SearchEmployeee");
    super.init(getServletConfig());
    Person person=new Person();
    RestWebController controller=new RestWebController();
    try{
    person=controller.getEmployee(request.getParameter("userid"),request);
    }
    catch(Exception e){
        e.printStackTrace();
    }
        response.setContentType("plain");
        request.setAttribute("person", person);
        request.setAttribute("username", "kishor");
        request.getRequestDispatcher("/jsp/searchemployee.jsp").forward(request, response);
    System.out.println("Exiting doget() in searchEmployee");
    }


 Front end coding is mostly like a Web form nothing special to JSP

for look and feel I want different message when parameter is present in request url(Null or Some value) or when parameter is not present

So what you’re wanting is something like this?

if (parameter > "") {
    // parameter is present
} else if (parameter === "") {
    // parameter is present but with no value
} else {
    // parameter is not present
}

That can be easily achieved with a small change to the getUrlParam function.

function getUrlParam(name, href) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(href || window.location.href);
    if (results) {
        return results[1];
    }
    return undefined;
}

Strictly speaking, returning undefined is not required, but it’s helpful to have there to make it clear that you haven’t forgotten anything and really do intend to return undefined.

Instead of returning the result when its value is not falsy, we can just return a result if the param is found. When the param is found but has no value, that will result in an empty string being returned instead…

I am busy on some other parts of my project soon I will update my post

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.