The servlet call order failed - java

Good afternoon!
In an example I did in class, when I debug the servlet comes in front of the filter.
On the system I'm doing the filter is called first that the servlet ... and this is causing problems.
I'm doing the login part of the system.
I am using version 3.0 of the servlet.
In class I did not need to use xml, but in some sites indicate to do this ... which also did not work.
Index
<%# 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>
<div>
<form action="template/inicio.html" method="post">
<label for="login">Login </label>
<input type="text" name="login">
<br>
<label for="senha">Senha </label>
<input type="text" name="senha">
<br>
<input type="submit" value="Entrar">
</form>
</div>
${msg}
</body>
</html>
FiltroLogin
package filtro;
import java.io.IOException;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet Filter implementation class FiltroLogin
*/
#WebFilter(
dispatcherTypes = {
DispatcherType.REQUEST,
DispatcherType.FORWARD,
DispatcherType.INCLUDE,
DispatcherType.ERROR
}
,
urlPatterns = {
"/FiltroLogin",
"/template/*"
})
public class FiltroLogin implements Filter {
/**
* Default constructor.
*/
public FiltroLogin() {
// TODO Auto-generated constructor stub
}
/**
* #see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if(session.getAttribute("login") != null ){
//Se estiver logado, deixa a pagina ser exibida
chain.doFilter(request, response);
}else{
//mandar embora
res.sendRedirect( req.getContextPath() );
}
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
ControleLogin
package control;
import java.io.IOException;
import java.util.List;
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 org.firebirdsql.jdbc.parser.JaybirdSqlParser.function_return;
import model.Funcionario;
import persistence.FuncionarioDao;
import persistence.LoginDao;
/**
* Servlet implementation class ControleLogin
*/
#WebServlet({"/ControleLogin","/template/inicio.html", "/template/logout.html"})
public class ControleLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ControleLogin() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
execute(request, response);
}
protected void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String url = request.getServletPath();
if(url.equalsIgnoreCase("/template/inicio.html")){
String login = request.getParameter("login");
String senha = request.getParameter("senha");
if(new LoginDao().logar(login, senha).booleanValue() == true){
Funcionario func = new LoginDao().buscarUsuario(login);
HttpSession session = request.getSession();
session.setAttribute("nomeP", func.getNome());
response.sendRedirect("template/indCadastro.jsp");
}else{
request.setAttribute("msg", "<div class = 'alert alert-info'>"+ "Email ou senha Incorretos!"+"</div>");
request.getRequestDispatcher("../index.jsp").forward(request, response);
}
}else if(url.equalsIgnoreCase("/template/logout.html")){
HttpSession session = request.getSession();
session.removeAttribute("nomeP");
session.invalidate();
response.sendRedirect( request.getContextPath() + "/");
}
}catch(Exception e){
e.printStackTrace();
}
}
}

I solved The index, was with the "Action =" template / Logar "", when I switched to "Action =" Logar "", it worked.
Silly mistake.

Related

JSP form submit and list population issue

