I've made a login script in JSP. It's working fine but the problem as i use
<%=session.getAttribute("first_name")%> it shows Null. Can you please tell me what's wrong here?
Main.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
if ((session.getAttribute("user_email") == null) || (session.getAttribute("user_email") == "")) {
response.sendRedirect("login.jsp");
%>
<%} else
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to the job seeker forum.</title>
<link rel="stylesheet" type="text/css" href="CSS_styles/forum_style.css"/>
<link rel='stylesheet' id='open-sans-css' href='//fonts.googleapis.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&subset=latin%2Clatin-ext&ver=4.1-alpha-20141011' type='text/css' media='all' />
<link href='http://fonts.googleapis.com/css?family=Londrina+Solid|Exo:800|Open+Sans:300italic,400,300,600|Roboto:400,100,300,500,700' rel='stylesheet' type='text/css' />
</head>
<body>
<div id="forum">
<h1><b>Welcome <%=session.getAttribute("first_name")%></b>,<br>to Job seeker forum, there are many openings that you can get through here. <a href='logout.jsp'>logout</a></h1>
<form id="forum_form" method="post">
</form>
</div><br><br><br>
<div id="forum2">
<h1 style="text-align: center;">Want to post on going walking,<br>Post your job description here.</h1>
<form id="forum2_form" method="post">
<p>
<label>Job title:</label>
<input type="text" class="" placeholder="e.g XXX Referral program for freshers."/>
</p>
<p>
<label>Your Question:</label>
<textarea class="question_ask_style" rows="3" cols="40" placeholder="Type description here.."></textarea>
</p>
<div id="submit_btn">
<input type="submit" value="Submit Question" />
</div>
</form>
</div>
</body>
</html>
Here is login_process.jsp
<%# page import="java.sql.*" %>
<%
String user_email=request.getParameter("user_email");
String user_password=request.getParameter("user_password");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888/login", "root", "1234");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("select * from members where email='"+user_email+"' and password='"+user_password+"'");
if(rs.next()){
session.setAttribute("user_email", user_email);
response.sendRedirect("main.jsp");
}else{
out.println("Invalid Password... Try again.. <a href='login.jsp'>login</a>");
}
%>
Here is my created database table:
create table `members`(
`id` int(10) unsigned NOT NULL auto_increment,
`email` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
PRIMARY KEY(`id`)
)ENGINE= InnoDB default charset=latin1;
This is what i'm getting error...
SCREENSHOT:
http://i.stack.imgur.com/AuF5M.png
<%=session.getAttribute("first_name")%> shows null because you have not set the first_name in the session.
You have set the only the user_email.
if(rs.next()){
String user_email=rs.getString("first_name");
session.setAttribute("user_email", user_email);
response.sendRedirect("main.jsp");
you can set like the above
P.S
Scriptlets are discouraged over the decades , so it is advised to use EL instead of them . You can simply use , ${sessionScope.user_email} to print it out in the jsp page
In login_process.jsp use <%=session.setAttribute("first_name",first_name)%> and then access it.
eg:
rs=st.executeQuery("select * from members where email='"+user_email+"' and password='"+user_password+"'");
if(rs.next()){
session.setAttribute("first_name", rs.getString("first_name"));//set first_name in session
session.setAttribute("user_email", user_email);
response.sendRedirect("main.jsp");
}
Try this
if(rs.next()){
session.setAttribute("user_email", user_email);
session.setAttribute("first_name", rs.getString(4));//Add this line to your code
response.sendRedirect("main.jsp");
}
Here 4 is column number for first_name
in login_process.jsp set
session.setAttribute("user_email", user_email);
to
session.setAttribute("first_name", rs.getString("first_name"));
because you have set the attribute name user_email and getting first_name from session.
Related
This is my current JSP code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="user" class= "uts.wsd.User" scope="session" ></jsp:useBean>
<%
String name = request.getParameter("name");
String email = request.getParameter("email");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String color = request.getParameter("favcol");
user.setName(name);
user.setEmail(email);
user.setPassword(password);
user.setGender(gender);
user.setFavouriteColour(color);
%>
<body style="background: <%= color %>;">
<% if (request.getParameter("tos") == null ) {%>
<p>
Sorry, you must agree to the Terms of Service.</p>
<p>Click <a href="register.jsp" > here </a> to go back.
</p>
<%} else { %>
<jsp:forward page="index.jsp" />
<% } %>
</html>
Here I use jsp:forward page="index.jsp" to redirect to index.jsp page. Then, if I want to use response.sendRedirect("index.jsp")? How can I proceed?
I tried this:
<% if (request.getParameter("tos") == null ) {%>
<p>
Sorry, you must agree to the Terms of Service.</p>
<p>Click <a href="register.jsp" > here </a> to go back.
</p>
<%} else { %>
<response.sendRedirect("index.jsp")>
<% } %>
</html>
But it failed. Please help! Thank you!!
response.sendRedirect() is Java code not a tag, so you should not close the scriptlet tags before typing it, and it is not to be preceded by < and closed with >...its just Java code:
<%
}
else
{
response.sendRedirect("index.jsp");
return; //this is to redirect immediately so it doesn't
//run any code below this point before redirecting
}
%>
I tried looking for help on the web to solve my problem but to no avail. I wish to convert verify[] to int, so it can be processed in the query.
verified column has a data type of string
staff_id column has a data type of autonumber
I'm getting an error of
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Data type mismatch in criteria expression.
VerifyStaff.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Verification of Staff Accounts</title>
</head>
<body>
<div align="center">
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Retrieving Staff Accounts - Reading --%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
String query = "select staff_id, username, password, user_group, verified from Staff";
ResultSet rs = st.executeQuery(query);
%>
<form action="VerifyStaffAuth.jsp">
<table width="200" border="1">
<tr>
<td>Staff_ID</td>
<td>Username</td>
<td>Password</td>
<td>User Group</td>
<td>Verified?</td>
<td>Verify/Un-verify</td>
</tr>
<%
while(rs.next()){
int staff = rs.getInt("staff_id");
%>
<tr>
<td><%= staff %></td>
<td><%= rs.getString("username") %></td>
<td><%= rs.getString("password") %></td>
<td><%= rs.getString("user_group") %></td>
<td><%= rs.getString("verified") %></td>
<td><label>
<input type="checkbox" name="CheckboxGroup" value="<%= staff %>">
</label></td>
</tr>
<%
}
rs.close();
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</table>
<input type="submit" VALUE="submit">
</form>
</div>
</body>
</html>
VerifyStaffAuth.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0"); %>
<% String[] verify = request.getParameterValues("CheckboxGroup");
int[] verify2 = new int[verify.length];
for(int i=0;i<verify.length;i++){
verify2[i]=Integer.parseInt(verify[i]);
}
if(verify != null){
for(int i=0; i<verify.length; i++){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
int status = st.executeUpdate("update Staff set verified = 'yes' where Staff_id = '"+verify[i]+"'");
if(status>0){
//response.sendRedirect("SuccessfulReg1.html");
}
else{
//out.println("Update unsuccessful");
}
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
}
}
%>
</body>
</html>
Change your UPDATE query to
st.executeUpdate("update Staff set verified = 'yes' where Staff_id = " + verify[i]);
Since, staff_id column has a data type of autonumber, its value should not be specified in quotes since it's numeric in nature.
I would also suggest you to use the SQL IN clause and fire just one single UPDATE instead of firing it multiple times, one for each staff_id value.
Your UPDATE query with IN clause should look something like
UPDATE staff SET verified = 'yes' WHERE staff_id IN (1, 2, 3)
Use Arrays.toString() to get the comma-delimited string as
String inValues = Arrays.toString(verify); // "[1, 2, 3]"
inValues = inValues.substring(1, inValues.length() - 1)); // "1, 2, 3"
I am trying to retrieve data from SQL query executed and validate the result with input I am making within form. I keep getting no return, in other words, it just returns empty value. Could you please help me with this matter or if this not the correct solution then how can I retrieve this value to perform validation.
My validation should match the inputed user with database user.
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
<script>
function validateForm() {
var x = document.forms["input"]["user"].value;
var y = document.forms["input"]["pwd"].value;
if (x == null || x == "" && y==null || y=="" ) {
alert("Username and Password must be filled out");
return false;
}
}
function validateUser() {
var x = document.forms["input"]["user"].value;
var variableFromServer = "${names.FIRST_NAME}";
document.write('<p>'+variableFromServer+'</p>');
if (x != variableFromServer) {
alert("Username is not right"+variableFromServer);
return false;
}
}
</script>
</head>
<body>
<sql:setDataSource var="db" driver="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:********" user="******" password="******"/>
Connected
<sql:query dataSource="${db}" var="query_select">
Select * from User_Details
</sql:query>
<c:forEach var="names" items="${query_select.rows}" >
inside loop : <p>${names.FIRST_NAME}</p>
</c:forEach>
<form action= "/BilalWebtier/login.jsp" name="input" action="demo_form_action.asp" method="post" onsubmit="return validateForm() & validateUser();">
Username: <input type="text" name="user">
Password: <input type="password" name="pwd">
<input type="submit" value="Login">
<br/>
<br/>
</form>
<button type="button">Password Reset</button>
</body>
</html>
You should change it to the click event
<form action= "/BilalWebtier/login.jsp" name="input" action="demo_form_action.jsp" method="post" >
Username: <input type="text" name="user">
Password: <input type="password" name="pwd">
<input type="submit" value="Login" onclick="return validateForm() && validateUser();">
<br/>
<br/>
</form>
I am creating small web apps and I am facing the following problem. I have 2 JSPs and when I click the submit button, it repeats the value every time. What I want is that when I click on the submit button it should give only the corresponding value.
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.io.*,java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Class Video</title>
</head>
<body>
<form action="second.jsp" method="post">
<table>
<%
File f=new File("C:/Users/SHAKTI/Desktop/video");
File[] list=f.listFiles();
if(list.length!=0){
String s[]=new String[list.length];
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
%>
<tr><td><%=fi %></td>
<td><input type="text" name="file" value="<%=s[i] %>">
</td>
<td><input type="submit" name="play" value="Play"></td>
</tr>
<%}}
else{
%>
<tr>
<td>There is no any files in the database...</td>
</tr>
<%
}
%>
</table>
</form>
</body>
</html>
second.jsp
<form action="" method="post">
<%
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
String id=request.getParameter("file");
out.println("id = "+id);
%>
<input type="submit" name="submit" value="submit>
</form>
First Jsp : Set Value in First Page
request.setAttribute("name",somevalue);
Second Jsp : Retrieve it in Second page
request.getAttribute("name")
use queryString
URl: http://myaddress.com/xyz?name=jill&sex=f
String someName = request.getParameter("name") ;
String sex = request.getParameter("sex") ;
One way is to use session as described by javaBeginner.
you can also create a from on the fly and submit it.
write a function similar to this one and use it in your success:
function submitValues(url, params) {
var form = [ '<form method="POST" action="', url, '">' ];
for(var key in params)
form.push('<input type="hidden" name="', key, '" value="', params[key], '"/>');
form.push('</form>');
jQuery(form.join('')).appendTo('body')[0].submit();
}
There are many options to pass a value from one jsp to another, Here are some
1) Adding that as a hidden variable and specifying the value
<input name="file" type="hidden" value=""/>
2)Adding it to the session and retrieving the session variable
session.setAttribute("file", value);
3)Passing that as a queryParameter
http://......one.jsp?file=""
It is beacause you are iterating the loop here,
for(int i=0;i<list.length;i++){
s[i]=list[i].toString();
String fi=list[i].getName();
so it will print the last element from the loop, to get the name u clicked on the button try this .. Change this line as
<input type="text" name="file" value="<%=s[i] %>">
as,
<td><input type="button" class="btn" data-reqno=value="<%=s[i] %>" value="file name">
And handle it using jQuery like this , so that you can pass the value to next JSP,
<script type="text/javascript">
$(document).ready(function () {
$(".btn").click(
function() {
var selectedFileName = $(this).attr("data-reqno");
var urlToApprove = "/yourApp/req/filename?name=" + selectedFileName;
}
);
});
</script>
And also try to avoid Scriptlets in JSP , you can use JSTL or El for the same purpose .
Hope it helps !!
there are many method to pass variable such as
session.setAttribute()
session.getAttribute
action "xxx.jsp?variable=1"
I have a JSP page with a form which calls the same page after the submit button is pressed. In the page I define a variable x, initially with the value of 1 and hence it fetches the data from DB corresponding to 1. Now when submit is pressed the value of x increases to 2 and the data should be fetched from DB corresponding to the new value. My problem is that the value increases but data is not fetched.Please tell me why?
<%# 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">
<%# page import="java.io.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<jsp:useBean id="Student" scope="session" class="StudentBean.StudentLoginBean"></jsp:useBean>
<%int x=1; %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>welcome <jsp:getProperty property="login" name="Student" />
</title>
</head>
<body>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
String URL="jdbc:mysql://localhost:3306/OnTest";
Connection con=null;
con=DriverManager.getConnection(URL,"root","root");
PreparedStatement stat=con.prepareStatement("select * from questions where qnNo="+x);
x+=1;
ResultSet rs=stat.executeQuery();
while(rs.next()) {
out.println(x);
out.println(rs.getString(1));%>
<form action="sucess.jsp">
<br><input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(2));%>
<input type ="radio" name ="answer" value="b">
<%
out.println(rs.getString(3));%>
<input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(4));%>
<input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(5));%>
<input type="submit" value="submit" name="submit">
</form>
<%
//System.out.println(rs.getString("name"));
//System.out.println(" "+rs.getString("password"));
//v.addElement(rs.getString("name"));
//v.addElement(rs.getString("name"));
}
if(!con.isClosed()) {
out.println("success");
}
}
catch(Exception e)
{
out.println(e);
}
%>
<h1><h1><h1>i am inside sucess</h1></h1></h1>
</body>
</html>
change this code - <%int x=1; %> to this <%!int x=1; %>.
Problem is : your x declaration is at local scope, which re-initializes for every call to .jsp (jsp_servlet).
by using <%! ... %> your x can be defined globlally.
Would be a good thing if you separe logic from view.
Anyway after pressing submit it will reload the page, setting the x variable again at 1.
A solution could be to send the x parameter with the post data and increment it then.
<input type="text" name="x" value="${x}" /> <!-- If you're using EL -->
<input type="text" name="x" value="<%=x%>" />
And
<%
int x = request.getParameter("x");
if(x == null){
x = 1;
}
%>
By separate logic from view i mean that you should use Servlets, you will find a lot of documentation online :)
while(rs.next())
{
out.println(x);
<form action="sucess.jsp">
out.println(rs.getString(1));%>
<br><input type ="radio" name ="answer" value="a">
<%
out.println(rs.getString(2));%>
<input type ="radio" name ="answer" value="b">
<%
out.println(rs.getString(3));%>
<input type ="radio" name ="answer" value="c">
<%
out.println(rs.getString(4));%>
<input type ="radio" name ="answer" value="d">
<%
out.println(rs.getString(5));%>
<input type ="radio" name ="answer" value="e">
<input type="submit" value="submit" name="submit">
</form>
<%
//System.out.println(rs.getString("name"));
//System.out.println(" "+rs.getString("password"));
//v.addElement(rs.getString("name"));
//v.addElement(rs.getString("name"));
}
Change these values and you will get the solution. Actually, you were not doing the first inside the Form method so it was behaving differently.