NPE in MultiSelect option JSP - java

i have written a jsp code which contains mutiple select and when i click on submit i get the null pointer exception . i am using the request.getParametervalues() to fetch the data from multiple select:
jsp code is as follows
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page language="java" import="java.lang.* ,javax.servlet.*,javax.servlet.http.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form id="form1" method="get" name="form">
<select name="color1" id="dd1" multiple>
<option value="empty">Select Color</option>
<option value="RED">red</option>
<option value="BLUE">blue</option>
<option value="GREEN">green</option>
<option value="YELLOW">yellow</option>
<option value="PINK">pink</option>
<option value="BLACK">black</option>
<option value="BROWN">brown</option>
<option value="PURPLE">purple</option>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<%
String [] x = request.getParameterValues("color1");
if(!x.equals(""))
{
for (int i = 0; i < x.length; i++)
out.println (x[i]);
}
%>
i am getting null pointer exception in out.println (x[i]); part
i have also tried if(x ! = null) which is giving error
i have also tried this :
if(request.getParameterValues("color1").equals(null))
{
out.println("abcd");
}
its giving the same exception

Check before doing this in your scriplet
if(request.getParameterValues("color1")!=null){
//Go On
}
As your select is in same .jsp and so on start up load it will give you null for sure.
<select name="color1" id="dd1" multiple>
Moreover you are comparing array with ""
if(!x.equals("")) //No use Check for Not Null
if(x!=null)//Cahange this
If you are using form why not pass request and perform checks and other stuff in Servlet.

Related

Is there any other way to convert string value into integer value in jsp? I am trying a basic program in jsp

index.html
<html>
<head>
<title>AddModule | Home page</title>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 offset-md-3">
<form action="op.jsp">
<div class="card">
<div class="card-header bg-dark text-white">
<h3>Provide me a number</h3>
</div>
<div class="card-body">
<div class="form-group">
<input name="n1" type="number" class="form-control" placeholder="Enter n1">
</div>
<div class=form-group>
<input name="n2" type="number" class="form-control" placeholder="Enter n2">
</div>
</div>
<div class="card-footer text-center">
<button type="submit" class="btn btn-primary">Divide</button>
</div>
</div>
</div>
</form>
</div>
</div>
</body>
</html>
Getting an exception in op.jsp named java.lang.NumberFormatException
HTTP Status 500-Internal Server Error
op.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Jsp Page</title>
</head>
<body>
<%
String n1= request.getParameter("n1");
String n2= request.getParameter("n2");
int a=Integer.parseInt(n1);
int b=Integer.parseInt(n2);
int c=a/b;
%>
<h3>Result is <%=c %></h3>
</body>
</html>
While converting value from string to integer it is generating an exception
Also Tried below code but still not working
<%int n1=Integer.parseInt(request.getParameter("n1"));
int n2=Integer.parseInt(request.getParameter("n1"));
int c=n1/n2 %>
The problem is not with your code, but rather how you run it.
You need to access index.html first to allow you to input numbers, then hit Divide. This will invoke op.jsp with n1 and n2 as parameters.
If you try to access op.jsp directly, your code will run without values for n1 and n2. If you don't have input, then trying to parse input as integers will obviously fail.
If you want to simplify testing, you can manually specify HTTP GET query parameters in the URL using op.jsp?n1=42&n2=7
<%
String n1 = request.getParameter("n1");
String n2 = request.getParameter("n2");
int n1Val,n2Val;
if(n1 != null){
n1Val=Integer.parseInt(n1);
}
if(n2!=null){
n2Val=Integer.parseInt(n2);
}int c;
if(n1 != null && n2!=null)c=n1Val + n2val;
%>

Embedding JavaScript code in JSP won't call the JS function

