Kindly assist here, the getParameter is only printing the first portion of the String element in the tag.
here is the select tag
<select name="ActionSelect" id="ActionSelect" >
<%Iterator itr;%>
<% List data = (List) request.getAttribute("data");
for (itr = data.iterator(); itr.hasNext();) {
String value = (String) itr.next();
%>
<option value=<%=value%>><%=value%></option>
<%}%>
</select>
and here is the code in the servlet
PrintWriter pw = response.getWriter();
String connectionURL = "jdbc:mysql://localhost/db";
Connection connection;
try{
this.ibrand = request.getParameter("ActionSelect");
pw.println(ibrand);
} catch (Exception e) {
pw.println(e);
}
Use double quotes around value in the option tag:
<option value="<%=value%>"><%=value%></option>
As it is right now, you probably have a space in your value so only the part of the value before space is returned.
Incidentally, it's not necessary to declare the Iterator uptop; you can do so directly in the for loop:
for (Iterator itr = data.iterator(); itr.hasNext();) {
Finally, consider using tag libraries instead of writing java code directly as scriptlets in your JSP.
Related
Servlet
ArrayList<String[]> itemsInCart = new ArrayList<String[]>();
String[] test = {"bah","3.50","false"};
itemsInCart.add(test);
ArrayList<Integer> testALEmpty = new ArrayList<>();
ArrayList<Integer> testALItems = new ArrayList<>();
testALItems.add(1);
testALItems.add(2);
testALItems.add(3);
String testStr = "This is a test string";
request.setAttribute("testALEmpty", testALEmpty);
request.setAttribute("testALItems", testALItems);
request.setAttribute("testStr", testStr);
request.setAttribute("cartAttribute", itemsInCart);
try {
getServletContext().getRequestDispatcher("/Cart.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
JSP
if (request.getAttribute("cartAttribute") == null) {
%>
<b>No Cart</b>
<%
}
When the servlet forwards to the JSP, I have No Cart because for some reason the servlet is not passing the attributes to the JSP.
set request attribute to session attribute:
request.getSession().setAttribute("parameter", "test");
or
There are two ways you can accomplish this.
Using a JSP expression you would use <%= %> as (notice no ; at the end)
<%= parameter %>
The second and preferred way is to use JSP EL syntax and reference the request attribute directly using ${ } as
${parameter}
The first option requires you to pull the attribute out of its scope first. The second doesn't.
String parameter = (String) request.getAttribute("parameter");
I have to put parameter in method defined in bean as.The parameters are static.I did this in jsp page as-
<%
String n= "p49_readback";
ref.getDbTable(n);
%>
Through this I'm getting value in java bean method and the method is
public String getDbTable(String parameter)
{
String tolerance =null;
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();//Holds the beamline name and status
try
{
con = getConnection();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql="select Tolerance from Reference.dbo.Set_range where Parameter_Name='"+parameter+"'";
System.out.println("sql "+sql);
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while(rs.next())
{
tolerance= (rs.getString(1));
System.out.println("value of tolerance is "+tolerance);
}
}
catch( Exception e )
{
System.out.println("\nException in getDbTable "+e);
}
finally
{
closeConnection(stmt, rs, con);
}
return tolerance;
Now I want to call this method in jsp and store its value into a variable.But I'm not able to retrieve or call this method in jsp page .
I tried as
<c:set value="${ref.getDbTable(param.p49_readback)}" var="db"></c:set>
But its a wrong approach,I'm not getting value returned by the method.How to do that?
If you are using plain JSPs, you could just do this...
<%
String n= "p49_readback";
String reference = ref.getDbTable(n);
%>
Now anywhere you want to use this, just do...
<%=reference%>
You could even do...
<%
String n= "p49_readback";
String reference = ref.getDbTable(n);
%>
<c:set var="reference" value="<%=reference%>"/>
I am trying to list values from the database using JSP combobox like this:
My Vector Method:
public Vector getCampusCode(StudentRegistrationBean srb){
lgcampus = srb.getLgcampus();
Vector v = new Vector();
Connection conn = null;
try{
conn = db.getDbConnection();
Statement st = conn.createStatement();
String sql = "select CAMPUS_CODE from campus_master where CAMPUS_NAME = '" + lgcampus + "'";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String camp = rs.getString("CAMPUS_CODE");
v.add(camp);
}
}catch(Exception asd){
System.out.println(asd.getMessage());
}
return v;
}
My JSP:
<jsp:useBean id="obj1" class="com.kollega.dao.StudentRegistrationDao" scope="page"/>
<jsp:useBean id="srb" class="com.kollega.bean.StudentRegistrationBean" scope="page"/>
<option selected value="SELECT">SELECT</option>
<c:forEach var="item" items="${obj1.campusCode(srb)}">
<option>${item}</option>
</c:forEach>
</select>
Of course the Combo is not getting Populated and all the other components on the page after the Combo are masked(disappear). If I remove the bean attached to the Vector without the Where Condition, my values are getting listed. But i need only specific values and not all. how Can i achieve this?
I just tried to populate the values in the combo box, it worked just fine. Please see the code below -- JSP
<jsp:useBean id="obj1" class="com.tutorial.ComboValues" scope="page"> </jsp:useBean>
<jsp:useBean id="obj2" class="com.tutorial.Input" scope="page"> </jsp:useBean>
<select>
<option selected value="SELECT">SELECT</option>
<c:forEach var="item" items="${obj1.getValues(obj2)}">
<option>${item}</option>
</c:forEach>
</select>
ComboValues class
public class ComboValues {
public Vector getValues(Input i){
Vector v = new Vector<String>();
if(i.getInput()==0)
v.add("worked");
else
v.add("it hurts");
return v;
}
}
Input class
public class Input {
int value = 0;
public void setInput(int i){
this.value = i;
}
public int getInput(){
return this.value;
}
}
The problem may be in the reference 'srb' you are passing to StudentRegistrationDao#getCampusCode since jsp:useBean will create a new instance of that type when there is no such object available. The other area to check is lgcampus = srb.getLgcampus(); whether it returns a proper value for the where clause. Hope this helps
Not sure whether it is possible, if I have the following code for autoComplete, how can I use this in jstl code to achieve the same? Or are there any other ways to achieve this?
<input type="text" id="department" name="department"/>
<script>
$("#department").autocomplete("getdept.jsp",{minChars: 4});
</script>
and in getdept.jsp
DepartmentMB dept = new DepartmentMB ();
String query = request.getParameter("q");
List<String> dep = dept.getData(query);
Iterator<String> iterator = dep .iterator();
while(iterator.hasNext()) {
String department = (String)iterator.next();
String deptName=(String)it.next();
out.println(deptName);
}
I have two dropdown fields in a JSP page and I have type4 connection with oracle 10g. I want that based on one dropdown selection I want that second dropdown should get filled by fetching data from database based on data in first dropdown automatically just like refreshing that JSP page or showing an alert something like "please wait". How can I do it in JSP-Servlet?
<select name="dropdown1">
<option value="<%out.println(name);%>"><%out.println(name);%></option>
</select>
My objective is: This below dropdown should get filled base don above selection:
<select name="dropdown2">
<option value="<%out.println(rollno);%>"><%out.println(rollno);%></option>
</select>
I have found one solution :
<body onload="setModels()">
<% // You would get your map some other way.
Map<String,List<String>> map = new TreeMap<String,List<String>>();
Connection con=null;
String vehtypeout="";
String vehtypeout1="";
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("");
PreparedStatement ps=null;
ResultSet rs=null;
ps=con.prepareStatement("select c1.name, c2.roll from combo1 c1 left join combo2 c2 on c1.name=c2.name order by name");
rs=ps.executeQuery();
while(rs.next()){
vehtypeout=rs.getString(1);
vehtypeout1=rs.getString(2);
map.put(vehtypeout, Arrays.asList((vehtypeout1)));// here i want to show multiple value of vehtypeout1 from database but only one value is coming from databse, how can i fetch multiple value?
map.put("mercedes", Arrays.asList(new String[]{"foo", "bar"}));
}
rs.close();
ps.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
<%! // You may wish to put this in a class
public String modelsToJavascriptList(Collection<String> items) {
StringBuilder builder = new StringBuilder();
builder.append('[');
boolean first = true;
for (String item : items) {
if (!first) {
builder.append(',');
} else {
first = false;
}
builder.append('\'').append(item).append('\'');
}
builder.append(']');
return builder.toString();
}
public String mfMapToString(Map<String,List<String>> mfmap) {
StringBuilder builder = new StringBuilder();
builder.append('{');
boolean first = true;
for (String mf : mfmap.keySet()) {
if (!first) {
builder.append(',');
} else {
first = false;
}
builder.append('\'').append(mf).append('\'');
builder.append(" : ");
builder.append( modelsToJavascriptList(mfmap.get(mf)) );
}
builder.append("};");
return builder.toString();
}
%>
<script>
var modelsPerManufacturer =<%= mfMapToString(map) %>
function setSelectOptionsForModels(modelArray) {
var selectBox = document.myForm.models;
for (i = selectBox.length - 1; i>= 0; i--) {
// Bottom-up for less flicker
selectBox.remove(i);
}
for (i = 0; i< modelArray.length; i++) {
var text = modelArray[i];
var opt = new Option(text,text, false, false);
selectBox.add(opt);
}
}
function setModels() {
var index = document.myForm.manufacturer.selectedIndex;
if (index == -1) {
return;
}
var manufacturerOption = document.myForm.manufacturer.options[index];
if (!manufacturerOption) {
// Strange, the form does not have an option with given index.
return;
}
manufacturer = manufacturerOption.value;
var modelsForManufacturer = modelsPerManufacturer[manufacturer];
if (!modelsForManufacturer) {
// This modelsForManufacturer is not in the modelsPerManufacturer map
return; // or alert
}
setSelectOptionsForModels(modelsForManufacturer);
}
function modelSelected() {
var index = document.myForm.models.selectedIndex;
if (index == -1) {
return;
}
// alert("You selected " + document.myForm.models.options[index].value);
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer">
<% boolean first = true;
for (String mf : map.keySet()) { %>
<option value="<%= mf %>" <%= first ? "SELECTED" : "" %>><%= mf %></option>
<% first = false;
} %>
</select>
<select onChange="modelSelected()" id="models">
<!-- Filled dynamically by setModels -->
</select>
But i am getting only one value in vehtypeout1 where databse contains multiple values. How can i do it?
Using jquery, bind a function to the onchange event of "combobox1" select box.
In that function, send an ajax request (you can use jquery get function) to a jsp page in your server.
In that jsp page, retrieve the relevant data from database and send the response back to the client with those data (may be you need to use JSON format).
In the jquery get function, you can add a callback function to execute after server send you back the response.
Inside that call back function, write the code to fill "combobox2" using response data sent by the server.
You'll want an ajax call like below. Have your function that is called return a html-string of
"<option value='myVal'>myText</option>".
The jQuery/Ajax would be:
$("#ddl1").change(function() {
$.ajax({
url: "URLyouwanttoaddress",
data: "myselection=" + $("#ddl1").val();
type:"get",
success: function(data) {
$("#ddl2").html(data);
}
});
});