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);
}
Related
I have a string with a number of place holders, is there any way if we can collect all the place holders in one go with the help of java streams?
Input:
<Html>
<Table>
<TR><TD>||BuySell||</TD></TR>
<TR><TD>||ExchangeName||</TD></TR>
</Table>
</Html>
Output:
List<String> placeholders = [BuySell,ExchangeName]
This can be done using a helper function.
BiFunction<Matcher, Function<Matcher, Object>, Collection<?>> placeHolderExtractor = (mch, extracter) -> {
List<Object> list = new ArrayList<>();
while(mch.find()) {
list.add(extracter.apply(mch));
}
return list;
};
String htmlStr = "<Html> <Table> <TR><TD>||BuySell||</TD></TR> <TR><TD>||ExchangeName||</TD></TR> </Table></Html>";
String regex = "(\\|\\|)([\\w]+)\\1";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(htmlStr);
List<String> placeHolderList = placeHolderExtractor.apply(matcher, macher -> macher.group(2))
.stream()
.map(String::valueOf)
.collect(Collectors.toList());
How can i show the special characters(~!##...etc) and numeric number(0-9) not in tag when user key in the value from the input tag? Is it possible to restrict special characters and numeric display in normal text? Any help would be appreciated.
Current output :
<%
ArrayList alTag = new ArrayList();
Vector vTag = new Vector();
String SQL = "SELECT CODE, DESCP FROM TB_FRUIT WITH UR";
TEST.makeConnection();
TEST.executeQuery(SQL);
while(TEST.getNextQuery())
{
Vector vRow = new Vector();
ArrayList alInner = new ArrayList();
String field =TEST.getColumnString("CODE");
String descp =TEST.getColumnString("DESCP");
alInner.add(field);
alInner.add(descp);
alTag.add(alInner);
vTag.addElement(field);
}
TEST.takeDown();
%>
<script>
var dbArray = [<%
String dbCode = "";
String dbList = "";
for(int i=0;i<vTag.size();i++)
{
dbCode = (String) vTag.elementAt(i);
dbList += "\"" + dbCode + "\",";
}
out.print(dbList); %>
];
$(document).ready(function() {
$("#myTags").tagit({
availableTags: dbArray
});
});
</script>
<html>
<body>
<input type="text" id="myTags" name="TYPE">
</body>
</html>
This restricts the input only to alphabets
$('#myTags').keypress(function (event) {
var regex = new RegExp("^[a-zA-Z]+$");
var str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(str)) {
e.preventDefault();
return false;
}
});
If you are open to introducing a jquery plugin, the easiset way is to include the [alphanum jquery plugin] and then do
$('#myTags').alpha();
[alphanum jquery plugin] : https://github.com/KevinSheedy/jquery.alphanum
UPDATED :
You could extent the jquery tagit plugin and override the cleaned input method as shown below so as to replace non alphabets .
$.widget( "ui.tagit", $.ui.tagit, {
_cleanedInput: function() {
var cleanedInput = this.tagInput.val().replace(/[^a-zA-Z0-9\s]+/,"");
return $.trim(cleanedInput.replace(/^"(.*)"$/, '$1'));
}
});
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
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);
}
});
});
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.