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.
Related
I am displaying data is a jsp page from "resultset.getString("column_name")" attribute which works fine for my columns.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%# page import="java.sql.*"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.servlet.ServletOutputStream"%>
<style>
th, td {
padding: 15px;
}
</style>
<%
String id = request.getParameter("name");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "employee";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String iurl1=null;
Blob employee_dp=null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<h2 align="center"><font><strong>Retrieve data from database in jsp</strong></font></h2>
<%
try {
connection = DriverManager.getConnection(connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT * FROM employee_details where ID='" + session.getAttribute("ID") + "'";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<table border="0" class="display" >
<tbody>
<tr>
<td>ID : </td>
<td><%=resultSet.getString("ID")%></td>
</tr>
<tr>
<td>First Name : </td>
<td><%=resultSet.getString("name")%></td>
</tr>
<tr>
<td>Last Name : </td>
<td><%=resultSet.getString("Last_Name")%></td>
</tr>
<tr>
<td>D.O.B. : </td>
<td><%=resultSet.getString("DOB")%></td>
</tr>
<tr>
<td>image : </td>
<td><img alt="Smiley face" src="<%=resultSet.getString("employee_dp") %>" width="500" height="500"/></td>
</tr>
<tr>
<td>Attach address proof </td>
<td> <input type="file" name="txtfile"> </td>
</tr>
</tbody>
</table>
<%}}
catch (Exception e) {
out.println("DB problem");
return;
}
finally {
try {
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
%>
Here is the code for my jsp displaying page.
Driver code to this is a basic login page which redirects to my this jsp page.
I changed the code a bit and tuned it to see if my image is available or not.
I tried by just giving the direct destination under "src" tag , it worked but when i retrieve it through resultSet.getString(column_name) it shows bits of symbols.
If i use .getBlob I get a empty image box
If i use .getString I get a lot of symbols
I want to retrieve data from database, where username = entered by the user during login.
Username is entered by user in html
But I am getting error as: Exception occurred when flushing data] with root cause
java.io.IOException: Stream closed.
Exception occurred when flushing data] with root cause
Stream closed.
my jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Student Details</title>
</head>
<body>
<%
String uname= request.getParameter("UserName");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vikas","root","rass");
PreparedStatement ps=con.prepareStatement("select * from Student_Data where UserName="+uname);
ResultSet rs = ps.executeQuery();
%>
<table rules="all" border="">
<%
while (rs.next()) {
%>
<tr>
<td>FirstName: </td><td><%out.println(rs.getString(1));%></td></tr>
<td>LastName: </td><td><%out.println(rs.getString(2));%></td></tr>
<tr><td>UserName: </td><td><%out.println(rs.getString(3));%></td></tr>
<tr><td>Password: </td><td><%out.println(rs.getString(4));%></td></tr>
<tr><td>DateOfBirth: </td><td><%out.println(rs.getString(5));%></td></tr>
<tr><td>E-Mail</td><td><%out.println(rs.getString(6));%></td></tr>
<tr><td>Mobile.No</td><td><%out.println(rs.getString(7));%></td></tr>
<tr><td>Gender</td><td><%out.println(rs.getString(8));%></td></tr>
<tr><td>Address</td><td><%out.println(rs.getString(9));%></td></tr>
<tr><td>City</td><td><%out.println(rs.getString(10));%></td></tr>
<tr><td>PinCode</td><td><%out.println(rs.getString(11));%></td></tr>
<tr><td>State</td><td><%out.println(rs.getString(12));%></td></tr>
<tr><td>Country</td><td><%out.println(rs.getString(13));%></td></tr>
<tr>
<td>Hobbies</td>
<td><%out.println(rs.getString(14));%> </td>
</tr>
<tr>
<td>Qualification</td><td>Sl.No</td><td>Examination</td><td>Board</td><td>Percentage</td><td>Year of Passing</td>
</tr>
<tr>
<td></td><td>1</td><td>Class X</td><td><%out.println(rs.getString(15));%></td><td><%out.println(rs.getString(16));%></td><td><%out.println(rs.getString(17));%></td>
</tr>
<tr>
<td></td><td>2</td><td>Class XII</td><td><%out.println(rs.getString(18));%></td><td><%out.println(rs.getString(19));%></td><td><%out.println(rs.getString(20));%></td>
</tr>
<tr>
<td></td><td>3</td><td>Graduation</td><td><%out.println(rs.getString(21));%></td><td><%out.println(rs.getString(22));%></td><td><%out.println(rs.getString(23));%></td>
</tr>
<tr>
<td>Course Applied</td><td><%out.println(rs.getString(24));%>
</td>
</tr>
</table>
<%
}
}
catch(Exception e)
{
System.out.println(e);
}
out.close();
%>
</body>
</html>
You should not invoke out.close in your jsp page,jsp will do it for you
So just remove below code:
<%
}
}
//remove below code
catch(Exception e)
{
System.out.println(e);
}
out.close();
%>
For your query sql,since you have use PreparedStatement ,so you need pass parameter like ps.setString() instead of write in the sql directly,so change to below:
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vikas","root","rass");
PreparedStatement ps=con.prepareStatement("select * from Student_Data where UserName=?");
ps.setString(1,uname);
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.
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.
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.