I'm having a couple issues with a simple JSP app. When I go to the Add or Delete pages, I'm able to input data and submit it, the item is either added or deleted to/from the database as it is supposed to be, but instead of returning me to the page, it sends me to a page that says, "Served at: /ToDoList". I can use the back button to return to the page, but it is supposed to simply reload the same jsp page. It worked previously, but I'm not sure what I changed.
Additionally, I'm trying to populate a table with the data from a database on the Show List page (show.jsp), but it gives me a ConcurrentModificationException that I can't figure out. I'm really not sure what I'm doing wrong here. Any help is appreciated. The ListItem object is just an int itemID and string itemDesc. Code follows:
add.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add an item</title>
</head>
<body>
<h1>Add an item</h1>
<form action="AddItem" method="post">
<table>
<tr><td><input type="text" name="desc" value="" size="100"/></td></tr>
<tr><td><input type="submit" value="Submit" name="addSub" /></td></tr>
</table>
</form>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
delete.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show list</title>
</head>
<body>
<h1>To-Do List</h1>
<form action="ShowList" method="post">
<input type="submit" value="Populate">
</form>
<table>
<c:forEach var="item" items="${dispList}">
<tr>
<td>${item.itemID}</td>
<td>${item.itemDesc}.</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
show.jsp
<%#page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Show list</title>
</head>
<body>
<h1>To-Do List</h1>
<form action="ShowList" method="post">
<input type="submit" value="Populate">
</form>
<table>
<c:forEach var="item" items="${dispList}">
<tr>
<td>${item.itemID}</td>
<td>${item.itemDesc}.</td>
</tr>
</c:forEach>
</table>
<input type="submit" name="btnAdd" value="Back to menu" onclick="window.location='/ToDoList/index.jsp'">
</body>
</html>
ItemList.java
package todolist;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import org.apache.tomcat.util.http.fileupload.util.LimitedInputStream;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.Query;
public class ItemList {
List<ListItem> list = new ArrayList<>();
List<ListItem> tempList = new ArrayList<>();
public static SessionFactory factory;
public ItemList() {
super();
}
public void addItem(String itemStr) {
//list.add(item);
//list.get(list.size() - 1).setItemNumber(list.size());
ListItem item = new ListItem(itemStr);
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
Integer itemID = null;
try {
tx = session.beginTransaction();
itemID = (Integer) session.save(item);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public void delItem(int itemNbr) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
ListItem item2 = (ListItem)session.get(ListItem.class, itemNbr);
try {
tx = session.beginTransaction();
session.delete(item2);
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public List<ListItem> getList() {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query<ListItem> queryList = session.createQuery("FROM itemlist");
tempList = queryList.list();
tx.commit();
} catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
list = tempList;
return list;
}
public int size() {
return list.size();
}
}
AddItem.java
package todolist;
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;
/**
* Servlet implementation class AddItem
*/
#WebServlet("/AddItem")
public class AddItem extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public AddItem() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("add.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("desc")!=null) {
String desc = request.getParameter("desc");
list.addItem(desc);
RequestDispatcher rd = request.getRequestDispatcher("add.jsp");
rd.forward(request, response);
}
}
}
DelItem.java
package todolist;
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.hibernate.HibernateException;
/**
* Servlet implementation class DelItem
*/
#WebServlet("/DelItem")
public class DelItem extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public DelItem() {
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
RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("itemNbr")!=null && request.getParameter("itemNbr")!="") {
int itemNbr = Integer.parseInt(request.getParameter("itemNbr"));
list.delItem(itemNbr);
RequestDispatcher rd = request.getRequestDispatcher("delete.jsp");
rd.forward(request, response);
}
}
}
ShowList.java
package todolist;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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;
/**
* Servlet implementation class ShowList
*/
#WebServlet("/ShowList")
public class ShowList extends HttpServlet {
private static final long serialVersionUID = 1L;
ItemList list2 = new ItemList();
/**
* #see HttpServlet#HttpServlet()
*/
public ShowList() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
rd.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<ListItem> tempList = new ArrayList<>();
tempList = list2.getList();
request.setAttribute("dispList", tempList);
RequestDispatcher rd = request.getRequestDispatcher("show.jsp");
rd.forward(request, response);
}
}

HTTP 404 The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I was following the tutorial on:
https://www.javahelps.com/2015/04/java-web-application-hello-world.html
The Tomcat server is running well on:
http://localhost:8080/
This page is displayed correctly:
http://localhost:8080/Hello_World/
However, when I press "Click here" and go to this link:
http://localhost:8080/Hello_World/saytime
The above error is displayed.
Here is my code:
package help;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloWorldServlet
*/
#WebServlet("/saytime")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloWorldServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("<html><body><h1 align='center'>" +
new Date().toString() + "</h1></body></html>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}`
I noticed that I don't have web.xml file
Any help is appreciated
Thanks in advance,
Here is my HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World</title>
</head>
<body>
Click Here
</body>
</html>

Why am I getting null value while using "sendReditect" in servlet as per below

Why am I getting null value while using "sendReditect" in servlet as per below
my code as per below : I am getting fname value null even in both FirstServlet and SecondServlet
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname"></br> <input type="submit"
value="SUBMIT">
</form>
</body>
</html>
FirstServlet:
package com.naveen;
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;
/**
* Servlet implementation class FirstServlet
*/
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname");
// TODO Auto-generated method stub
/*String s1=request.getParameter("t1");*/
/*RequestDispatcher rd=request.getRequestDispatcher("SecondServlet");
rd.forward(request, response);*/
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
SecondServlet:
package com.naveen;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class SecondServlet
*/
#WebServlet("/SecondServlet")
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String s3=request.getParameter("fname");
out.print("hi i am siddharth");
out.println(s3);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
why i am getting null value while using "sendReditect" in servlet as
per below my code as per below : i am getting fname value null even in
both FirstServlet and SecondServlet,
Because you're not setting any values to your request. You need to set the value to the request like this:
#WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String s3=request.getParameter("fname"); //get the value you set in your jsp/html/url
request.setAttribute("fname", s3); // set the s3 value to the request
res.sendRedirect("SecondServlet");
System.out.println("your output as per" +s3);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I'm assuming here you have sent the fname value via a form or something. If you call FirstServlet by just typing it in the url, you will get null.
But not if you set something, try it like this if you are not submitting a form:
/FirstServlet?fname=helloworld
EDIT:
just noticed in your form you're not actually setting fname with any value. You need to give it a value:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="get">
username<input type="text" name="fname" value="helloworld"></br> //add value to your input!!
<input type="submit" value="SUBMIT">
</form>
</body>
</html>

