I am new to Java and programming in general. For background, I am working on my simple survey system. I have all the classes/methods necessary to insert and pull from MySQL and display the survey on my JSP page.
This is my Index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Survey System</title>
</head>
<body>
<h1>Survey List</h1>
<%
ResultSet resultset = new controller.SelectSurvey().SelectSurvey();
if (request.getParameter("btnControlSurvey") != null){
response.sendRedirect("controlsurvey.jsp");
}
if (request.getParameter("btnTakeSurvey") != null){
response.sendRedirect("takesurvey.jsp");
}
%>
<form name = 'surveylist' action="index.jsp" method="POST">
<table border="0">
<thead>
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select id="listsurvey">
<% while (resultset.next()) {
%>
<option><%= resultset.getString("survey_ID")%> - <%= resultset.getString("title")%></option>
<% } %>
</select>
</td>
<td>
<input type="submit" value="TAKE SURVEY" name = "btnTakeSurvey" />
</td>
</tr>
</tbody>
<td>
<input type="submit" value="CONTROL SURVEY" name = "btnControlSurvey" />
</td>
</table>
</form>
</body>
How do I pass the selected surveyID value in my drop down list with ID listsurvey to my hard-coded surveyID1 variable in my Takesurvey.jsp (see below) once the Submit button is clicked?
<%
int surveyID1 = 1;
ResultSet rsSurvey = new controller.SelectSurvey().SelectSurveyByID(surveyID1);
ResultSet rsSurveyQuestion = new controller.SelectSurvey().SelectQuestionByID(surveyID1);
%>
I found that there are at least three ways to do this as listed below. What would be the easiest way and would you please give me an example?
Putting values into the session object.
Putting values into the application object
Putting values at the end of the redirect URL.
Your inputs are very appreciated.
Thank you and have a good day.
Not sure what you're doing in that 2nd code segment, but you can get a hold of the form parameters using
String surveyId = request.getParameter(listsurvey);
It looks like you're looking for an int on the other side, but it comes in as a String so just use Integer.parseInt() after you pull it from the request.
Note: The request variable is already implicitly available in your JSP. You don't have to declare it.
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameter%28java.lang.String%29
You need to pass the surveyID in the HTTP page request using either GET or POST. Then in the servlet / JSP you can use request.getParameter("surveyID")
I figured it out by using request.getParameters and use different forms for each button and it works as wanted.
Thank you for all of yours input again guys.
Related
I have made a certain form with a table layout
the table is kind of like this below:
UAN NAME DESIGNATION No. of Days Present
87982 JOHN SALESMAN 25
now, the columns uan name and designation are already given (taken from the database) and the user only needs to put in the attendance.
the number of days will then be inserted into the database
in the row where UAN = 87892
The problem is that I am unable to figure out how to get the value of UAN from the page and use it to enter the number of days in the database.
could you give some idea how to accomplish this using nodejs??
I am using the ejs templating system and mysql database.
that's not the only problem.
I also want to enter the number of days present for all the different employees
where the number of days gets added to the row with their UAN number.
how am I supposed to do that?
any ideas??
here's the code for the attendance page
<!DOCTYPE HTML>
<html>
<head><title>attendance for employees</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<table>
<tr>
<th>Serial No.</th>
<th>UAN</th>
<th>Name</th>
<th>Designation</th>
<th>Attendance</th>
</tr>
<form action="/attendance-data" method="post">
<% var i=0 %>
<% rows.forEach(function(item){ %>
<% i=i+1 %>
<tr>
<td><%= i+"." %></td>
<td id="uan<%= i %>"> <%= item.uan %> </td>
<td><%= item.name %></td>
<td><%= item.designation %></td>
<td><input type="text" name="attendance <%= i %>" ></td>
</tr>
<% }); %>
</form>
</table>
</div>
<div>
<input type="button" value="submit" />
</div>
</body>
</html>
In order to get the data from the page and insert it into your database:
WHERE uan = '[data_from_html]', you will need to reference it by name. This can be accomplished when the user enters into the form how many days of attendance. The biggest issue you will have is that forms are tough to get working in correspondence to a table. You can put an entire table inside of a form but not the other way around necessarily.
Inside of your last td tag it would be best to place the entire form there with only one field visible and the rest hidden(you can still display as you were, just leave the other fields out of the form:
<td>
<form action='/attendance-data' method='post'>
<input type='hidden' id='uan<%= i %>' name='attendance' value ='<%= i %>'/>
<input type='hidden' name='item_name' value ='<%= i %>'/>
<input type='hidden' name='designation' value ='<%= item.designation %>'/>
<input type='text' name='attendance' value ='<%= i %>'/>
<input type="submit" value="Submit" />
</form>
</td>
Then inside of your routes in express:
app.post('/attendance-data', function(req, res) {
var uan = req.body.uan
var item_name = req.body.item_name
var designation = req.body.designation
var attendance = req.body.attendance
// Make sure they all contain some sort of value
var connString = new ConnectionString(
config.mysql.host,
config.mysql.port,
config.mysql.username,
config.mysql.password,
config.mysql.default_db
)
var MySqlConn = new MySqlConnection(connString)
// Proceed to do an update/insert into your db
MySqlConn.Connection.query("insert into [your_table] " +
"values(uan, item_name, designation, attendance) where uan='" + uan + "'",
function (err)
{
if (err)
{
console.log(err.stack)
throw err
}
// Otherwise success
res.status(200).send('blah')
})
}
How can I get/set checkbox value using jstl and delete only those record from the database where the checkbox is checked? can you also advise how to use ternary operators in jstl for this scenario?
SearchStudent.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Lookup Students</title>
</head>
<form method="post" action="deleteStudentServlet" class="form">
<body class="body">
<!-- List results -->
<c:if test="${not empty studentList}">
<table border="1" cellspacing="0" cellpadding="0" :>
<tr>
<th></th>
<th>ID</th>
<th>Title</th>
<th>First Name</th>
<th>Last Name</th>
<th></th>
</tr>
<c:forEach var="students" items="${studentList}">
<tr>
<td><input type="checkbox" name="chkBox"> </td>
<td>${students.studentID}</td>
<td>${students.title}</td>
<td>${students.firstName}</td>
<td>${students.lastName}</td>
<td><c:url value="UDS" var="url">
<c:param name="StudentID" value="${students.studentID}" />
</c:url> Edit</td>
</tr>
</c:forEach>
</table>
</c:if>
<td><input type="submit" name="submit" value="Delete" ></td>
</form>
<p>There are ${fn:length(studentList)} results.</p>
</body>
</html>
thanks.
Your checkbox has currently no value associated with the parameter name at all:
<input type="checkbox" name="chkBox">
So it's hard to find out the checked ones. You need to give the checkbox a value which uniquely identifies the selected item. In your particular example, the student ID seems to be an obvious choice:
<input type="checkbox" name="selected" value="${student.studentID}">
(by the way, why are you duplicating the entity name in the property name? why not just name it id so that you can just self-documentary use ${student.id}? also your var="students" is kind of odd, it is referring only one student, so just name it var="student"; the ${studentList} can better be named ${students})
When the form is submitted, all checked value are available as follows:
String[] selectedStudentIds = request.getParameterValues("selected");
Finally, just pass it through to your DAO/service class which does the business job:
studentService.delete(selectedStudentIds);
See also:
How to transfer data from JSP to servlet when submitting HTML form
ServletRequest.getParameterMap() returns Map<String, String[]> and ServletRequest.getParameter() returns String?
Send an Array with an HTTP Get
this may help you.
In ajax call:
var boolValue= $(this).closest(".tr").find('.checkboxClass').is(':checked');
$.post("/api/dosomething", {
someSettings : boolValue
})
How do I go about displaying the results of a query from MYSQL in a jsp using html tags? My instructor said to do the query in the .jsp file and use html tags to display the results. What is the correct syntax for this. Can I get an example or a link to a page that will show me. I have no problem writing the query, just unsure about the jsp/html display. Thanks
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>
in jsp we have scriptlet tags ( <% %> ).you can use the jdbc statements between these jsp tags, The below sample code shows the display query in jsp using html,
<%#page import="java.sql.*,java.util.*,java.io.*"%>
<html>
<head>
<body background="1.jpg">
<title>ehealthcare advisor</title>
</head>
<body><center>
<h1><center>E-HEALTH CARE ADVISOR</center></h1>
<h4><center>get best solutions in minuites...</center></h4>
<table border="0" cellspacing="50" cell padding="10">
<tr>
<td> HOME</td>
<td> LOGOUT</td>
<td>ABOUT US</td>
</table>
</center>
<center>
<h2>PATIENT LIST</h2>
<table border="1" width="40%">
<thead>
<th>UserId</th>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
<th>Occupation</th>
<th>Height</th>
<th>Weight</th>
</thead>
<tbody>
<%
Statement st = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/ehealthcare","root","root");
st = con.createStatement();
String qry ="select * from user";
rs = st.executeQuery(qry);
while(rs.next()){ %>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
<td><%=rs.getString(6)%></td>
<td><%=rs.getString(7)%></td>
</tr>
<%
}
con.close();
st.close();
}
catch(Exception ex){
out.println(ex);
}
%>
</tbody>
</table>
</body>
</html>
Here I give the link you refer it.
Jsp Sample Database Access, it is like core java
Jsp using JSTL tags
Database from Jsp
If you use No. 2 . Jsp using JSTL tags, that will be good programming.
JSTL tags are simple to learn.
I have aproblem. Here I am showing some bills from Invoice table in mysql. And for single bill I am keeping a checkbox. I want to pass selected checkbox values to next jsp page. Please help me to do it. Thanks in advance.
<%
String company_name=request.getParameter("c_name");
try
{
Integer count=0;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","aadi");
Statement st = con.createStatement();
String sql="select invoice_no, invoice_date, gross_amount from tbl_invoice where client='"+company_name+"'";
ResultSet rs=st.executeQuery(sql);
%>
<center>
<table id="show_table">
<tr>
<td>PNR No</td>
<th>Date</td>
<th>Amount</td>
<th>Select</td>
</tr>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getInt(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getInt(3)%></td>
<td><input type="checkbox" name="ck"/></td>
</tr>
%>
</table>
</center>
<%
}
catch(Exception e)
{
out.println(e);
}
%>
Hey I found the solution. On action page where I am going to receive values I will store all checkbox names in a array of string.
String selected_Checkboxes=request.getParameterValues("ck");
I will just change "td" tag of checkbox. I will put value of PNR NO which is coming from database and will put in checkbox.
<td><input type="checkbox" value="<%=rs.getInt(1)%>" name="ck"/></td>
I will use indexes of "selected_Checkboxes" to do further coding.
--Thanks Santino 'Sonny' Coleone
I am developing a web application using JSP and Servlets.
In that application I have to show data from database table stud(studID, name, add) in html table, And each row in the table will have a hyperlink associated with it at the last column. After clicking on that hyperlink I wants to get the (studID) from the table...
so far I have done getting the data from database and then putting it into the column and then adding hyperlink for each row.. But I am not able to get the (studID) from the html table associated with hyperlink..
Thanks in advance....
Source code :
<%
String[][] data = (String[][])request.getAttribute("data");
String[] cNames = (String[])request.getAttribute("columnNames");
//headings
%>
<table>
<tr>
<%
for(int i=0;i<cNames.length;i++) {
%>
<th>
<%= cNames[i] %>
</th>
<%
}
//data if(data!=null)
for(int i=0;i<data.length;i++) {
%>
<tr>
<%
for(int a=0;a<3;a++) {
%>
<td>
<%=
data[i][a]
%>
</td>
<%
//hyperlink
if(a==2) {
%>
<td>
<a href="PlanProtocol" id=<%=i%> onclick="<% session.setAttribute("ID","p2"); %>" >Edit</a></td>
<%
}
}
%>
</tr>
<% } %>
<tr>
</table>
You can pass the id as a query string in the url. Simply:
My Link
Will work. But if you are using JSTL or another tag library then you can do something like this:
<c:url value="/myservlet" var="myURL">
<c:param name="id" value="1234"/>
</c:url>
mylink
And this has its advantages such as url encoding etc.
So to add the id to the URL in your posted code you can:
<a href="PlanProtocol?id=<%=i%>" >Edit</a>
And the url will end up like this: PlanProtocol?id=1234.
In the Servlet you can get the Parameter by:
request.getParameter("i");
However, as I mentioned above, you probably want to use a tag library like the JSTL rather than placing these scriptlets in your page. There are several advantages.
think you should pull out the studID in JSP and format the studID into the query string of the URL, html page. (?studID=xxxxx) So the servlet will know the studID.
You can use request.setAttribute("studID","value"); in your jsp page to set the value and use request.getAttribute("studID"); in servlet to get value