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.
Related
Hi im trying to update data from database using submit button , witch is located on a jsp page that shows data based on name and surname that you entered in login.jsp..
validationForDatabase.jsp shows data from the table pacijent,based on name and surname are entered in another jsp page. Fields name and surname are readonly so you can chage everything except those fileds, and when you make chages and press button Update it should redirect you to update.jsp. If the update is successful you sholud be redirected back to validationForDatabase.jsp but instead of doing that it shows me Badly entered data from else section.
Could you please guide me on how to fix this problem or maybe another way to do this.
Thanks in advance
validationForDatabase.jsp
`
<%
try{
String name= request.getParameter("name");
String surname= request.getParameter("surname");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/sth","root","");
PreparedStatement pst = conn.prepareStatement("Select name,surname from pacijent where name=? and surname=?");
pst.setString(1, name);
pst.setString(2, surname);
ResultSet rs = pst.executeQuery();
if(rs.next())
{
out.println("Name of the patient : "+name);
out.println("<br/>Surname of the patient : "+surname);
HttpSession sesija = request.getSession();
sesija.setAttribute("name", name);
sesija.setAttribute("surname", surname);
%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String connectionUrl = "jdbc:mysql://localhost:3306/sth";
try {Class.forName("com.mysql.jdbc.Driver");}
catch (ClassNotFoundException e) {e.printStackTrace();}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<form action="Update.jsp" method="get">
<%
try{
connection = DriverManager.getConnection ("jdbc:mysql://localhost:3306/sth","root","");
statement=connection.createStatement();
String sql ="SELECT name,father,surname,birth,adress,phone,email,notes "+ "FROM pacijent where name='"+sesija.getAttribute("name")+"'and surname='"+surname+"';";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<p align="center"><%= sesija.getAttribute("name")%><%= sesija.getAttribute("surname")%></p>
<p><label class="uname">name</label><input name="name" readonly value="<%=sesija.getAttribute("name") %>"/></p>
<p><label class="uname">father</label><input name="father" value="<%=resultSet.getString("father") %>"/></p>
<p><label class="uname">surname</label><input name="surname" readonly value="<%=sesija.getAttribute("surname") %>"/></p>
<p><label class="uname">birth</label><input name="birth" value="<%=resultSet.getString("birth") %>"/></p>
<p><label class="uname">Adress</label><input name="adress" value="<%=resultSet.getString("adress ") %>"/></p>
<p><label class="uname">phone</label><input name="phone" value="<%=resultSet.getString("phone") %>"/></p>
<p><label class="uname" > E-mail</label><input name="email" value="<%=resultSet.getString("email") %>"/></p>
<p><label for="usernamesignup" class="uname">info</label>
<textarea name="notes" id="a" class="a" rows="4" cols="60"
textareaObject.value="text" ><%= resultSet.getString("notes") %></textarea></p>
<input type="submit" name="Submit" value="Update" />
</form>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
sesija.invalidate();
%>
<%
}
else{
%>
<br/><br/><br/><br/><br/><h1 align="center">Badly entered data</h1>
<%}
}
catch(Exception e){
out.println("Error "+e);
}
%>`
Update.jsp works in redirecting back but it wont update data.
Update.jsp
`
<%
String name=request.getParameter("name");
String father=request.getParameter("father");
String surname=request.getParameter("surname");
String birth=request.getParameter("birth");
String adress =request.getParameter("adress ");
String phone=request.getParameter("phone");
String email=request.getParameter("email");
String notes=request.getParameter("notes");
try {
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/sth", "root", "");
Statement st1 = null;
st1 = conn.createStatement();
HttpSession sesija = request.getSession();
sesija.setAttribute("name", name);
System.out.println(sesija.getAttribute(name));
st1.executeUpdate("UPDATE pacijent SET name= '"+name+"',father= '"+father+"',"
+ "surname= '"+surname+"',birth= '"+birth+"',adress = '"+adress +"',"
+ "phone= '"+phone+"',email = '"+email+"',notes = '"+notes+"'"
+ "WHERE name="+sesija.getAttribute(name));
response.sendRedirect("validationForDatabase.jsp");
} catch (Exception e) {
out.println("Error : " + e);
}
%>`
Thanks a lot.
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
I am trying to get a value from jsp to sevlet.First the variable value is taken by session setArribute(), getAttribute() then I need to pass that particular variable from jsp to servlet but I am getting null value for that variable.
Here below I am sharing my code, can anyone findout how can I solve this issue?
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.*"%>
<html>
<head>
<title>Welcome to survey</title>
</head>
<body>
<%
ResultSet rset;
String sur_id = request.getParameter("surveyid");
session.setAttribute( "surveyid", sur_id );
int new_survey_id = Integer.parseInt(sur_id);
if (request.getParameter("surveyid") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter("surveyid")+"</b>!");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
Statement stmt = con.createStatement();
rset = stmt.executeQuery(query);
while(rset.next()){
// out.println(rset.getString(1));
// out.println(rset.getString(2));
// out.println(rset.getString(3));
// out.println(rset.getString(4));
%>
<table border="3">
<tr><td>Survey_Id</td><td><%=rset.getString(1)%></td></tr>
<tr><td>Family name</td><td><%=rset.getString(2)%></td></tr>
<tr><td>First name</td><td><%=rset.getString(3)%></td></tr>
<tr><td>Middle name</td><td><%=rset.getString(4)%></td></tr>
<tr><td>gender</td><td><%=rset.getString(5)%></td></tr>
<tr><td>dat of birth</td><td><%=rset.getString(6)%></td></tr>
<tr><td>income</td><td><%=rset.getString(7)%></td></tr>
<tr><td>complete address</td><td><%=rset.getString(8)%></td></tr>
<tr><td>coordinates</td><td><%=rset.getString(9)%></td></tr>
<tr><td>mobile number</td><td><%=rset.getString(10)%></td></tr>
<tr><td>email address</td><td><%=rset.getString(11)%></td></tr>
<tr><td>present Internet provider</td><td><%=rset.getString(12)%></td></tr>
<tr><td>comments</td><td><%=rset.getString(13)%></td></tr>
<tr><td>remarks</td><td><%=rset.getString(14)%></td></tr>
<br>
<form>
<table>
<tr><td><input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();"></td>            
<td><input type="button" value="delete"></td>            
<td><input type="button" value="print"></td>            
<td><input type="button" value="send mail"></td>            
</tr>
</table>
</form>
</table>
<%
}
%>
</body>
</html>
from the above code I have set the session variable as surveyid
and I can get it from the below code.It is working properly
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit survey</title>
</head>
<body>
<%
ResultSet resultSet;
String surveyId = (String) session.getAttribute("surveyid");
out.println("check"+surveyId);
request.setAttribute("surveyid", surveyId);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ surveyId ;
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(query);
while(rset.next()){
%>
<form name="Editsurveyform" method="post" action="EditSurvey">
<table>
<tr><td>Family name:</td><td><input type="text" name="familyName" value='<%=rset.getString(2)%>'></td></tr>
<tr><td>First name:</td><td><input type="text" name="firstName" value='<%=rset.getString(3)%>'></td></tr>
<tr><td>Middle name:</td><td><input type="text" name="middleName" value='<%=rset.getString(4)%>'></td></tr>
<tr><td>Gender:</td>
<td>
<%
if(rset.getString(5).equals("male")){
%>
<input type="radio" name="sex" value="male" checked>Male
<input type="radio" name="sex" value="female">Female
<%}
else{
%>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female" checked>Female
<%
}
%>
</td>
</tr>
<tr><td>Birthday:</td><td><input type="date" name="dob" value='<%=rset.getString(6)%>'></td></tr>
<tr><td>Income : A?B?C?D?</td><td><input type="text" name="income" value='<%=rset.getString(7)%>'></td></tr>
<tr><td>Complete Address:</td><td><input type="text" name="address" value='<%=rset.getString(8)%>'></td></tr>
<tr><td>Coordinates:</td><td><input type="text" name="coordinates" value='<%=rset.getString(9)%>'></td></tr>
<tr><td>Mobile number:</td><td><input type="tel" name="mobileno" value='<%=rset.getString(10)%>'></td></tr>
<tr><td>Email Address:</td><td><input type="email" name="email" value='<%=rset.getString(11)%>'></td></tr>
<tr><td>Present internet provider:</td><td><input type="text" name="iprovider" value='<%=rset.getString(12)%>'></td></tr>
<tr><td>Positive comments with present provider:</td><td><textarea name="comments" cols="40" rows="5"><%=rset.getString(13)%></textarea></td></tr>
<tr><td>Negative remarks with present provider:</td><td><textarea name="remarks" cols="40" rows="5"><%=rset.getString(14)%></textarea></td></tr>
<tr><td><input type="submit" name="editsurvey" value="update survey details"></td><td><input type="reset" name="cancel" value="cancel"></td></tr>
</table>
</form>
<%}
//response.sendRedirect("EditSurvey?surveyId="+surveyId);
%>
</body>
</html>
But I encounter the problem in below java
package com.survey;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* Created by rajee on 2/18/15.
*/
public class EditSurvey extends HttpServlet {
public String familyName;
public String firstName;
public String middlename;
public String gender;
public String dateOfBirth;
public String income;
public String completeAddress;
public String coordinates;
public String mobileno;
public String emailAddress;
public String presentIP;
public String comment;
public String remark;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String surveyId = (String) request.getAttribute("surveyid");
System.out.println(surveyId);
familyName = request.getParameter("familyName");
firstName = request.getParameter("firstName");
middlename = request.getParameter("middleName");
gender = request.getParameter("sex");
dateOfBirth = request.getParameter("dob");
income = request.getParameter("income");
completeAddress = request.getParameter("address");
coordinates = request.getParameter("coordinates");
mobileno = request.getParameter("mobileno");
emailAddress = request.getParameter("email");
presentIP = request.getParameter("iprovider");
comment = request.getParameter("comments");
remark = request.getParameter("remarks");
System.out.println(familyName);
System.out.println(firstName);
System.out.println(middlename);
System.out.println(gender);
System.out.println(dateOfBirth);
System.out.println(income);
System.out.println(completeAddress);
System.out.println(coordinates);
System.out.println(mobileno);
System.out.println(emailAddress);
System.out.println(presentIP);
System.out.println(comment);
System.out.println(remark);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="surveysample";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
// try{
//
//
// Class.forName(driver).newInstance();
// conn = DriverManager.getConnection(url + dbName, "root", "root");
// PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into surveysample.surveydetail(familyname,firstname,middlename,gender,dateofbirth,income,complete_address,coordinates,mobilenumber,emailaddress,presentiprovider,comments,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
//
// pst.setString(1,familyName);
// pst.setString(2,firstName);
// pst.setString(3,middlename);
// pst.setString(4,gender);
// pst.setString(5,dateOfBirth);
// pst.setString(6,income);
// pst.setString(7,completeAddress);
// pst.setString(8,coordinates);
// pst.setString(9,mobileno);
// pst.setString(10,emailAddress);
// pst.setString(11,presentIP);
// pst.setString(12,comment);
// pst.setString(13,remark);
//
//
// int i = pst.executeUpdate();
// //conn.commit();
// String msg=" ";
// if(i!=0){
// msg="Record has been inserted";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
//
//
// }
// else{
// msg="failed to insert the data";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
// }
// pst.close();
// }
// catch (Exception e){
// pw.println(e);
// }
//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
code
If your problem is for surveyId being null is servlet, it is normal because you try to get it from request :
String surveyId = (String) request.getAttribute("surveyid");
As you put it in session, you should read it from there :
String surveyId = (String) request.getSession().getAttribute("surveyid");
You can try below code in your servlet as :
HttpSession session = request.getSession(false);
String surveyId = (String) session.getAttribute("surveyid");
this method request.getSession(false) will not create new session if session object is already exists. it will simply return old session object if its there otherwise it will return null.
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 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>