Given the following code :
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<script>
function verifyEmptyString()
{
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
return !(username == null || username == "" || password == null || password == "");
}
</script>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form id="loginForm" action="loginPage" onsubmit="verifyEmptyString()" >
<p style="font-size:15px"> <span style="color:red;font-weight:bold;">*</span> Username: <input type="text" name="username"><br> </p>
<p style="font-size:15px"><span style="color:red;font-weight:bold;">*</span> Password : <input type="password" name="password"><br> </p>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
I'm trying to call the JS function verifyEmptyString() , but the JSP doesn't call the function.
Any idea what's wrong with the code ?
The function is being called (I added an alert to verify). But you want to return the value of the function in the onclick event:
<form id="loginForm" action="loginPage" onsubmit="return verifyEmptyString(this)" >
Try something like this : http://jsfiddle.net/daguru/RBYnc/1/
var myForm = document.getElementById('loginForm');
myForm.addEventListener("submit", function(ev) {
ev.preventDefault(); // to stop the form from submitting
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
if(!(username == null || username == "" || password == null || password == "")){
this.submit(); // If all the validations succeeded
alert("submiting")
}
});
Here is the solution :
<form onsubmit="return verifyEmptyString(this)" id="loginForm" action="loginPage" >
For anyone who might encounter this problem in the future , you need to change the onsubmit ...
From this :
onsubmit="verifyEmptyString()"
To this :
onsubmit="return verifyEmptyString(this)"
I do not quite understand why we need to pass thisas a parameter to the function, because it is not accepted in the actual function definition function verifyEmptyString() . You are directly referring the form elements inside the function.
On the otherhand, if your code is similar to the below scenario,
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(obj) {
var x = obj["firstname"].value;
alert(x);
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="action.jsp"
onsubmit="return validateForm(this)" method="post">
First name: <input type="text" name="firstname"> <input
type="submit" value="Submit">
</form>
</body>
</html>
In this scenario, we are making use of the passed parameter this.
It refers to the current context, In our case, it is the form whose name is myForm
But in your original scenario, you are directly referring the form inside the javascript function by calling document.forms["loginForm"]["username"].value.

how to add arraylist in Jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=new Date() %>
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<option value="<%=al%>"></option>
</select>
</body>
</html>
This is my code i want to add Arraylist in drop down in Jsp I dont know how to Bind arraylist in html obtion or drop down please help me i have tried Much but unable to do this .
You have to use JSTL <forEach> to iterate through the elements and add it to the select-option . Probably make the List a scoped attribute . Populate the List object in the servlet, set it in request/session scope and forward the request to this JSP. Remember you can populate the List in the JSP itself and use pageScope to refer it , but that will be bad design in my opinion.
<select>
<c:forEach var="element" items="${al}">
<option value="${element}">${element}</option>
</c:forEach>
</select>
Here , al is the name of the attribute which stores the List in probably request or session scope.
Use JSTL in project :
Download the JSTL 1.2 jar .
Declare the taglib in JSP file for the JSTL core taglib.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use just the scriptlets(which is bad off course) :
<%
List<String> al = new ArrayList<String>();
al.add("C");
..........
...........
%>
<select>
<% for(String element: al) { %>
<option value="<%=element%>"><%=element%></option>
<% } %>
</select>
The above code will work if you have defined the List as List<String> , or else you need to cast the element to String.
Read How to avoid Java Code in JSP-Files?.
EDITED
Try this:
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<% for(int i = 0; i < al.size(); i++) {
String option = (String)al.get(i);
%>
<option value="<%= option %>"><%= option %></option>
<% } %>
</select>
</body>
</html>
Take a look at the tag in the core JSTL library.
Store the arraylist in pageScope.myList and loop as follows:
<select>
<c:forEach items="${pageScope.myList}" var="item" varStatus="status">
<option value='${item}'></option>
</c:forEach >
</select>
This is preferable than using scriptlets which are not considered good practice
Try this: declare your arraylist in between <%! … %>
<%! ArrayList al = new ArrayList(); %>

how to display Value On select change in jsp

<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
$("div").text(str);
}).change();
</script>
</body>
</html>
This my code I want to display on console in jsp on Select change passing the value.I want to Print onslected item in Jsp page
<%
String k=request.getParameter("sweets");
out.println(k);
%>
Like this I want to Print on select item data please help me
Enclose select box with-in form tag and in
onchange method of select , trigger form submit
<form id="resultform" action="resultPage.jsp">
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
</form>
In jquery method write
$("select").change(function() {
$('#resultform').submit();
}

How to set default value for drop-down/select in JSP?

I have an arraylist for Strings eqArray.
I need to show it in a drop-down list for which I'm using the following in my JSP:
<%
for(int count=0;count<eqArray.size();count++){ %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%}
%>
I have an eqName String which is part of eqArray and should be the selected value by default.
How do I go about it without having to check and set the first option as eqName always?
<% for(int count=0; count<eqArray.size(); count++){ %>
<option value="<%= eqArray.get(count) %>" <%= (eqArray.get(count).equals("eqName"))?"selected":"" %> ><%= eqArray.get(count) %></option>
<%} %>
Change the index of eqName element to 0 in the array, or use a conditional Statement.
<%
for(int count=0; count < eqArray.size(); count++){ %>
<%if(eqArray.equals("eqName"){ %>
<option selected="selected" value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%} %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%} %>
but use JSTL taglibs instead of using scriptlets.
You can do it via JQuery, which IMHO more clean:
<select data-selected="${eqName}">
<%
for(int count=0;count<eqArray.size();count++){ %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%}
%>
</select>
At the end of the page:
<script type="text/javascript">
$("select[data-selected]").each(function() {
var selected = $(this).data("selected");
$("select[data-selected='" + selected + "'] option[value='" + selected + "']").attr("selected", "selected");
})
</script>
By this way, you just need include the js at each of your page.
BTW, I recommend you to use JSTL and EL, which is more readable:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<select data-selected="${eqName}">
<c:forEach items="${eqArray}" var="model">
<option value="${model}">${model}</option>
</c:forEach>
</select>
You can implement these in two ways
By using jsp
" selected="selected" >
By Using Javascript at the end of the select box code
document.getElementById('selectBoxID').value=""
instead of selectBoxID id use the select box id

Categories