I am trying to populate a page with check box selections.I am using struts in my project.So in the action class i have created the list loaded with experiment nos in it.So in My Jsp page i got back the experiment list and set it to the checkbox .But the checkboxes with unique experiment nos are not shown on the page
Generating the list from the action class
public List expList() throws FISException
{
Utilities utilities = new Utilities();
PreparedStatement sqlQueryStmt = null;
ResultSet resultSet = null;
int index = 1;
List expList = new ArrayList();
Connection conn = null;
Logger logger = Logger.getInstance();
try
{
String resource = null;
String sql = "SELECT factory_node_id,exp_id FROM s_exp where dept = ?";
sqlQueryStmt = conn.prepareStatement(sql);
sqlQueryStmt.setString(index++,dept);
resultSet = sqlQueryStmt.executeQuery();
while(resultSet.next())
{
expNo= resultSet.getString(2);
expList.add(expNo);
}
}
catch(Exception e)
{
logger.error(Logger.FLOW,"Error in getting expNo",e);
}
finally
{
DBUtils.cleanUp(sqlQueryStmt,resultSet);
DBUtils.cleanUp(conn);
}
return expList;
}
<%
List expList = new ArrayList();
expList =factory.getList("resource_list_data");
request.setAttribute("expNos ", expList );
%>
<c:forEach var="item" items="${expNos}">
<input type="checkbox" value="${item}"/>
</c:forEach>
Kindly help on how to display checkbox dynamically..
<c:set var="count" value="0" scope="page" />
<c:forEach var="item" items="${expNos}">
<input type="checkbox" name="${count + 1}" value="${item}"/>
</c:forEach>
update:
<c:set var="count" value="0" scope="page" />
<c:forEach var="item" items="${expNos}">
${item} <input type="checkbox" name="${count + 1}" value="${item}"/>
</c:forEach>
Related
I have written a dropdown list which is populated by the database. This is my dropdown code in JSP file.
<td>Category:</td>
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
String cname = rs.getString("category_name");
String id = rs.getString("category_id");
System.out.println(id);
%>
<option value="<%= id%>"><%= cname%></option>
<%
}
%>
</select>
<%
} catch (SQLException sqe) {
out.println(sqe);
}
%>
</td>
The relevant servlet code is;
String id = request.getParameter("category");
In the sout of the dropdown in JSP it prints all the IDs in the category. But when it comes to the servlet it returns a null. How to resolve this issue?
I didn't find any <form> tag neither submit button in your code ,try below code :
<td>Category:</td>
<form method="post" action="yourservleturl">//form tag for submitting data
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
%>
<option value="<%=rs.getString("category_id")%>"><%=rs.getString("category_name")%></option> // printing option values
<%
}
%>
</select>
<%
} catch (SQLException sqe) {
out.println(sqe);
}
%>
<input type="submit" value="submit">///submit btn
</form>
</td>
also get, dropdown value by String id = request.getParameter("category"); .it should worked .
The local variable should be sound out of while loop, because you need that value after while loop.
<%
try {
dbConnect dbConnect = new dbConnect();
Connection currentCon = dbConnect.Connect();
System.out.println("Connection sucess");
String sql = "SELECT * FROM categories";
PreparedStatement ps = currentCon.prepareStatement(sql);
ResultSet rs = ps.executeQuery();%>
String cname = null;
String id = null;
<td><select name="category" class="form-control" required>
<%
while (rs.next()) {
cname = rs.getString("category_name");
id = rs.getString("category_id");
System.out.println(id);
%>
Besides, I suggest you use Expression Language instead of <%= id%>
change
<option value="<%= id%>"><%= cname%></option>
to
<option value="${id}">${name}</option>
And don't forget submit button.
Here is my code.
<%--
Document : index
Created on : Jan 16, 2016, 2:49:24 PM
Author : Manoj
--%>
<%#page import="java.sql.*"%>
<% Class.forName("org.apache.derby.jdbc.ClientDriver"); %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Inserting Data</title>
</head>
<body>
<h1>Inserting Data</h1>
<%!
public class Contact {
String URL = "jdbc:derby://localhost:1527/contact";
String USERNAME = "nbuser";
String PASSWORD = "nbuser";
Connection conn = null;
PreparedStatement pst = null;
Statement stm = null;
ResultSet rst = null;
public Contact(){
try{
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
pst = conn.prepareStatement(
"INSERT INTO contactinfo (name, address, mobile)"+" VALUES (?, ?, ?)");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
public int setContact(String name, String address, String mobile)
{
int result =0;
try{
pst.setString(1, name);
pst.setString(2, address);
pst.setString(3, mobile);
result = pst.executeUpdate();
}
catch(SQLException e)
{
e.printStackTrace();
}
return result;
}
}
%>
<%
int result = 0;
if(request.getParameter("submit") != null){
String name = new String();
String address = new String();
String mobile = new String();
if (request.getParameter("name")!= null)
{
name = request.getParameter("name");
}
if (request.getParameter("address")!= null)
{
address = request.getParameter("address");
}
if (request.getParameter("mobile")!= null)
{
mobile = request.getParameter("mobile");
}
Contact contact = new Contact();
result = contact.setContact(name, address, mobile);
}
%>
<form name="myform" action="index.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Name</td>
<td><input type="text" name="name" value="" size="30" /></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" value="" size="50" /></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" value="" size="10" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="clear" />
<input type="submit" value="Submit" name="submit" />
</form>
</body>
</html>
Kindly help me. This is the first time I am writing a JSP code.
The database I am using is Apache derby within Neatbeans 8.1. I tried all alternatives but could not find a solution. When I manually insert a row into the database it is inserting the values.
You can try to debug your code and check whether if(request.getParameter("submit") != null) is returning TRUE or FALSE.
As I doubt because you have used a
<input type="submit" value="Submit" name="submit" />
where value is with capital S
My goal is to selected data in database and display in drop down list.
For example, see the image below show that fbMenuId = M001 (Lasagne).
So at dropdownlist M001 option will be selected. I also need display OTHER MENU like M002,M003,M004,M005,M006 and M007. For example, see the image below
However, my outcome is
Below are my codes
<select class="form-control" name="menu" id="menu">
<option value="${order.fbMenuId}" selected>${order.fbMenuName}</option>
<c:forEach var="menu" items="${menu}">
<option value="${menu.fbMenuId}">${menu.fbMenuName}</option>
</c:forEach>
</select>
I am able to display M001 Lasagne. However, there are 2 Lasagne which I do not want. Anyone please help me. Help will be appreciate. Thanks in advance!
Below are codes for servlet and data access object.
Servlet
OrderDAO dao = new OrderDAO();
request.setAttribute("order", dao.getOrder(fbOrderId));
request.setAttribute("menu", dao.getMenu(restaurant));
OrderDAO
public OrderBean getOrder(Integer fbOrderId) {
OrderBean ob = new OrderBean();
try {
currentCon = ConnectionManager.getConnection();
Statement statement = currentCon.createStatement();
ResultSet rs = statement.executeQuery("SELECT fborders.fbMenuId, fbMenuName FROM fborders INNER JOIN fbmenu ON fborders.fbMenuId = fbmenu.fbMenuId WHERE fbOrderId='"+ fbOrderId + "'");
while (rs.next()) {
ob.setFbMenuId(rs.getString("fbMenuId"));
ob.setFbMenuName(rs.getString("fbMenuName"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return ob;
}
public ArrayList getMenu(String restaurant) {
ArrayList<OrderBean> am = new ArrayList<OrderBean>();
try {
currentCon = ConnectionManager.getConnection();
Statement statement = currentCon.createStatement();
ResultSet rs = statement
.executeQuery("SELECT fbMenuId, fbMenuName FROM fbmenu WHERE fbRestaurantId='"
+ restaurant + "'");
while (rs.next()) {
OrderBean ob = new OrderBean();
ob.setFbMenuId(rs.getString("fbMenuId"));
ob.setFbMenuName(rs.getString("fbMenuName"));
am.add(ob);
}
} catch (SQLException e) {
e.printStackTrace();
}
return am;
}
As per my understanding, you are showing the selected value twice. one time by appending
<option value="${order.fbMenuId}" selected>${order.fbMenuName}</option>
and another time by iterating the list. Instead of this populate all the values in the dropdown and set the required value as selected. Just write simple condition like the following.
<select class="form-control" name="menu" id="menu">
<c:forEach var="menu" items="${menu}">
<option value="${menu.fbMenuId}">${menu.fbMenuName}
<c:if test="${menu.fbMenuId == order.fbMenuId}">
selected
</c:if>
</option>
</c:forEach>
</select>
<select class="form-control" name="menu" id="menu">
<c:forEach var="menu" items="${menu}">
<c:choose>
<c:when test="${menu.fbMenuId == order.fbMenuId}">
<option value="${order.fbMenuId}" selected>${order.fbMenuName}</option>
</c:when>
<c:otherwise>
<option value="${menu.fbMenuId}">${menu.fbMenuName} </option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
I have a JSP page in which I have two tags. In first I am trying get input such as Car Maker name such as Tata, Hyundai, Toyota, Audi etc. When user selects any option in first , it should display car models from that maker such as Innova,Land Cruiser etc. So when user selects any option in first tag, I am calling a servlet which gets all the models from database in a list and setting the list as attribute of session and forwarding the request back to JSP. But in jsp when I try to fetch the list it is giving NULL POINTER EXCEPTION. How to solve it?
The code is as below:
DbReviewCar.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn= null;
PreparedStatement pstmt= null;
ResultSet rs;
String sql= null;
String maker= request.getParameter("make");
List modellist= new ArrayList();
/*if(maker==null)
{
modellist.add("ferrari");
modellist.add("hummer");
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
else
{*/
try {
Class.forName("com.mysql.jdbc.Driver");
conn= DriverManager.getConnection("jdbc:mysql://localhost/cardetails", "root", "Welcome123");
sql= "select model from cars where make=?;";
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, maker);
rs= pstmt.executeQuery();
while(rs.next())
{
String mod= rs.getString(1);
modellist.add(mod);
System.out.println(mod+">>>>>>>>>>>>>>>>>>.");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getSession().setAttribute("value", modellist);
request.getRequestDispatcher("CarReview.jsp").forward(request,response);
}
CarReview.jsp
Here is my JSP file
<form action="DbReviewCar" method="get" name="myform">
<table>
<tr>
<td>
<tr>
<td>Make:</td>
<td><select name="make" onchange="this.form.submit()"><option>select</option>
<option>Maruti</option>
<option>Ford</option>
<option>Honda</option>
<option>Skoda</option>
<option>Tata</option>
<option>Audi</option>
<option>Toyota</option></select><br></br></td>
</tr>
<%
List list = new ArrayList();
list.addAll((List) (request.getSession().getAttribute("value")));
%>
<tr>
<td>Model:</td>
<td><select name="model">
<%
for (int i = 0; i < list.size(); i++) {
%>
<option value=<%=list.get(i)%>><%=list.get(i)%></option>
<%
}
%>
</select><br></br></td>
</tr>
<tr>
<td>Rating For Style:</td>
<td><input type="text" name="style"><br></br></td>
</tr>
<tr>
<td>Rating for comfort:</td>
<td><input type="text" name="comfort"><br></br></td>
</tr>
<tr>
<td>Rating for Performance:</td>
<td><input type="text" name="performance"><br></br></td>
</tr>
<tr>
<td>Rating for FuelEconomy:</td>
<td><input type="text" name="economy"><br></br></td>
</tr>
<tr>
<td>Review:</td>
<td><textarea cols="18" rows="3"></textarea><br></br></td>
</tr>
<tr>
<td><Button>Save</Button></td>
<td><input type="reset" name="cancel" value="Cancel" /></td>
</tr>
</table>
</form>
When jsp loading for the first time the "value" atribute is not set.
Try to check null for value:
request.getSession().getAttribute("value")
having a issues with getting the result of a query based on the drop down select, for some reason its not returning anything when trying to post it on to the jsp.
here is my what code looks like
here is my index.jsp
<form method="post" action="Test">
<h3>Get today's feed event</h3>
<p>
<select name="colour" size="1" class="selectpicker" data-style="btn-inverse">
<option value="light">Runningball</option>
<option value="amber">Enetpulse</option>
<option value="DonBest">DonBest</option>
<option value="BetRadar">Betradar</option>
</select>
</p>
<input type="submit" value="Submit" class="btn">
</form>
and here is my logic
public List<String> getColours(String colour) {
List<String> colours = new ArrayList<String>();
if(colour.equals("DonBest")){
try {
connectToCoral3();
CachedRowSet res1 = con.selectQuery(
"select id,name,event_time from nodes where syst_id=16 and event_time>=now() order by event_time");
//some debugging code
while (res1.next()) {
System.out.println("id= " + res1.getString("id") + " name= "
+ res1.getString("name"));
}
while (res1.next()) {
colours.add(res1.getString("id"));
colours.add(res1.getString("name"));
colours.add(res1.getString("event_time"));
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
e.getStackTrace();
}
}else if(colour.equals("light")){
colours.add("orange");
colours.add("pink");
}
return (colours);
}
servlet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
try {
String c = request.getParameter("colour");
ColourExpert ce = new ColourExpert();
List<String> styles = ce.getColours(c);
request.setAttribute("styles",styles);
System.out.println(styles);
} catch (Exception e) {
request.setAttribute("error", "Retrieving rows failed.");
e.printStackTrace();
}
RequestDispatcher view = request.getRequestDispatcher("WEB-INF/Home/simplePage.jsp");
view.forward(request, response);
and here is my jsp,
<c:forEach items="${styles}" var="styles">
<c:out value="${styles.id}" />
<c:out value="${styles.name}" />
<c:out value="${styles.event_time}" />
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>
any help would be great
Remove the first while loop in your code. Then it will work.
//Remove This
while (res1.next()) {
System.out.println("id= " + res1.getString("id") + " name= " + res1.getString("name"));
}
First to access a request variable in JSTL you need to change your code to:
<c:forEach items="${requestScope.styles}" var="styles">
<c:out value="${styles.id}" />
<c:out value="${styles.name}" />
<c:out value="${styles.event_time}" />
</c:forEach>
<c:if test="${not empty error}">Error: ${error}</c:if>