Display query in jsp using html - html

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.

Related

How to pass parameter to Java using HTML

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.

Error With JSP search

Okay I have a huge problem with this. I have spend hours with my group trying to solve this small problem we have on the group project and cant find the answer
I either get null pointer exeption or something with org.apache.jasper.jasperexception or the most common ones is the try with out catch or finally where I use try and catch ..
Please help me o
Form for team name
<body>
<h2>Search Team</h2>
<form action="searchteam.jsp" method="post">
<table border="0">
<tr>
<td>Team Name</td>
<td><input type="text" name="tm"/> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Search"/>
</td>
</tr>
</table>
</form>
</body>
and this here is the searchteam.jsp
<%#page import="livescore_pack.*"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="bean" class="livescore_pack.Accessor" scope="session"/>
<%
String team = request.getParameter("tm");
Team me = bean.getTeams(team);
if(me == null)
response.sendRedirect("index.jsp");
else {
session.setAttribute("tm", me);
response.sendRedirect("doSearchTeam.jsp");
}
%>
and the dosearchteam.jsp
<%#page import="livescore_pack.Team"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<jsp:useBean id="bean" class="livescore_pack.Accessor" scope="session"/>
<%
String me = request.getParameter("tm");
Team tm =(Team) session.getAttribute("tm");
if(me == null)
response.sendRedirect("index.jsp");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link rel="stylesheet" type="text/css" href="st1.css">
</head>
<body>
<div id="menu">
</div>
<div id="main">
<%
Team team = bean.getTeams(tm.getTm_name()); //dame eshi null
%>
<b> <%= tm.getTm_name() %> </b>
for <%= tm.getCountry_pk() %>
<p> <%= tm.getFounded()%> </p>
<p> <%= tm.getStadium() %> </p>
<p> <%= tm.getManager()%> </p>
<p> <%= tm.getLeagues() %> </p>
<p> <%= tm.getCups() %> </p>
<%
}
%>
</div>
</body>
</html>
and also the part getTeams in our accessor .java
public Team getTeams(String tm_name) {
try{
Connection cn = getGetDATABASE().getConnection();
String sql = "SELECT * FROM Team WHERE tm_name = ? ";
PreparedStatement pst = cn.prepareStatement(sql);
pst.setString(1, tm_name);
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Team tm = new Team();
tm.setTm_pk(rs.getLong("team_id"));
tm.setCountry_pk(rs.getLong("country_id"));
tm.setTm_name(rs.getString("tm_name"));
tm.setFounded(rs.getLong("founded"));
tm.setStadium(rs.getString("stadium"));
tm.setManager(rs.getString("manager"));
tm.setLeagues(rs.getInt("leagues"));
tm.setCups(rs.getInt("cups"));
return tm;
}
}
catch(Exception e) {
String msg = e.getMessage();
}
return null;
}
Your try catch statement has the wrong syntax. it has an extra } before the catch block try deleting that. If that fails and you are still getting errors can you paste in a copy of the jasper exception that is returned
Also as far as i can see you are calling getTeams() twice with the same name. Once in searchteam.jsp and the second time in dosearchteams.jsp. You have set all the variables in serachteam.jsp you do not need to call it again in dosearchteams.jsp this appears to be a redundant call.
Okay sorry for the delaid answer
I have fixed my problem it seems i was connecting to a wrong part of the database.
once that was fixed the problem was solved.

Displaying Logged In User Specific data from MYSQL using JSP

