Display Selected Data from database in drop down list - java

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>

Related

Dynamic dropdown returns a null from jsp

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.

Null pointer exception on click submit

i created a user management (Create, Read, Update, Delete) with Java and sql.
Here is my dao:
private static final String UPDATE = "UPDATE user set login_user=?, pwd_user=?, id_role=? where id_user=? ";
#Override
public void update_user(User user) throws DAOException {
Connection connexion = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connexion = (Connection) dao_factory.getConnection();
preparedStatement = connexion.prepareStatement(UPDATE);
preparedStatement.setString(1, user.getLogin());
preparedStatement.setString(2, user.getPwd());
preparedStatement.setInt(3, user.getRole());
preparedStatement.setLong(4, user.getId_user());
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new DAOException(e);
}
}
My jsp for update user:
<%
if(action.equalsIgnoreCase("edit")){
%>
<form method="get" action="client">
<div class="form-group">
<input type="text" class="form-control" id="login" name="login" placeholder="login">
Update
</div>
</form>
<% } %>
And my servlet:
String action = request.getParameter("action");
if (request.getParameter("action") != null && action.equalsIgnoreCase("view")) {
request.setAttribute("client", user_dao.find_all());
}
if (action.equalsIgnoreCase("delete")) {
int id = Integer.parseInt(request.getParameter("id"));
user_dao.delete_user(id);
request.setAttribute("client", user_dao.find_all());
}
if (action.equalsIgnoreCase("edit")) {
int id = Integer.parseInt(request.getParameter("id"));
User user = user_dao.getById(id);
session.setAttribute("user_edit", user);
}
if (action.equalsIgnoreCase("update")) {
Long id = Long.parseLong(request.getParameter("id"));
String login = request.getParameter("login");
User user = new User();
user.setLogin("test_login");
user.setPwd("test_pwd");
user.setRole(1);
user.setId_user(id);
user_dao.update_user(user);
}
else {
request.setAttribute("client", user_dao.find_all());
}
this.getServletContext().getRequestDispatcher(VUE).forward(request, response);
My first problem is, when i click in the button "update", it work. But if i press enter, i have a null pointer exception
Second problem is, If I want to recover login user with String login = request.getParameter("login");and user.setLogin(login); the login value is null in db.
Thanks a lot
EDIT:
here is stack trace:
Avertissement: StandardWrapperValve[client]: Servlet.service() for servlet `client threw exception`
java.lang.NullPointerException
at egame.servlets.admin.client.processRequest(client.java:53)
at egame.servlets.admin.client.doGet(client.java:94)
line 53 : if (action.equalsIgnoreCase("delete")).
line 94 is empty
ResultSet resultSet = null;
It is still null after update user is called.
In any case you are trying to access
the servlet will always call request.setAttribute("client", user_dao.find_all());
Use else if unless you want it to happen only on nonupdate cases.
Your HTML/JSP is wrong. You create a HTML-form but what you say is a "button" is actually just an independent link. This is the reason of both issues you mention:
When you click the link form is not submitted
When you press enter, the form is submitted but without data you put in URL
You need to change it to something like
<%
if(action.equalsIgnoreCase("edit")){
%>
<form method="post" action="client">
<div class="form-group">
<input type="text" class="form-control" id="login" name="login" placeholder="login">
<input type="hidden" id="action" value="update" >
<input type="hidden" id="id" value="${ user_edit.id_user }" >
<button type="submit" class="btn btn-primary">Update</a>
</div>
</form>
<% } %>
Side node: NEVER use HTTP GET to submit any changes to the server. If you change data on the server, it should be POST (or DELETE, or PUT but not GET).

Ajax call with spring MVC and Hibernate

