I want to show firstname, lastname, username and password of logged in user in jsp textbox, but it show details of every user like this:
For now I have only two users in MySql database.
But, for example if I log in as a gordon_k, how to show only his data?
I have servlet (LoginServlet.java) like this:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
PrintWriter out = response.getWriter();
String username = request.getParameter("username");
String password = request.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/e-book", "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select username,password from users where username='" + username
+ "' and password='" + password + "'");
if (rs.next()) {
response.sendRedirect("mainMenu.jsp");
HttpSession session = request.getSession();
session.setAttribute("username", username);
} else {
out.println("Wrong id and/or password");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And jsp file like this:
changePersonalData.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "e-book";
String userid = "root";
String password = "root";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!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>Change</title>
</head>
<body>
<form method="post" action="ChangePersonalDataServlet">
<table align="left">
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr>
<td>First name</td>
<td><input type="text" name="firstname"
value="<%=resultSet.getString("first_name")%>"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" name="lastname"
value="<%=resultSet.getString("last_name")%>"></td>
</tr>
<tr>
<td>User name</td>
<td><input type="text" name="username"
value="<%=resultSet.getString("username")%>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"
value="<%=resultSet.getString("password")%>"></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
<tr>
<td></td>
<td><input type="submit" value="Change"></td>
</tr>
</table>
</form>
</body>
</html>
Change in changePersonalData.jsp like following to get username from session and pass this username in your sql query to get selected user data:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String id = request.getParameter("id");
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "e-book";
String userid = "root";
String password = "root";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!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>Change</title>
</head>
<body>
<form method="post" action="ChangePersonalDataServlet">
<table align="left">
<%
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String username = (String) request.getSession().getAttribute("username");
String sql = "select * from users where username='"+username+"'";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr>
<td>First name</td>
<td><input type="text" name="firstname"
value="<%=resultSet.getString("first_name")%>"></td>
</tr>
<tr>
<td>Last name</td>
<td><input type="text" name="lastname"
value="<%=resultSet.getString("last_name")%>"></td>
</tr>
<tr>
<td>User name</td>
<td><input type="text" name="username"
value="<%=resultSet.getString("username")%>"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password"
value="<%=resultSet.getString("password")%>"></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
<tr>
<td></td>
<td><input type="submit" value="Change"></td>
</tr>
</table>
</form>
</body>
</html>
Related
I made an html textbox for an input and want to connect this to database.
But everytime I make an input to the textbox and move on to the result page, the result only shows the name of the attribute but not any tuples.
I think the request.getParameter() returns null or empty string. I did several tries but cannot find any solution.
Here's my code.
This's selectTestForm.jsp
<%# page contentType="text/html; charset=utf-8" %>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Select the game</title>
</head>
<body>
<p>Input opponent team</p>
<form name="form1" method="get" action="result.jsp">
<p>Opponent team : <input type="text" name="oppon"></p>
<p><input type="submit" name="Submit" value="send"></p>
</form>
</body>
</html>
And this's the result.jsp
<%# page contentType="text/html; charset=utf-8" %>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<title>Find the game</title>
</head>
<body>
<table width="500" border="1">
<tr>
<td width="100">Game ID</td>
<td width="100">Opponent Team</td>
<td width="100">Start Date</td>
</tr>
<%
String opponent = (String) request.getParameter("oppon");
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException cnfe){
cnfe.printStackTrace();
System.out.println("Driver loading error");
}
try{
String jdbcUrl = "jdbc:oracle:thin:#localhost:1521:xe";
String userId = "sports_booking";
String userPass = "jade";
con = DriverManager.getConnection(jdbcUrl, userId, userPass);
String sql = "select * from game where opponent=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "opponent");
rs = pstmt.executeQuery();
while( rs.next() ) {
String game_id = rs.getString("game_id");
String start_date = rs.getString("start_date");
%>
<tr>
<td width="100"><%= game_id %></td>
<td width="100"><%= opponent %></td>
<td width="100"><%= start_date %></td>
</tr>
<%
}
}catch(SQLException e){
e.printStackTrace();
if(rs != null) {
try {
rs.close();
}catch(SQLException sqle) {}
}
if(pstmt != null) {
try {
pstmt.close();
}catch(SQLException sqle) {}
}
if(con != null) {
try {
con.close();
}catch(SQLException sqle) {}
}
}
%>
</table>
</body>
</html>
I'd appreciate if you help my problem thanks!
The problem is line pstmt.setString(1, "opponent");, as you set a const "opponent" string instead of the variable.
pstmt.setString(1, "opponent"); -> pstmt.setString(1, opponent); should work now.
i have been trying to make it work for a long time now. but none of the reference works. so far these are my latest code regarding search. hopefully someone can help. i am new in jsp and this is final graduation project. so badly need help.
code:
index.jsp:
<div class="container">
<form class="form-inline" method="post" action="search.jsp">
<input type="text" name="roll_no" class="form-control" placeholder="Search roll no..">
<button type="submit" name="save" class="btn btn-primary">Search</button>
</form>
search.jsp:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "hospital";
String userid = "hospital";
String password = "hospital";
String NAME=request.getParameter("NAME");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<!DOCTYPE html>
<html>
<body>
<h1>Search Data</h1>
<table border="1">
<tr>
<td>CODE</td>
<td>NAME</td>
<td>PRICE</td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select * from product where NAME="+NAME+"' ";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("CODE") %></td>
<td><%=resultSet.getString("NAME") %></td>
<td><%=resultSet.getString("PRICE") %></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
I am trying to store files (text or image) in mySql database using jsp and servlet.
This is index.jsp.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
This is my FileUploadDBServlet.
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet(name = "FileUploadDBServlet", urlPatterns ={"/FileUploadDBServlet"})
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
String dbURL = "jdbc:mysql://localhost:3306/rep";
String dbUser = "root";
String dbPass = "";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream=null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
//System.out.println(inputStream);
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
And this is my Message.jsp
<%# 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"/>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The message page displays "ERROR: No value specified for parameter 3".
So, I think null value is being stored in inputStream. Why is it so and how can it be handled?
Thanks.
You can use statement.setNull(3, java.sql.Types.BLOB); if yoúr inputstream is null.
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
} else {
statement.setNull(3, java.sql.Types.BLOB);
}
As you are submitting form data with enctype="multipart/form-data" For this you have to mention #MultipartConfig(maxFileSize = "max file size") in your upload servlet.
I am trying to get a value from jsp to sevlet.First the variable value is taken by session setArribute(), getAttribute() then I need to pass that particular variable from jsp to servlet but I am getting null value for that variable.
Here below I am sharing my code, can anyone findout how can I solve this issue?
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.*"%>
<html>
<head>
<title>Welcome to survey</title>
</head>
<body>
<%
ResultSet rset;
String sur_id = request.getParameter("surveyid");
session.setAttribute( "surveyid", sur_id );
int new_survey_id = Integer.parseInt(sur_id);
if (request.getParameter("surveyid") == null) {
out.println("Please enter your name.");
} else {
out.println("Hello <b>"+request.getParameter("surveyid")+"</b>!");
}
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ new_survey_id ;
Statement stmt = con.createStatement();
rset = stmt.executeQuery(query);
while(rset.next()){
// out.println(rset.getString(1));
// out.println(rset.getString(2));
// out.println(rset.getString(3));
// out.println(rset.getString(4));
%>
<table border="3">
<tr><td>Survey_Id</td><td><%=rset.getString(1)%></td></tr>
<tr><td>Family name</td><td><%=rset.getString(2)%></td></tr>
<tr><td>First name</td><td><%=rset.getString(3)%></td></tr>
<tr><td>Middle name</td><td><%=rset.getString(4)%></td></tr>
<tr><td>gender</td><td><%=rset.getString(5)%></td></tr>
<tr><td>dat of birth</td><td><%=rset.getString(6)%></td></tr>
<tr><td>income</td><td><%=rset.getString(7)%></td></tr>
<tr><td>complete address</td><td><%=rset.getString(8)%></td></tr>
<tr><td>coordinates</td><td><%=rset.getString(9)%></td></tr>
<tr><td>mobile number</td><td><%=rset.getString(10)%></td></tr>
<tr><td>email address</td><td><%=rset.getString(11)%></td></tr>
<tr><td>present Internet provider</td><td><%=rset.getString(12)%></td></tr>
<tr><td>comments</td><td><%=rset.getString(13)%></td></tr>
<tr><td>remarks</td><td><%=rset.getString(14)%></td></tr>
<br>
<form>
<table>
<tr><td><input type="button" value="edit" onclick="javascript:document.forms[0].action = 'EditSurvey.jsp'; document.forms[0].submit();"></td>            
<td><input type="button" value="delete"></td>            
<td><input type="button" value="print"></td>            
<td><input type="button" value="send mail"></td>            
</tr>
</table>
</form>
</table>
<%
}
%>
</body>
</html>
from the above code I have set the session variable as surveyid
and I can get it from the below code.It is working properly
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit survey</title>
</head>
<body>
<%
ResultSet resultSet;
String surveyId = (String) session.getAttribute("surveyid");
out.println("check"+surveyId);
request.setAttribute("surveyid", surveyId);
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/surveysample", "root", "root");
String query = "select * from surveydetail where surveyid ="+ surveyId ;
Statement stmt = con.createStatement();
ResultSet rset = stmt.executeQuery(query);
while(rset.next()){
%>
<form name="Editsurveyform" method="post" action="EditSurvey">
<table>
<tr><td>Family name:</td><td><input type="text" name="familyName" value='<%=rset.getString(2)%>'></td></tr>
<tr><td>First name:</td><td><input type="text" name="firstName" value='<%=rset.getString(3)%>'></td></tr>
<tr><td>Middle name:</td><td><input type="text" name="middleName" value='<%=rset.getString(4)%>'></td></tr>
<tr><td>Gender:</td>
<td>
<%
if(rset.getString(5).equals("male")){
%>
<input type="radio" name="sex" value="male" checked>Male
<input type="radio" name="sex" value="female">Female
<%}
else{
%>
<input type="radio" name="sex" value="male">Male
<input type="radio" name="sex" value="female" checked>Female
<%
}
%>
</td>
</tr>
<tr><td>Birthday:</td><td><input type="date" name="dob" value='<%=rset.getString(6)%>'></td></tr>
<tr><td>Income : A?B?C?D?</td><td><input type="text" name="income" value='<%=rset.getString(7)%>'></td></tr>
<tr><td>Complete Address:</td><td><input type="text" name="address" value='<%=rset.getString(8)%>'></td></tr>
<tr><td>Coordinates:</td><td><input type="text" name="coordinates" value='<%=rset.getString(9)%>'></td></tr>
<tr><td>Mobile number:</td><td><input type="tel" name="mobileno" value='<%=rset.getString(10)%>'></td></tr>
<tr><td>Email Address:</td><td><input type="email" name="email" value='<%=rset.getString(11)%>'></td></tr>
<tr><td>Present internet provider:</td><td><input type="text" name="iprovider" value='<%=rset.getString(12)%>'></td></tr>
<tr><td>Positive comments with present provider:</td><td><textarea name="comments" cols="40" rows="5"><%=rset.getString(13)%></textarea></td></tr>
<tr><td>Negative remarks with present provider:</td><td><textarea name="remarks" cols="40" rows="5"><%=rset.getString(14)%></textarea></td></tr>
<tr><td><input type="submit" name="editsurvey" value="update survey details"></td><td><input type="reset" name="cancel" value="cancel"></td></tr>
</table>
</form>
<%}
//response.sendRedirect("EditSurvey?surveyId="+surveyId);
%>
</body>
</html>
But I encounter the problem in below java
package com.survey;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* Created by rajee on 2/18/15.
*/
public class EditSurvey extends HttpServlet {
public String familyName;
public String firstName;
public String middlename;
public String gender;
public String dateOfBirth;
public String income;
public String completeAddress;
public String coordinates;
public String mobileno;
public String emailAddress;
public String presentIP;
public String comment;
public String remark;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String surveyId = (String) request.getAttribute("surveyid");
System.out.println(surveyId);
familyName = request.getParameter("familyName");
firstName = request.getParameter("firstName");
middlename = request.getParameter("middleName");
gender = request.getParameter("sex");
dateOfBirth = request.getParameter("dob");
income = request.getParameter("income");
completeAddress = request.getParameter("address");
coordinates = request.getParameter("coordinates");
mobileno = request.getParameter("mobileno");
emailAddress = request.getParameter("email");
presentIP = request.getParameter("iprovider");
comment = request.getParameter("comments");
remark = request.getParameter("remarks");
System.out.println(familyName);
System.out.println(firstName);
System.out.println(middlename);
System.out.println(gender);
System.out.println(dateOfBirth);
System.out.println(income);
System.out.println(completeAddress);
System.out.println(coordinates);
System.out.println(mobileno);
System.out.println(emailAddress);
System.out.println(presentIP);
System.out.println(comment);
System.out.println(remark);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="surveysample";
String driver="com.mysql.jdbc.Driver";
//String dbUserName="root";
//String dbPassword="root";
// try{
//
//
// Class.forName(driver).newInstance();
// conn = DriverManager.getConnection(url + dbName, "root", "root");
// PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into surveysample.surveydetail(familyname,firstname,middlename,gender,dateofbirth,income,complete_address,coordinates,mobilenumber,emailaddress,presentiprovider,comments,remarks) values (?,?,?,?,?,?,?,?,?,?,?,?,?)");//try2 is the name of the table
//
// pst.setString(1,familyName);
// pst.setString(2,firstName);
// pst.setString(3,middlename);
// pst.setString(4,gender);
// pst.setString(5,dateOfBirth);
// pst.setString(6,income);
// pst.setString(7,completeAddress);
// pst.setString(8,coordinates);
// pst.setString(9,mobileno);
// pst.setString(10,emailAddress);
// pst.setString(11,presentIP);
// pst.setString(12,comment);
// pst.setString(13,remark);
//
//
// int i = pst.executeUpdate();
// //conn.commit();
// String msg=" ";
// if(i!=0){
// msg="Record has been inserted";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
//
//
// }
// else{
// msg="failed to insert the data";
// pw.println("<font size='6' color=blue>" + msg + "</font>");
// }
// pst.close();
// }
// catch (Exception e){
// pw.println(e);
// }
//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
code
If your problem is for surveyId being null is servlet, it is normal because you try to get it from request :
String surveyId = (String) request.getAttribute("surveyid");
As you put it in session, you should read it from there :
String surveyId = (String) request.getSession().getAttribute("surveyid");
You can try below code in your servlet as :
HttpSession session = request.getSession(false);
String surveyId = (String) session.getAttribute("surveyid");
this method request.getSession(false) will not create new session if session object is already exists. it will simply return old session object if its there otherwise it will return null.
I am trying to pass username and password from a jsp page to Authenticate Method in a Java class (LogMeIn.java), but I am getting 'false' as a result. However when I hard code values (abc/abc) I do get 'pass' result. ie. it's successful.
Please can you advise why it's not accepting the parameters passed through jsp?
--LogMeIn.java--
package org.cms.model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class LogMeIn {
public boolean Authenticate( String username, String password ) {
Connection connection = null;
// Statement statement = null;
ResultSet resultSet = null;
PreparedStatement pst = null;
String query;
boolean result = false;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();
//statement = connection.createStatement();
query = "select name from account where name= ? and password = ?";
pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
resultSet = pst.executeQuery();
int count=0;
if(resultSet.next())
{
count++;
}
if(count>0)
{
result = true;
}
else
{
result = false;
}
}
catch (SQLException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return result;
}
}
---LoginServlet---
package org.cms.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.cms.model.LogMeIn;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username;
String password;
username = request.getParameter("user");
password = request.getParameter("pass");
LogMeIn a = new LogMeIn();
boolean result = a.Authenticate(username, password);
System.out.println(result);
if (result) {
request.setAttribute("loginresult","Pass");
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
request.setAttribute("loginresult","Failed");
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
}
}
---Login.jsp---
<%# 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">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
<script language="JavaScript" type="text/JavaScript" src="validate.js"> </script>
</head>
<body>
<form enctype="multipart/form-data" onSubmit="return validate(this)" method="post" action="LoginServlet" class="form">
<table border = "0">
<tr align="left" valign="top">
<td>User Name:</td>
<td><input type="text" name ="user" class="inputbox"/></td>
</tr>
<tr align="left" valign="top">
<td>Password:</td>
<td><input type="password" name ="pass" class="inputbox" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" name="submit"
value="submit" class="fb8"/></td>
</tr>
</table>
<c:out value="${loginresult}" > </c:out>
</form>
</body>
</html>
Many Thanks
use setAttribute() method. This method sets the value of the attribute for the request which is retrieved later in the servlet by passing the request object through the dispatcher method. The set value of the attribute is retrieved by the getAttribute() method of the request object.
http://www.roseindia.net/servlets/request-parameter.shtml
http://www.roseindia.net/tutorial/servlet/passParameters.html