Servlet Post parameters : what case can a parameter have several values? - java

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

Related

How to show a message in the current JSP page after a submit to a servlet? [duplicate]

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>

Java httpServletRequest Into Arrays

I have a jsp page that calls a JavaScript function to dynamically create content like this:
<input type="text" name="loadLocation1" id="loadLocation1" class="loadLocation />
<input type="text" name="loadMagnitude1" id="loadMagnitude1" class="loadMagnitude / >
<input type="text" name="loadLocation2" id="loadLocation2" class="loadLocation />
<input type="text" name="loadMagnitude2" id="loadMagnitude2" class="loadMagnitude / >
and so on
My goal is to end up with two separate arraysLists containing:
[loadLocation1, loadLocation2, etc.]
[loadMagnitude1, loadMagnitude2, etc.]
Right now I have a servlet that is separating out the data into two different arrays in a rather stupid way:
if(req.getParameter("loadLocation1" ) != null ) {
beam.appendForceDistance( Double.parseDouble(req.getParameter("loadLocation1" )));
beam.appendForce( Double.parseDouble(req.getParameter("loadMagnitude1" )));
if(req.getParameter("loadLocation2" ) != null ) {
beam.appendForceDistance( Double.parseDouble(req.getParameter("loadLocation2" )));
beam.appendForce( Double.parseDouble(req.getParameter("loadMagnitude2" )));
etc.
Which isn't expandable at all. I've looked at the HttpServletRequest documentation, without much luck. I was able to iterate over a map and get the strings of keys and values to print out which wasn't much help since I couldn't separate results by class name.
Also, the getAttribute() looked promising, but when I called it on a request:
req.getAttribute("loadLocation")
it returns null.
Is there any way to separate the two types of data based on class into two different arrays while maintaining the order?
No, this is not possible.
When the form is submitted only the form elements with the "name" attribute will be submitted.
The order will remain exactly the same so that part is solved.
What I would suggest is to create the Object with javascript and post that with ajax.
// One Load object
function Load(args) {
this.kind = args.kind || null; // Location or Magnitude
this.value = args.value || null;
this.clazz = args.clazz || null;
}
var arr = new Array();
var loads = document.getElementsByName('load');
for (var i=0; i< loads.length; i++) {
arr[i] = new Load({
kind: loads[i].id,
value: loads[i].value.
clazz: loads[i].getAttribute('class').
});
}
Use JQuery to post this:
$.postJSON(getHost() + "save/load",arr, function(data) {
});
And your jsp looks like this
<input type="text" name="load" class="loadLocation />
<input type="text" name="load" class="loadMagnitude / >
<input type="text" name="load" class="loadLocation />
<input type="text" name="load" class="loadMagnitude / >
The code is not tested or perfect but you get the idea I hope.

Using an if statement to send result back to jsp

I want a way where the user enters details through a series of radio buttons. A java class then does some work by looking at the responses and returning a score to the user based on the responses (i.e. a different response can give different feedback). ive written the code for the jsps and now need some way it can link to the java class containing the if statement, go through the if statement and then return the result.
the first jsp where the radio buttons are selected
<form:form action="/HelloSpring/questionTwo" method="post">
<p> What is the correct wrapper class for the primitive int? </p>
<input type="radio" name="radios1" value="Int" path="types" >Int<br>
<input type="radio" name="radios1" value="Enum" path="types">Enum<br>
<input type="radio" name="radios1" value="integer" path="types" >integer<br>
<input type="radio" name="radios1" value="Integer" path="types" >Integer<br>
<input type="submit" value="Next" >
</form:form >
the controller where it should read results and then perform if statement
#RequestMapping(value = "/results", method = RequestMethod.POST)
public String results(Model model, HttpServletRequest request,
HttpServletResponse response){
String radio = (String)request.getParameter("radios1");
request.setAttribute("total", total);
// model.addAttribute("total", total);
if (radio.equals("Int")){
total = total + 0;
}
else if (radio.equals("Enum")){
total = total + 0;
}
else if (radio.equals("integer")){
total = total + 0;
}
else if (radio.equals("Integer")){
total = total + 1;
}
else{
total = total + 0;
}
System.out.println(radio);
return "results";
}
the jsp that should post what result they get. The session.getAttribute bit works just not ${total}
<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose <%= session.getAttribute("q1") %> </p>
<p>For question 2 you chose <%= session.getAttribute("q2") %> </p>
<p>For question 3 you chose <%= session.getAttribute("q3") %> </p>
<p>For question 4 you chose <%= session.getAttribute("q4") %> </p>
<section>
<p>Total score: ${total} /4</p>
Submit the form to a controller, call the if statement and put the result in a ModelAndView, that your controller returns.
#RequestMapping(value = "/results", method = RequestMethod.POST)
public ModelAndView results(Model model, HttpServletRequest request, HttpServletResponse response){
ModelAndView mav = new ModelAndView();
// set name of next view ...
mav.setViewName("results");
// handle if...
// add results to next view ...
mav.addObject("anyNameYouWant", yourObject);
return mav;
}

Why does jsp request.getParameter(“String”) return null after the first call?

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%>")'>

get and send data in String[] Array using servlet

int i = 0;
String[] pnumbers = new String[3];
String[] pqtys = new String[3];
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String pnumber = request.getParameter("pnumber");
DAO dao = new DAO();
Product p = dao.checkProduct(pnumber);
String qunty = request.getParameter("pqty");
while (i < 3) {
pnumbers[i] = p.getNumber();
pqtys[i] = p.getQty();
i++;
}
request.setAttribute("pnum" pnumbers);
}
I need to add 3 items coming by webpage in to this array. but ones you can add one item
<td>
<input type="text" name="pnumber" value="" />
</td>
<td>
<input type="text" name="pqty" value="" />
</td>
i need to add only 3 items to array after adding those 3 i need to get that values again to same page please help?
Once you set attribute in you Servlet like you have done.
request.setAttribute("pnum" pnumbers);
Forward control from Servlet to required JSP and You can access it in your JSP using
request.getAttribute(paramName)
Hint:
if(request.getAttribute("pnum")!=null){
String []strArray = (String []) request.getAttribute("pnum");
for(int i=0;i<strArray.length;i++){
out.println(strArray[i]);
}
}
Print the values at your required point.

Categories