I have run into a problem where I have to display certain data that is present in the Ratings table of MYSQL depending upon the user that is logged in.
The heirarchy is as below :
login.jsp --> check.jsp --> welcome.jsp
I have to display data on Welcome.jsp depending on the user who is logged in. I am unable to get the user parameter to server as an input for the sql query that displays the user specific data. Here are my files.
login.jsp
<%--
Document : login
Created on : May 15, 2012, 10:36:24 AM
Author : Diaa
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<script>
function validate(){
var username=document.form.user.value;
var password=document.form.pass.value;
if(username==""){
alert("Enter Username!");
return false;
}
if(password==""){
alert("Enter Password!");
return false;
}
return true;
}
</script>
<div align="center">
<div class='cssmenu'>
<ul>
<li class='active '><a href='index.jsp'><span>Home</span></a></li>
<li><a href='login.jsp'><span>Login</span></a></li>
<li><a href='index.jsp'><span>About</span></a></li>
<li><a href='#'><span>Contact</span></a></li>
</ul>
</div>
<form name="form" method="post" action="check.jsp" onsubmit="javascript:return validate();">
<div align="center">
<h1>USER LOGIN</h1>
<table>
<tr><td bgcolor="#FF9900">Username:</td><td bgcolor="#33CCCC"><input type="text" name="user"></td></tr>
<tr><td bgcolor="#FF9900">Password:</td><td bgcolor="#33CCCC"><input type="password" name="pass"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</div>
check.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%#page import="java.sql.*"%>
<%
String user=request.getParameter("user");
String pass=request.getParameter("pass");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/recommend","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select UserID,password from Users where UserID='"+user+"' and password='"+pass+"'");
int count=0;
while(rs.next())
{
count++;
}
if(count>0)
{
out.println("welcome "+user);
response.sendRedirect("welcome.jsp?msg=welcome "+user +" logout");
session.removeAttribute("user");
}
else
{
response.sendRedirect("login.jsp?msg=Invalid Username or Password");
}
%>
welcome.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%-- Database Interaction Queries Start --%>
<% String user=(String)session.getAttribute(user); %>
<sql:setDataSource var="genretype" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/recommend"
user="root" password="root"/>
<sql:query dataSource="${genretype}" var="result">
SELECT * from Genres;
</sql:query>
<sql:query dataSource="${genretype}" var="result1">
SELECT * from Ratings where UserID = ?
<sql:param value="${user}"/>
</sql:query>
<%-- Database Interaction Queries End --%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Heading</title>
</head>
<body>
<div align="center">
<div class='cssmenu'>
<ul>
<li class='active '><a href='index.jsp'><span>Home</span></a></li>
<li><a href='login.jsp'><span>Login</span></a></li>
<li><a href='index.jsp'><span>About</span></a></li>
<li><a href='#'><span>Contact</span></a></li>
</ul>
</div>
<%String msg=request.getParameter("msg");
if(msg!=null){
%>
<label><font color="red"><%=msg%></font></label>
<%
}
%>
<h1>Sample Title</h1>
<%--For Displaying Genre List Start --%>
<div>
<div align="left" position:absolute left:1200px>
<c:forEach var="row" items="${result.rows}">
<ul id="tab_nav">
<li><c:out value="${row.GenreName}"/></li>
</ul>
</c:forEach>
</div>
<div id="box" >
<table border="1">
<c:forEach var="row" items="${result1.rows}">
<tr>
<td><c:out value="${row.Rating}"/></td>
<td><c:out value="${row.UserID}"/></td>
<td><c:out value="${row.GenreName}"/></td>
<td><c:out value="${row.MovieName}"/></td>
</tr>
</c:forEach>
</table>
</div>
</div>
</body>
</html>
Can anyone please look into this and let me know what I am missing here :( Please feel free to ask back any other information apart from the code posted.
Fingers Crossed.. Awaiting for help!!
Cheers!
You cannot append HTML to the URL parameter of your sendRedirect() method call. There could be encoding issues with it and so it may be failing:
response.sendRedirect("welcome.jsp?msg=welcome "+user +" logout");
This should simply be
response.sendRedirect("welcome.jsp?user=" + user);
with the message being constructed in the JSP as
<c:if test="${not empty user}">
<label><font color="red">Welcome ${user}</font></label><br />
logout
</c:if>
If this doesn't solve the issue please update your question with how's the application behaving. Do you see any errors? Are you logging the exceptions anywhere?
I did a sample code here for you to check out.
Here is a sample login.jsp form:
<form action="check.jsp" method="post">
<table border="0">
<tr>
<input type="text" name="user" id="user"/>
</tr>
<tr>
<input type="password" name="pass" id="pass"/>
</tr>
<td>
<input type="submit" id="submit"/>
</td>
</table>
</form>
Then,the check.jsp could look this way:
<%#page import="java.sql.*" %>
<%
Connection con;
ResultSet rs;
PreparedStatement ps;
String query;
String user = request.getParameter("user");
String pass = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/recommend","root","root");
query = "select userID,password from Users where userID='"+user+"' and password='"+pass+"'";
ps = con.prepareStatement(query);
//ps.setString(1,request.getParameter("user"));
//ps.setString(1,request.getParameter("pass"));
rs = ps.executeQuery();
if(rs.next()){
session.setAttribute("user", user);
%>
<jsp:forward page="welcome.jsp"/>
<%
}else{
response.sendRedirect("login.jsp");
}
}catch(Exception e){
out.println(e);
}
%>
from the code above,you can see that after the querying of the database the attribute of the user is set and also the check.jsp forward that to the welcome.jsp page with that attribute of the user that has been set,else if the user or password is Incorrect,the person is being redirected to the login.jsp page.
The welcome.jsp page looks this way:
<body>
<% String user = (String)session.getAttribute("user");%>
<% if(user == null){
response.sendRedirect("login.jsp");
}else{
out.println("Welcome "+user);
}
%>
</body>
In the welcome.jsp page,it retrieves the session attribute of the user that is logged in via the session.getAttribute() method.It then checks if the session attribute is null and then redirects back to the user,else it prints Welcome + the user.Note that the user being printed is from the session.getAttribute which is gotten from the session.setAttribute in the check.jsp,that way you are able to get the user parameter as input from the login. I hope this helps.

