MySQL to JSP using Servlet - java

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,

Related

Trying to implement an SQL vulnerability in a java web application. Java + MySQL

This is a bit of an odd one. For my uni final project I'm trying to develop a vulnerable web application as an educational tool. One of the vulnerabilities I want to implement is an SQL vulnerability where the user could perform an SQL injection through a 'product search' page on the site.
The problem is that somewhere along the way the inputs seem to be getting sanitised automatically which means I am unable to perform an injection attack. I made a test record of just a single quote (') and this is returned when a single quote in put into the search. If the input was not sanitised it would return an error, right? I'm thinking this could be a feature of the software I'm using that I'll need to disable or use an older version, or I've accidentally set it up in such a way that this is happening. If anyone knows why this might be happening, any help would be massively appreciated! :)
I have a database set up in MySQL Community Server 8.0.13 and a simple application made using JSPs. I have included source code below.
The 'Product Search' page:
<%#page import="java.sql.Connection"%>
<%#page import="databaseManagement.DBConnection"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Search Our Products</title>
</head>
<body>
<h1>Search for a product</h1>
<form method="post" action="ProductSearch">
Search: <input type="text" name="Search"> <br>
<input type="submit" value="Go">
<%#taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%><br>
<table align="left" border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<c:forEach var="product" items="${r1}">
<tr bgcolor="">
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
The java servlet:
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
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 databaseManagement.DBConnection;
import databaseManagement.Product;
#WebServlet("/ProductSearch")
public class ProductSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductSearch() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
searchTerm = "%" + searchTerm + "%";
ArrayList<Product> ab = new ArrayList();
try {
String sql1 = "select * from products where name like ?;";
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement(sql1);
ps.setString(1, searchTerm);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product b = new Product();
b.setId(rs.getInt("id"));
b.setName(rs.getString("name"));
b.setDescription(rs.getString("description"));
b.setPrice(rs.getString("price"));
ab.add(b);
}
request.setAttribute("r1", ab);
request.getRequestDispatcher("productSearch.jsp").forward(request, response);
}
catch (Exception s2) {
s2.printStackTrace();
}
}
}
Fragment of doPost method that should be placed to accept SQL injection:
....
try {
String sql1 = "select * from products where name like '"+searchTerm+"';";
DBConnection db = new DBConnection();
Connection con = db.getConnection();
Statement ps = con.createStatement();
ResultSet rs = ps.executeQuery();
while (rs.next()) {
....
PreparedStatement prevents SQL Injection, so use Statement instead.
It's PreparedStatement who's sanitising your inputs. Instead of setting your parameters, simply concat them to the sql.

Simple Java Web Application: Table Not Loading On Startup

I'm developing a simple application with Eclipse and Apache in which i display a table created with MySQL pertaining to products (with columns id, name and price) using Java, JSP and HTML. I also have a text box with a button which allows to filter the table showing only the products which have a bigger price than the one inserted on the text box.
Everything seems to be working fine including the filter. However, when i run the application for the first time, the full table isn't displayed like it should. It only displays when i use the filter. I'm not sure but there seems to be some conflict between the scriptlet for the filter elements and the table because if i comment the scriptlet for the filter elements in the JSP file, the table loads on startup like it should.
This is the code for JSP class which loads the table and the search elements (with some Bootstrap styling):
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.Connection,java.sql.ResultSet,java.sql.DriverManager,project1.components.DBConnector, project1.components.Filter"%>
<!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>Product</title>
<style type="text/css">
<%#include file="bootstrap/css/bootstrap.css" %>
<%#include file="bootstrap/css/bootstrap-theme.css" %>
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<%
DBConnector dbc = new DBConnector();
Connection conn = dbc.connect();
String query = "select * from product";
%>
</body>
<form method="post">
<div class="col-xs-2 col-xs-offset-5">
<input type="text" class="form-control" name="value" value=<%=request.getParameter("firstinput")%>>
<br><br>
<input type="submit" class="form-control" name="submit" value="Filter">
<%
if(!request.getParameter("value").isEmpty()){
String val = request.getParameter("value");
Filter ft = new Filter();
query = ft.filterByValue(val);
}
%>
</div>
<br></br>
<table class = 'table table-hover'>
<tr>
<td>Id</td>
<td>Name</td>
<td>Product</td>
</tr>
<%
try
{
ResultSet rs = dbc.obtainTable(query);
while(rs.next())
{
%><tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getFloat("PRICE") %></td>
</tr> <%
}
%>
</table>
<%
rs.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</html>
The Java class which connects to the database and obtains data with a given query to be loaded on the table defined in the previous JSP file:
package project1.components;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnector {
String url = "jdbc:mysql://localhost:3306/products?autoReconnect=true&useSSL=false";
String user = "root";
String pass = "root";
public Connection connect() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
return (Connection) DriverManager.getConnection(url,user,pass);
}
public ResultSet obtainTable(String query) throws ClassNotFoundException, SQLException{
Connection cn = this.connect();
Statement stmt= (Statement) cn.createStatement();
return stmt.executeQuery(query);
}
}
And finally, the filter itself defined in Java:
package project1.components;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Filter {
public String filterByValue(String val) throws ClassNotFoundException, SQLException{
int num = Integer.parseInt(val);
String query = null;
if(num >= 0){
query = "select * from product where price >" + val;
}
else{
query = "select * from product";
}
return query;
}
}
Any help would be really appreciated.
Could you please replace the following:
if(!request.getParameter("value").isEmpty()){
by:
if(request.getParameter("value")!=null && !request.getParameter("value").trim().isEmpty()){
and see the results?

Storing files in MySql database using jsp and servlet.

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.

How to properly display Mysql tables using servlets and java?

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();
}
}

PreparedStatment not fetching data from MySql using Java Class's Method parameters

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

Categories

Resources