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();
Related
Hello guys i'm facing a problem with my code, i have a jsp form that send a file into a servlet, and when i try to extract the file using request.getParts() it return null value wheni try to print it to the console, can anyone help me please. here is my code.
my jsp:
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="/PartsServlet" enctype="multipart/form-data" >
File:
<input type="file" name="file" id="file" /> <br/>
Destination:
<input type="text" value="/tmp" name="destination"/>
</br>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
My servlet:
package Servv;
import java.io.IOException;
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 PartsServlet
*/
#WebServlet("/PartsServlet")
public class PartsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public PartsServlet() {
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.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("Get Parts "+request.getPart("file"));
System.out.println("Get Parts "+request.getPart("destination"));
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Add #MultipartConfig annotation.
Always parse your request body only once and store it in a list.
so that one part cannot consume it.
List<Part> fileParts = request.getParts().stream().filter(part -> "file".equals(part.getName())).collect(Collectors.toList());
for (Part part : fileParts) {
}
File uploads = new File("/path/to/uploads");
File file = File.createTempFile("somefilename-", ".ext", uploads);
try (InputStream input = part.getInputStream()) {
Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
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
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>
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.
I am creating a java servlet which should get a number from a textbox (created using using HTML) calculate its factorial and when i will press submit button (also created using HTML) it should calculate and display the factorial in another textbox which i have created.
Problem I have successfully retrieved the number from the first textbox (using request.getParameter) and calculated it factorial. Now the problem is that i am unable to post the calculated factorial in that 2nd textbox.
Plz help me what should i do?
Thank in advance!
Here is the code:
servlet:
package factorial;
import java.io.*;
import javax.servlet.Servlet;
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.apache.jasper.tagplugins.jstl.core.Out;
/**
* Servlet implementation class fact
*/
#WebServlet("/fact")
public class fact extends HttpServlet implements Servlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public fact() {
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
PrintWriter out = response.getWriter();
long number = Long.parseLong((request.getParameter("num")));
long fact=1;
while(number>1){
fact=fact*number;
number--;
}
//request.setAttribute("factorial", fact); //***this is not working***
//out.println(fact);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Factorial</title>
</head>
<body>
<form action="fact" method="get">
Enter a number: <input type="text" name="num">
<input type="submit"/>
Factorial <input type="text" id="factorial" name="factorial"/>
</form>
</body>
</html>
store the value in request or session attributes as request.setAttribute("name",value) or session.setAttribute("name", value). and in JSP, retrieve them using request.getAttribute("name") or session.getAttribute("name")