Fetch Multiple Records from Mysql Database Using Where Clause

Im using a web application ,which runs on Apache Tomcat and has Mysql Database as backend
I want to retrieve multiple rows for a particular column usin the Where clause
For Example If I give select * from xyz where type=abc
I should get all the rows having type abc.
Problem:
I use the JDBC connection to achieve this, however Only the 1st row matching the where condition is returned rather than all the rows (even though multiple rows match the criteria in database)
Kindly help me resolve this
Code:
<%# page import="java.sql.*" %>
<html>
<head><link href="style.css" rel ="stylesheet" type="text/css"></head>
<body bgcolor="white" >
<div id="container">
<div id="header">
<img src="logo.jpg">
<div class ="horiztext"><p> Order Tracker</p></div>
</div>
</div>
<br>
<img src="banner.jpg" width="1500 " height="5"><br>
<% if(session.getAttribute("username") !=null)
{
%>
<div id="navbar">
<ul>
<li>New Order</li>
<li>Update Order</li>
<li>Track Order</li>
<li>Track Delay</li>
<li>View Database</li>
<li>Delete Order</li>
<li>Logout</li>
</ul>
</div>
<br>
<br>
<form>
<TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">
<%
String ProductNamez=request.getParameter("ProductName");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3307
/test","root", "root");
Statement st=conn.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM inventory WHERE ProductName = '"+
ProductNamez +"' ");
if(rs.next()){
%>
<tr>
<tr><th>Serial No</th>
<th>Product Name</th>
<th>Product Type</th>
<th>Model</th>
<th>Make</th>
<th>License / Voucher</th>
<th>Location</th>
</tr>
<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>
<%
}
%>
</table>
</form>
<%
}
else { %>
you are not logged in click here to <b>login</b>
<%
} %>
</body>
</html>
You'll be wanting
while (rs.next()){
instead of
if (rs.next()){
It's because you just do a if(rs.next()){ so only the first row is shown.
You should do this instead
while (rs.next()) {
[...]
}

passing data from jsp to servlet from html table

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