Why is a blank page being displayed when I call my servlet?

I'm currently trying to complete a simple Web project using Activiti. I doing it in Eclipse using a Tomcat 7.0 server. I have a servlet that should display a tasks info but even if there's a problem there surely it should still display something.
I'm only starting to learn JSP so I apologise for any stupid mistakes I may have made in the code.
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h1>Welcome.</h1>
<br />
<h3>Go to:</h3>
<ul>
<li>Request Loan</li>
<li>Management Tasks</li>
</ul>
</body>
</html>
My servlet:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
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.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
/**
* Servlet implementation class ManagementTasks
*/
#WebServlet("/ManagementTasks")
public class ManagementTasks extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ManagementTasks() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Management Tasks</title</head><body>");
ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
TaskService taskService = processEngine.getTaskService();
List<Task> tasks = taskService.createTaskQuery()
.taskCandidateGroup("management").list();
if (tasks.size() > 0) {
out.println("<h1>You have " + tasks.size() + " task(s) to complete.</h1>");
Task t = tasks.get(0);
out.println("<br /><br /><h2>" + t.getDescription() + "</h2>");
out.println("<br />Do you want to approve this request?</h2><br />");
out.println("<form method=\"POST\" action=\"ManagementApproval\">");
out.println("<label for=\"approve\">Do you approve?</label>");
out.println("<select name=\"approve\">");
out.println("<option value=\"true\">Yes</option>");
out.println("<option value=\"false\">No</option>");
out.println("</select><br />");
out.println("<input type=\"hidden\" id=\"taskId\" name=\"taskId\" " + "value=\"" + t.getId() + "\" /><br/>");
out.println("<input type=\"submit\" value=\"Submit Form\" />");
out.println("<input type=\"reset\" value=\"Reset Form\" />");
out.println("</form>");
} else {
out.println("<h1>There are no tasks for you. </h1>");
}
out.println(" HOME ");
out.println("</body></html>");
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}

using httpsession for session management

facing problem to manage session in servlet program. this is my servlet code.
//`SessionUsingHttpSession .java
package suprio.servlets.examples;
import java.io.IOException;
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 org.apache.catalina.Session;
/**
* Servlet implementation class SessionUsingHttpSession
*/
public class SessionUsingHttpSession extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionUsingHttpSession() {
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
response.setContentType("<html/text");
String name = request.getParameter("txtName4");
String pass = request.getParameter("txtPassword4");
if(pass.equals("12345"))
{
HttpSession session = request.getSession();
session.setAttribute("user", name);
//response.sendRedirect("SessionUsingHttpSessionRedirected");
RequestDispatcher rd = request.getRequestDispatcher("SessionUsingHttpSessionRedirected");
}
}
}
and the following code is the redirected from SessionUsingHttpSession.java
//SessionUsingHttpSessionRedirected.java
package suprio.servlets.examples;
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;
/**
* Servlet implementation class SessionUsingHttpSessionRedirected
*/
public class SessionUsingHttpSessionRedirected extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public SessionUsingHttpSessionRedirected() {
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
response.setContentType("html/text");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String user = (String) request.getAttribute("user");
out.print("Hello"+user);
}
}
and this is for view part
// UsingHttpSession.html
<!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 method="get" action="SessionUsingHttpSession">
Enter Name:<input type="text" name="txtName4"/><br/>
Password: <input type="text" name="txtPassword4"/><br/>
<input type="Submit" value="Enter">
</form>
</body>
</html>
while i am trying to run it through apache tomcat server my web browsers(mozila,chrome,IE) showing this message:
if i save and open it it is giving "hello null" as output. Now my question is that why its showing such message as i am just trying to forward this page to another.
Thank you in advance.
The content type is wrong in both servlets. It should be text/html.
Moreover is you are using SessionUsingHttpSession servlet just for redirection then there is no need for specifying the content type at all.
Your content type appears reversed, you have it as html/text, instead of text/html.
Also it's a good habbit to flush/close stream after you write.
out.print("Hello"+user);
out.flush();
out.close();

Categories