How can i get data from a servlet into a JSP page? - java

I am developing a small sql servlet application that takes in a SQL command from a text area in an html page, sends the command to a servlet that makes an sql connection and puts in the resultset into an arraylist. I have all of that down, and i can print column names to the browser in the java servlet class. One thing i need to do is print the results into a table using a JSP page. The JSP page will look just like the html page we first used. I can not figure out how i am going to get the arraylist from the servlet to the JSP page to be displayed to the user.
Here is the HTML page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
</font>
</body>
</html>
and here is the servlet code:
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 java.util.ArrayList;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
/**
*
* #author KJ4CC
*/
public class NewServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
Connection connection;
Vector<String> columnNames = new Vector<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
String command = request.getParameter("command");
out.println("<!DOCTYPE html>");
out.println("<html>");
sqlConnection(command);
//prints out column names into the browser.
out.println(columnNames);
}
}
public void sqlConnection(String command){
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/project3";
String user = "root";
String pass = "Brandy?1994";
ResultSet rs;
try {
Class.forName(driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
connection = DriverManager.getConnection(url,user,pass);
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
Statement stmt;
try {
stmt = connection.createStatement();
rs = stmt.executeQuery(command);
int colNum = rs.getMetaData().getColumnCount();
for (int i = 0; i < colNum; i++) {
columnNames.add(rs.getMetaData().getColumnLabel(i+1));
}
} catch (SQLException ex) {
Logger.getLogger(NewServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Here is the start of the JSP page:
<html>
<head>
<title>WebApp</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="background-color:blue;">
<center>
<font color="white">
<h1> Welcome to the Project 4 Remote Database Management System</h1>
<hr>
You are connected to the Project4 database. <br>Please enter any valid SQL query or update statement.<br>
If no query/update command is given the Execute button will display all supplier information in the database. <br>All execution results will appear below.
<br>
<br>
<form action="NewServlet" method="post">
<textarea rows="10" cols="60"name="command"></textarea>
<br>
<button type="submit">Execute Query</button>
<button type="submit">Clear Command</button>
</form>
<hr>
<h1>Database Results</h1>
<%
DO TABLE STUFF HERE TO OUTPUT SQL RESULTS
%>
</font>
</body>
</html>
I think i will create a javaBean to store the arrays so that the JSP page can access the column arraylist. Then use a for loop to iterate through the array list so that i can create the table columns. how could i link the JSP page to the servlet so that if can get the information needed?
I have to do the sql connection in the servlet and cannnot make the connection in the JSP page.

In your servlet method, set attribute in page context as below
HttpServletRequest req = (HttpServletRequest)request;
.... // find out what to put
req.getPageContext.setAttribute('some', objectYouFound);
In your jsp, use el to access the variable:
${some}

In the servlet, store the data in a request attribute:
request.setAttribute("rows", rows);
In the JSP, use the JSTL to loop over the rows:
<c:forEach var="row" value="${rows}">
...
</c:forEach>
Do NOT use Java scriptlets in your JSP.

You have few issues with your current code:
(1) A single servlet instance will be shared across all request threads, so you should NOT create the instance variables for a servlet class i.e.,
Connection connection;
Vector<String> columnNames = new Vector<String>();
These two variables should be created inside your processRequest() method so that they will be local to each request thread.
(2) You are ONLY querying the META DATA of the table, so you can display only column names, but if you wanted to fetch the data as well, you need to use resultSetObj.hasNext() and then use next() method like below:
while (rs.hasNext())
{
String X = rs.getString("empno");
//Retrieve all data
//add to a bean object
//add to list
}
//Now return the list which contains the data
You can look at here for a good example.
(3) Use the request.setAttribute to set the results to the request object and then you can retrieve to the next JSP (results) page.

Related

Java Servlet redirect to page auto calls its form servlet

the problem to when I fill in the form it calls a servlet, which displays the correct information, when the user clicks the back button it seems to call the servlet on that page with the value null. How do i make it so it reloads the page so the user can refill in the form.
SetTimeZone.xhtml
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SetTimeZone</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<div>
<form name ="SetTimeZone" method="post" action="SetTimeZoneServlet">
Set Time Zone: <input type="text" name="timeZone"/><br></br><br></br>
<input type ="submit" value="Submit" name="submit"/>
</form>
</div>
</body>
public class SetTimeZoneServlet extends HttpServlet {
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
TimeZoneBean bean = new TimeZoneBean();
String city = request.getParameter("timeZone");
bean.setCity(city);
String temp = bean.checkCity();
String value = "";
if ("error".equals(temp)) {
value = "Sorry no information is availible for " + city;
} else {
value = "The current time in " + city + " is " + bean.getTime();
}
try (PrintWriter out = response.getWriter()) {
response.setContentType("text/html;charset=UTF-8");
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet OrderFormServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>" + value + "</p>");
out.println("<form name=\"SetTimeZone.xhtml\" method=\"post\" name=\""
+ "SetTimeZoneRedirectServlet\"> ");
out.println("<input type =\"submit\" value=\"Back\"/ name=\"back\">");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}
}
public class SetTimeZoneRedirectServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("SetTimeZone.xhtml");
}
}
The output i get after the redirect back to the page is;
Sorry no information is available for null.
Try Using the GET Instead of POST
This may solve your problem
By using the POST method for your form you may encounter this problem. As #visray suggested, you need to override the doGet() Servlet method for the GET method to work correctly.
POST method should be used when dealing with database changes, so in your case GET is appropriate.

Unable to retrive data from database and display in JSP using Servlet

I am beginner in JSP and Servlets. I have searched about the issue and couldn't found exactly what the solution is.
I am passing data from jsp to servlet and inserting in database and from there retrieving the same and passing to JSP for display
I was able to pass data from JSP and insert in database successfully but unable to retrieve and display in jsp again. Below is code.
jsp:
<!DOCTYPE HTML><%#page language="java"
contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>loginform</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form name=loginform action=TestServlet method=post>
Input ID <input type=text name="id" size=10></input> <br><br>
<Input type="button" value=Retrive> <br>
<label for = "getdata" ></label> <br>
value is <%= request.getSession().getAttribute("data") %>
<input type=submit value=submit></input>
</form>
</body>
</html>
Servlet:
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;
import java.sql.*;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
// Actual logic goes here.
try {
String getvalue=request.getParameter("id");
PrintWriter out = response.getWriter();
out.println(getvalue);
out.println("attempting to read from table");
Class.forName("oracle.jdbc.driver.OracleDriver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:#IP:Port:ServiceName, UN, Pass);
// Execute SQL query
Statement stmt = conn.createStatement();
String sqlinsert, sqlselect;
sqlinsert = "Insert into abc(abc) values("+getvalue+")";
sqlselect="Select abc from abc";
ResultSet rs = stmt.executeQuery(sqlinsert);
ResultSet rs1 = stmt.executeQuery(sqlselect);
int id=0 ;
// Extract data from result set
while(rs1.next()){
//Retrieve by column name
id = rs1.getInt("ABC");
//Display values
out.println("ID: " + id + "<br>");
}
HttpSession session = request.getSession(false);
request.setAttribute("data", "0");
request.getRequestDispatcher("/loginform.jsp").forward(request, response);
// out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
I am unable to understand where is the problem. Every time I run the code I am able to see only null in JSP.
Simply change request.getSession().getAttribute("data") to request.getAttribute("data") and it will work fine.
In your Java code you use request.setAttribute("data", "0"); ,but in you JSP page you use request.getSession().getAttribute("data") ,so you will not get the data.
you are actually storing your data in session and try to fetch it from request scope so i think you are getting null value.
in jsp remove <%= request.getSession().getAttribute("data") %> line and use this line <%= request.getAttribute("data") %>

java servlet getparameter return null

I have a page that uses a servlet
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Estoque Online - Registro</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/js/materialize.min.js"></script>
</head>
<body>
<div>
<FORM ACTION="ValidaRegistro" method="post">
<label>
<font size="6">
Cadastro de Usuários
</font>
</label><br>
<label for="Nome">
<font size ="4">
Nome
</font>
</label>
<input autocomplete="on" type="Text" name="inNome" id="Nome">
<label for="Email">
<font size="4">
Email
</font>
</label>
<input autocomplete="on" type="Text" name="inEmail" id="Email">
<label for="Senha">
<font size="4">
Senha
</font>
</label>
<input type="password" name="inSenha" id="Senha">
<label for="Tipo">
<font size="4">
Tipo
</font>
</label>
<input type="Text" name="inTipo" id="Tipo">
<input type="submit" id="Submeter" value="Submeter" class="btn waves-effect waves-light col s12">
</FORM>
</div>
</body>
</html>
This is the page
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
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.swing.JOptionPane;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
/**
*
* #author Rafael
*/
/**
*
* #author Rafael
*/
public class ValidaRegistro extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet ValidaRegistro</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet ValidaRegistro at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Nome = (String)request.getParameter("Nome");
String Email =(String)request.getParameter("Email");
String Senha =(String)request.getParameter("Senha");
int Tipo = Integer.parseInt(request.getParameter("Tipo"));
DAO.main(null);
try {
Inserir(Nome,Email,Senha,Tipo);
} catch (SQLException ex) {
Logger.getLogger(ValidaRegistro.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
public void Inserir(String Nome,String Email,String Senha,int Tipo) throws SQLException{
DAO.Inserir(Nome,Email,Senha,Tipo);
}
}
And this is the servlet, but in doPost Method request.getParameters always return null and i don't know why.
I tried to change to request.getAtributes but the result is the same.
Please help me.
Hi can you try the below
String Nome = (String)request.getParameter("inNome");
String Email =(String)request.getParameter("inEmail");
String Senha =(String)request.getParameter("inSenha");
int Tipo = Integer.parseInt(request.getParameter("inTipo"));
Form parameters are identified by name, not by ID. You should use the same value for both name and ID and in the getParameter() method.

Unable to send Client's timestamp to the server

Please check the below code
JSP
<%--
Document : index
Created on : Sep 8, 2015, 10:13:49 AM
Author : Yohan
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page contentType="text/html" import="java.util.Date" %>
<%#page contentType="text/html" import="java.sql.Timestamp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script>
function time()
{
var elem = document.getElementById("hiddenTxt");
elem.value = "<%= new Date().getTime()%>";
}
</script>
<script type="text/javascript">
function time2()
{
var elem = document.getElementById("hiddenTxt");
elem.value = Date.now();
}
</script>
<script type="text/javascript">
function time3()
{
alert(<%= new Date().getTime()%>);
}
</script>
</head>
<body>
<button onclick="time3()" value="click" >Click</button>
<form action="TimestampClass" method="post" onsubmit="time2()">
Name: <input type="text" name="nameTxt">
<input type="hidden" name="hiddenTxt" id="hiddenTxt" >
<input type="submit" value="Submit">
</form>
</body>
</html>
Servlet
package test;
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 java.sql.*;
/**
*
* #author Yohan
*/
public class TimestampClass extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// long currentTimeMillis = System.currentTimeMillis();
// Timestamp timestamp = new Timestamp(currentTimeMillis);
// System.out.println(currentTimeMillis);
// System.out.println(timestamp);
String name = request.getParameter("nameTxt");
long timeStampLong = Long.parseLong(request.getParameter("hiddenTxt"));
PrintWriter out = response.getWriter();
out.println(name);
out.println("<br>");
out.println("Script Time: "+getSQLCurrentTimeStamp( timeStampLong));
out.println("<br>");
out.println("Normal Time: "+getSQLCurrentTimeStamp());
}
public static java.sql.Timestamp getSQLCurrentTimeStamp(long timeStampLong)
{
Timestamp t2= new Timestamp(timeStampLong);
return t2;
}
public static java.sql.Timestamp getSQLCurrentTimeStamp()
{
java.util.Date date= new java.util.Date();
Timestamp t= new Timestamp(date.getTime());
System.out.println(t);
return t;
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
All I want is to send the current time of the client PC to the server. I have tried both Javascript and Java inside JSP.
But there is an issue with the Javascript. I have my server in amazon EC2 US-West and I am in Sri Lanka. The time difference is +5.30GMT
When I deploy the code, the javascript simply gets the time of the server, not the time in my computer.
I tried using Java inside JSP and it is having another issue. That is, no matter where I place the new Date.getTime(), it is always getting the time the web page was loaded and it won't change even after minutes.
What am I doing here wrong? All I want is to send the current time of the client to the Server side Servlet.
The snippet:
<%= new Date().getTime()%>
will always get the server time, so forget about using that.
To get the client timestamp you need to use JavaScript. In your HEAD section add this (within script tags of course):
if (!Date.now) {
Date.now = function() { return new Date().getTime(); }
}
This sets up the Date.now function in case the client uses Internet Explorer 8, which doesn't know Date.now
I don't know how JavaScript optimizes code. Maybe you could try this to see if it makes a difference if the Date is determined inside a function or not:
<form action="TimestampClass" method="post" onsubmit="document.getElementById('hiddenTxt') = Date.now();">
Name: <input type="text" name="nameTxt">
<input type="hidden" name="hiddenTxt" id="hiddenTxt" >
<input type="submit" value="Submit">
</form>
Try to use JS function to get time
function time3(){
alert(new Date().getTime());
}

HTTP Status 404. description The requested resource is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I've got a page here. When I click the submit button, I get the 404 page saying:
HTTP Status 404 - /Email/EmailGet
type Status report
message /Email/EmailGet
description The requested resource is not available.
Apache Tomcat/7.0.47
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>
<form action="EmailGet" method="GET">
Email: <input type="text" name="email"> <br> Password: <input
type="password" name="password"> <br> <input
type="submit" value="Submit">
</form>
</body>
</html>
Here's the EmailGet code:
package email;
import java.io.IOException;
import javax.mail.Session;
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;
/**
* Servlet implementation class Controller
*/
#WebServlet("/EmailGet")
public class EmailGet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public EmailGet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Gets the entered email and password
String username = request.getParameter("email");
String password = request.getParameter("password");
//Creates the session and sets the session attributes
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("password", password);
RequestDispatcher dispatcher;
//Calls the setCredentials method to check if entered credentials are valid
boolean result = SendSMTPMail.setCredentials(username, password);
//if valid, forwards to send page
if (result == true) {
dispatcher = request.getRequestDispatcher("send.jsp");
dispatcher.forward(request, response);
}
//if not valid, forwards to index page with error message displayed
else {
dispatcher = request.getRequestDispatcher("indexerror.jsp");
dispatcher.forward(request, response);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Any ideas? It used to forward the page fine, but seems not to be working now.
Each jsp page runs fine individually, it's just the forwarding that isn't working.
It seems. . . that the requested page does not exist. I don't know the names of you files, so i can only guess that you have a typo somewhere, try to check your url bar and check if this is really the url you wanted.

Categories

Resources