I have a simple case of calling a servlet with query parameters on a button click. The issue is, in the servlet when I try to read the query parameters, I am getting null.
This is my jsp code snippet.
<form action="http://localhost:8080/ChartsApp/apps/CreateXMLServlet?r=0.7180008697323501&fc=03&fc=04&fc=05">
<input type="submit" title="Submit"/>
</form>
This is my servlet code snippet in the doPost
System.out.println(request.getQueryString());
String[] selectedCodes = (String[]) request.getParameterValues("fc");
if (selectedCodes != null) {
for (int i = 0; i < selectedCodes.length; i++) {
System.out.println("fc[" + i + "] = " + selectedCodes[i]);
}
}
The first sout is printing null, and I am getting nullpointer exception in the subsequent lines. What am I doing wrong?
Add the "post" method in form tag to access the request parameters.
<form method="post" action="http://localhost:8080/ChartsApp/apps/CreateXMLServlet?r=0.7180008697323501&fc=03&fc=04&fc=05">
<input type="submit" title="Submit"/>
Related
I am able to display a table when a user clicks a search button. But now I want to split the table into chunks of 20 rows where the user can click next or previous to go forward and backward through all of the data. I am not allowed to use JavaScript for this assignment. Only JSP, Java, HTML.
The two debugging out.print() calls are not showing up. A different page is being loaded after one of the buttons is clicked, but the two debugging out.print calls are not displaying any HTML. I have checked out How to know which button is clicked on jsp this post but had no luck.
<form method="GET">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
try {
if ("Previous".equals(val1)) { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if ("Next".equals(val2)) { // Get next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
I also have a follow up question. If the user clicks next or previous button, will my current table on the page be overwritten by the new one? That is my intent but I don't know if it will work that way.
I WAS ABLE TO FIX IT BY DOING THIS:
<form method="POST">
<center>
<input type="submit" name="previous_table" value="Previous" />
<input type="submit" name="next_table" value="Next" />
</center>
</form>
</br>
<%
String val1 = request.getParameter("previous_table");
String val2 = request.getParameter("next_table");
you should add name with value for button after that you can get by parameter click value.
`<input type="hidden" name="myprevious" value="previous"/>
<input type="hidden" name="mynext" value="next" />
<%
String val1 = request.getParameter("myprevious");
String val2 = request.getParameter("mynext");
try {
if (val1 == "previous") { // Get previous results
out.println("<h1>HELLO 1</h1>");
buildTable(rs, out, false);
}
else if (val2 == "next") { // Go next results
out.println("<h1>HELLO 2</h1>");
buildTable(rs, out, true);
}
} catch(Exception e) {
out.print("<center><h1>"+e.toString()+"</h1></center>");
}
%>
`
I hope it will help you.
Thanks.
Try to use the subList() method of a List<>().
As explained here.
HOW TO IMPLEMENT IT ##
you can put an hidden input in your form to give you the last index for your list like :
<input type="hiden" value="${last_index_of_your_list + 1}" name="index">
Then in your servlet part you put like this :
int index = Interger.ParseInt(request.getParameter("index"));
if(index <= 0){
datalist = datalist(0, 19>datalist.size()? datalist.size() : 19);
}else{
if(clicked_on_next){
datalist = datalist(index, index+19>datalist.size()? datalist.size() : index+19 );
}else{
datalist = datalist(index - 40, index-20>datalist.size()? datalist.size() : index-20 );
}
}
You are using hidden fields but you need to use submit button for next and previous.
<input type="submit" name="myprevious" value="previous"/>
<input type="submit" name="mynext" value="next" />
Make sure both are define in form. when we submit form after that you will get button value in parameter.same my previous answer. because we can not get parameter value without submit form.
Thanks.
This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 4 years ago.
I have an Jsp page that has the ID text field which takes the input from the user and that input is read in a servlet. I am also validating that input in servlet. If user enters an wrong input I need to give a text message like wrong input below that ID field only in the Jsp.
Here is the servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
services2 reporteeservice = new services2();
services3 jiraservice = new services3();
service4 empid = new service4();
String id = request.getParameter("ManagerId");
int Number = 1;
PrintWriter out1=response.getWriter();
String n = ".*[0-9].*";
String a = ".*[a-z].*";
String c = ".*[A-Z].*";
if( id.matches(n) && id.matches(a) || id.matches(c))
{
out1.println("valid input");
try {
//s.getList(id);
....
}
else
{
out1.println("not a valid input");
}
But if I give else part as above, it will redirect me to next page and prints not a valid upon giving the wrong input. But, I want that to be displayed in the same page under the ID field in the Jsp.
My JSP page:
<form name = "reportees" method = "GET" action="reportsto">
<center>
<h1><font size="20"> Enter the ID to get the Reportees</font></h1>
<label><font size="+2">ID</font></label>
<input name="ManagerId" ype="text" style="font-size:16pt"/>
<input type="submit" value="submit"/>
<button type="reset" value="Reset">cancel</button>
</center>
</form>
See if this helps you.
<script>
function validateForm() {
var mid = document.getElementById("ManagerId").value;
// If manager id is empty
if(mid===""){
alert("Please enter valid manager id.");
return false;
}
}
</script>
<form name = "reportees" method = "GET" onsubmit="return validateForm()" action="reportsto">
<center>
<h1><font size="20"> Enter the ID to get the Reportees</font></h1>
<label><font size="+2">ID</font></label>
<input name="ManagerId" id="ManagerId" ype="text" style="font-size:16pt"/>
<input type="submit" value="submit"/>
<button type="reset" value="Reset">cancel</button>
</center>
</form>
I have an int variable in that gets passed into a jsp file from a java class. I now want to pass this int value from the jsp to a javascript file I have. I am stuck with a coming up with a solution. I have tried the following but still does not work:
javascript:
jQuery(document).ready(function() {
jQuery('div.awsmp-hero-featureSwap').each(function() {
jQuery(this).find('div.hero-featureSwap').each(function() {
var width = 0;
var height = 0;
var count = 1;
var perpage = "${products_per_page}"; // ***** this is the value I want from the jsp*****
var totalcarousel = jQuery('.hero').length;
jQuery(this).find('div').each(function() {
width += jQuery(this).width();
count = count + 1;
if (jQuery(this).height() > height) {
height = jQuery(this).height();
}
});
jQuery(this).width(((width / count) * perpage + 1) + (perpage * 12) + 60 + 'px');
jQuery(this).height(height + 'px');
});
});
JSP:
<c:set var="products_per_page" value="3" />
<c:if test="${not null model.listSize}">
<c:set var="products_per_page" value="${model.listSize}" />
</c:if>
I just want to pass the the "products_per_page" value to the javascript. should be very simple...
you can put your <c:set> block into an HTML element as its value then get the value easily using Javascript or jQuery
example :
<input id="ppp" type="text" value="<c:set var='products_per_page' value='3' />"/>
js:
var products_per_page = document.getElementById("ppp").value;
You can use this, is not very recommendable.... but works..
Hard-coding the value into the html file like this:
<body>
.....
var x = <%= some_value %>;
.....
</body>
I passed the request argument to my onclick handler in js the following way:
<s:submit name="kurierButton" onclick="openKurierWindow('%{#attr.OUTBOUND_KURIER_URL}');" value="%{#attr.OUTBOUND_KURIER}"/>
Try doing it this way->
servlet_file.java
HttpSession session = request.getSession();
session.setAttribute("idList", idList);
.jsp file
<%
HttpSession session1 = request.getSession();
ArrayList<Integer> idList = (ArrayList<Integer>) session1.getAttribute("idList");
%>
.js file
alert("${idList}");
If I run my web project, in the first call I get the right Parameter (request.getParamter(userid)),
but if I do more then one call, the request.getParamter Method always returns null.
I don't know why, and I have tried many things.
Thank you for your help.
in jsp I have this:
function addPersonToDatabase(userID){
var check = 0;
for (var zaehler = 0; zaehler < (document.getElementsByName("notinProject[]").length);
zaehler++) {
if (document.getElementsByName("notinProject[]")[zaehler].checked) {
location.href='<%=request.getContextPath()%>/administration/persons
action=addfrompersons&comingfrom=' + location.href + '&username=' + userID;
check++;
}
}
<form name='setcheckbox' id='setcheckbox' action='PersonControllerServlet' method='post' >
<input type="checkbox" name="notinProject[]" value="" onclick='javascript:addPersonToDatabase("
<%=lobjPerson.userName%)'><br> </td>
in servlet I have this:
String lstrUserName=request.getParameter("username");
try:
onclick='javascript:addPersonToDatabase("<%=lobjPerson.userName%>")'>
Here is the a function on my servlet to test various things (I'm new to servlets althought I understadn the logic)
public void testParameters(HttpServletRequest request, HttpServletResponse response) throws IOException{
PrintWriter out = response.getWriter();
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.println("\n>>>" + paramName);
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0){
out.print("No Value");
}else{
out.print(paramValue);
}
} else {
System.out.println("Number of parameters "+paramValues.length);
for(int i=0; i<paramValues.length; i++) {
out.print("" + paramValues[i]);
}
}
}
}
(this code I took from a tutorial and tweeked so it might just be something stupid)
I get everything working just fine but I was wandering in what cases does a parameter have several values?
Example: http://myhost/path?a=b&a=c&a=d
The parameter a has values b, c and d.
Example:
<form name="checkform" method="post" action="xxxxx">
Which langauge do you want to learn:<br>
<input type="checkbox" name="langtype" value="JSP">JSP
<input type="checkbox" name="langtype" value="PHP">PHP
<input type="checkbox" name="langtype" value="PERL">PERL
<input type="submit" name="b1" value="submit">
</form>
The form can allow you to select multiple values. If you ticks all check boxes , then the parameter langtype will have the values JSP , PHP and PERL