I am currently working on A middle-size Java Web application using Netbeans & GlassFish. And everything was good until I placed all JSP fils into the folder called LoginOut, which I created it to store all specific JSP files to make my project succinct. But after I placed all JSP files into that folder, the problem came out. In detailed, the browser keeps telling me HTTP 404 Not Found. This is a very common error I believe. I put relevant screenshots below. By the way, when I put all JSP files outside LoginOut folder, my application works fine. I don't know where the error has occurred..(Here is code) Project Fils Structure
public User checkLogin(String email, String password) throws SQLException,
ClassNotFoundException {
Connection conn = getConnection();
String sql = "SELECT * FROM users WHERE email = ? and password = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, email);
st.setString(2, password);
ResultSet rs = st.executeQuery();
User user = null;
if (rs.next()) {
user = new User();
user.setFullName(rs.getString("fullname"));
user.setEmail(email);
}
conn.close();
return user;
}
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="POST">
Email: <input type="text" name="email" ><br><br>
Password: <input type="password" name="pass" ><br><br>
<input type="submit" value="Login" ><br><br>
Click here to go back.
</form>
</body>
</html>
package controller.Servlet;
import Dao.UserDao.UserDAO;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.sql.SQLException;
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 javax.servlet.http.HttpSession;
import model.User.User;
#WebServlet("/Login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
UserDAO userDao = new UserDAO();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String email = request.getParameter("email");
String password = request.getParameter("pass");
try {
User user = userDao.checkLogin(email, password);
String destPage = "Login.jsp";
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
destPage = "home.jsp";
} else {
String message = "Invalid email/password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
Related
I have created a post yesterday regarding this, but someone decided to close it. I have tried solutions from the post, it didn't work. If answer from the post could solve my issues, I won't be asking the same question again. Tried Put servlet class in a package, Set servlet URL in url-pattern, Use domain-relative URL to reference servlet from HTML. The thing is my registration.jsp is almost the same as my login.jsp same for the servlets as well, I dont get why it doesnt work for registration when it works for the login servlet. I also have clean and restarted my server multiples times. Didnt install tomcat into the computer just import it thru zip files into eclipse.
HTTP Status 404 return by Servlet
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
Login Servlet
package net.login.controller;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import net.login.dao.UserDAO;
import net.login.model.Users;
#WebServlet("/login")
public class UserLoginServlet extends HttpServlet{
public #interface WebServlet {
}
private static final long serialVersionUID = 1L;
public UserLoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDao = new UserDAO();
try {
Users user = userDao.checkLogin(username, password);
String destPage = "login.jsp";
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
destPage = "home.jsp";
} else {
String message = "Invalid username/password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
register.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registration</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript"
src="https://cdn.jsdelivr.net/npm/jquery-validation#1.19.0/dist/jquery.validate.min.js"></script>
<link href=”bootstrap/css/bootstrap.min.css” rel=”stylesheet” type=”text/css” />
<script type=”text/javascript” src=”bootstrap/js/bootstrap.min.js”></script>
</head>
<body>
<div style='text-align=center' class="container">
<h1>New User Registration</h1>
<form action='register' method='POST' role='form'>
<div class='registerform'>
<label for='username'> Username: </label>
<input type="text" placeholder='Username' class='form-control' name='username'>
</div>
<div class='registerform'>
<label for='password'> Password: </label>
<input type="password" class='form-control' placeholder='Password' name='password'>
</div>
<br><br>
<button type="submit" class="btn btn-default"> Register </button>
</form>
</div>
</body>
</html>
UserRegisterServlet
package net.login.controller;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.login.dao.UserDAO;
import net.login.model.Users;
#WebServlet("/register")
public class UserRegisterServlet extends HttpServlet{
public #interface WebServlet{
}
private static final long serialVersionUID = 1L;
public UserRegisterServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// String pathInfo = request.getPathInfo();
// String[] pathParts = pathInfo.split("/");
// String part1 = pathParts[1];
// String part2 = pathParts[2];
//
// System.out.println(part1 + part2); //doesnt work for now since cant find /register
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDAO userDAO = new UserDAO();
try {
userDAO.createUsers(username, password);
String destPage = "register.jsp";
System.out.println("Success");
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
}catch(SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}
I am trying to retrieve data from one column of my table in MySQL and display the whole row in a .jsp file. Right now, when I run the code it prints the table with no values. As Shown here.
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.PreparedStatement;
#WebServlet("/review")
public class findservlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8402378218178447403L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection conn = null;
//using movie_resolved view
try{
// Get a Connection to the database
String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/mydatabase";
String DB_USERNAME = "root";
String DB_PASSWORD = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
// Create a Statement object
PreparedStatement st = (PreparedStatement) con.prepareStatement("SELECT * FROM coursereview");
ResultSet rs = st.executeQuery();
if (rs.next())
{
com.java.bean.coursereview Course = new com.java.bean.coursereview ();
Course.setCourse_id(rs.getString("courseid"));
Course.setCourserate(rs.getString("courserate"));
Course.setProfessor(rs.getString("professor"));
Course.setProrate(rs.getString("prorate"));
Course.setReview(rs.getString("review"));
req.setAttribute("Course", Course);
RequestDispatcher view = req.getRequestDispatcher("review.jsp");
view.forward(req, res);
}
}
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
}
finally {
// Always close the database connection.
try {
if (conn != null) conn.close();
}
catch (SQLException ignored) { }
}
}
}
Here is my reivew 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>
<link rel="stylesheet" href="styles/style1.css">
<meta http-equiv="Content-Type" content="text/css; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="banner">
<img class="banner-image" src="images/uncclogo400.jpg"></div>
<h2>Review a Course</h2>
<table>
<TR>
<TD>Course ID: </TD>
<TD>${course.courseid}</TD>
</TR>
<TR>
<TD>Course Rate: </TD>
<TD>${course.courserate}</TD>
</TR>
<TR>
<TD>Professor: </TD>
<TD>${course.professor}</TD>
</TR>
<TR>
<TD>Professor Rate: </TD>
<TD>${course.prorate}</TD>
</TR>
<TR>
<TD>Review: </TD>
<TD>${course.review}</TD>
</TR>
</table>
</body>
</html>
I am trying to pull the values from the MySQL DB to print to the review.jsp page. Any ideas on what I am doing wrong?
Hello, I think it's a typo
Change this req.setAttribute("Course", Course); by this req.setAttribute("course", Course);
Best,
There is a problem in the session.
In create.html when i click on createdepartment the createdepartment.jsp page opens i copy its url1 after i submit the data , i again copy the url2 and then i logout after logging out when i paste url2 in the browser it gives message that Please login first and opens login.html but when i paste url1 in the browser it opens it but it shouldn't. Why is this happening?
I have given the code please could someone correct it?
LoginServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
String sql="select * from roles where name='" + name + "' and pass='" + password + "'";
PreparedStatement stmt =con.prepareStatement(sql);
String role="admin";
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
status=true;
role=rs.getString("role");
}
if(status){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
if(role!=null && role.equals("admin") ){
request.getRequestDispatcher("create.html").include(request, response);
}
else {
request.getRequestDispatcher("create1.html").include(request, response);
}
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
}catch( SQLException | ServletException | IOException e){}
}
}
}
create.html
Logout
Create Department
Create Users
<hr/>
department.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Create Department</h1>
<br>
<form action="DepartmentServlet">
<table border="1">
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
DepartmentServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DepartmentServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
if(status){
out.print("Values have been inserted,"+name);
request.getSession();}
else
{
out.print("failed");
}
request.getRequestDispatcher("department.jsp").include(request, response);
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
}
Logout.Servlet
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
}
}
}
http://mytechsoft.jimdo.com/exclusive-projects
above link is for your problem, refer first 2 photos in it
LogoutServlet.java code might has problem.
You haven't mentioned its code.
Logout procedure includes 2 important things..
Remove all attributes attached to that session object
Make session object null (by making session.invalidate(); )
doing this makes session eligible for Garbage Collection, and reference of object (object stored in heap memory) is deleted (reference is stored in stack ).
In your case, I guess (because LogoutServlet.java is not there), most likely the reason for error is that
"You might be creating a new session Object and then you are copying the reference of old session object, now you would be deleting this new session by "session.invalidate();".
The above process deletes new reference but old one is still there because it's copy available in new object is deleted not the original one.
For More Specific and correct answer, please attach your LogoutServlet.java source code too.
Your logout servlet should have request.getSession(false)..This will not return new session if one already exists..Also clear your browser cache before running it.
HttpSession session=request.getSession(false);
session.invalidate();
I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.
You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example
Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}
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