I am trying to propagate the value in input type[text] whenever user is selecting one option from select box.
I have a form containing one select option and 3 input type(text) field. What i am trying to do here whenever user select one option from select box depending upon that option value some data i want to fetch from database and propagate to the same page in input type and then after clicking on submit button i want to store the data in database.
I have used ajax call for the same but the problem is that on selecting option value i am able to get the particular data but i am not able to get the same data in jsp input type, each time i need to reload the page manually.
userdetail.jsp
//imports are here
<html>
<head>
</head>
<body>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".name").change(function(){
var name = $(this).val();
if(name.length >= 1){
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "getparamfromdb.do",
data: "name="+name,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
$(".status").html(msg);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be atleast <b>5</b> character long.</font>");
}
});
});
</script>
<div class="add">
<form:form method="post" action="addHealthParam.do" >
<table style="margin-top:-6%; margin-left:8%;">
Parameter Name:<br>
<select name="name" class="name">
<option value="select">Select</option>
<option value="Glucose, Serum">Glucose, Serum</option>
<option value="Uric Acid, Serum">Uric Acid, Serum</option>
<option value="Platelets">Platelets</option>
<option value="NRBC">NRBC</option>
</select>
Parameter Current Reading:
<input type="text" name="current_reading"/>
Unit of Measurement:
<select name="measurementunit" >
<option>
<c:forEach var="healthp" items="${paramvalue}">
${healthp.measurementunit}
</c:forEach>
</option>
</select>
Reference Range(Minimum):
<input type="text" name="minrange" value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.minrange}
</c:forEach>" >
Reference Range(Maximum):<br>
<input type="text" name="maxrange"
value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.maxrange}
</c:forEach>">
<input type="submit" value="Submit"/>
</body>
</html>
Controller class:-
imports are here
#Controller
#SessionAttributes
public class HealthParameterController {
#Autowired
BharatService service;
#Autowired
HibernateTemplate hibernateTemp;
List<HealthParameter> healthparam=null;
// to store the value in database.
#RequestMapping(value="/addHealthParam.do",method=RequestMethod.POST)
public String addHealthParam(#ModelAttribute("addhealthparam")HealthParamMVC addhealthparam,BindingResult result,HttpSession session){
// code to store the value in database
}
// execute through ajax call
#RequestMapping(value="/getparamfromdb.do",method=RequestMethod.POST)
public String gettingParam(#ModelAttribute("addhealthparam")
HealthParamMVC addhealthparam,BindingResult result,
HttpServletRequest req,HttpSession session){
System.out.println("In gettingParam ");
String name=addhealthparam.getName();
List<ParameterFromDB> li=service.getParamfromDb(name);
// further getting value from database based on name.
Iterator it=li.iterator();
while(it.hasNext()){
Object ob=it.next();
ParameterFromDB db= (ParameterFromDB) ob;
}
session.setAttribute("paramvalue", li);
// i have tried it with request also
//request.setAttribute("paramvalue", li);
return "userdetails";
}
}
Here is some modify code. please check and let me know it's working or not.
<html>
<head>
</head>
<body>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".name").change(function(){
var name = $(this).val();
if(name.length >= 1){
$(".status").html("<font color=gray> Checking availability...</font>");
$.ajax({
type: "POST",
url: "getparamfromdb.do",
data: "name="+name,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
var json = eval(msg);
$(".status").html(msg);
var minRange = json.MINRANGE;
vat maxRange = json.MAXRANGE;
$('#minrange').val(minRange);
$('#maxRange').val(maxRange);
});
}
});
}
else{
$(".status").html("<font color=red>Username should be atleast <b>5</b> character long.</font>");
}
});
});
</script>
<div class="add">
<form:form method="post" action="addHealthParam.do" >
<table style="margin-top:-6%; margin-left:8%;">
Parameter Name:<br>
<select name="name" class="name">
<option value="select">Select</option>
<option value="Glucose, Serum">Glucose, Serum</option>
<option value="Uric Acid, Serum">Uric Acid, Serum</option>
<option value="Platelets">Platelets</option>
<option value="NRBC">NRBC</option>
</select>
Parameter Current Reading:
<input type="text" name="current_reading"/>
Unit of Measurement:
<select name="measurementunit" >
<option>
<c:forEach var="healthp" items="${paramvalue}">
${healthp.measurementunit}
</c:forEach>
</option>
</select>
Reference Range(Minimum):
<input type="text" id="minrange" value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.minrange}
</c:forEach>" >
Reference Range(Maximum):<br>
<input type="text" id="maxrange"
value="
<c:forEach var="healthp" items="${paramvalue}">
${healthp.maxrange}
</c:forEach>">
<input type="submit" value="Submit"/>
</body>
</html>
i use response object here. you need to get that.
imports are here
#Controller
#SessionAttributes
public class HealthParameterController {
#Autowired
BharatService service;
#Autowired
HibernateTemplate hibernateTemp;
List<HealthParameter> healthparam=null;
// to store the value in database.
#RequestMapping(value="/addHealthParam.do",method=RequestMethod.POST)
public String addHealthParam(#ModelAttribute("addhealthparam")HealthParamMVC addhealthparam,BindingResult result,HttpSession session){
// code to store the value in database
}
// execute through ajax call
#RequestMapping(value="/getparamfromdb.do",method=RequestMethod.POST)
public String gettingParam(#ModelAttribute("addhealthparam")
HealthParamMVC addhealthparam,BindingResult result,
HttpServletRequest req,HttpSession session){
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
System.out.println("In gettingParam ");
String name=addhealthparam.getName();
List<ParameterFromDB> li=service.getParamfromDb(name);
// further getting value from database based on name.
Iterator it=li.iterator();
while(it.hasNext()){
Object ob=it.next();
ParameterFromDB db= (ParameterFromDB) ob;
String minRange = ""; // Create what you want to display in Minrange Text Box
String maxRange = ""; // Create what you want to display in Maxrange Text Box
}
json.put("MINRANGE",minRange);
json.put("MAXRANGE",maxRange);
//Get a RESPONCE object here.
PrintWriter out = response.getWriter();
out.print(json.toString());
session.setAttribute("paramvalue", li);
// i have tried it with request also
//request.setAttribute("paramvalue", li);
return "userdetails";
}
}

Dynamically creating a checkbox from an Array list java

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>

JSP not returing result with drop down menu

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>

Categories

Resources