When I have cookies enabled and I do a requestDispatcher.forward(req,resp) from loggedIn to ShoppingCart , the 'session id' and 'username' is carried forward/saved.
But when the cookies are disabled, a new 'session id' is created and the 'username' is null.
My question is how should i maintain the session when cookies are disabled.
login form
<html>
<body>
<form method="POST" action="login.do">
username:<input type="text" name="username" />
<input type="submit" value="login"/>
</form>
</body>
</html>
loggedIn.jsp
<html>
<body>
Session Id : <%out.print(session.getId());%><br>
Logged In User: <%out.print(session.getAttribute("username"));%><br>
<form action="shopping.do" method="POST">
<input type="submit" value="start shopping"/>
</form>
</body>
</html>
shoppingCart.jsp
<html>
<body>
Session Id : <%out.print(session.getId());%><br>
Logged In User: <%out.print(session.getAttribute("username"));%><br>
<h1>Shopping Cart</h1>
</body>
</html>
web.xml
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<!-- LOGIN CONTROLLER -->
<servlet>
<servlet-name>LoginController</servlet-name>
<servlet-class>com.example.controller.LoginController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginController</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<!-- SHOPPING CONTROLLER -->
<servlet>
<servlet-name>ShoppingController</servlet-name>
<servlet-class>com.example.controller.ShoppingController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShoppingController</servlet-name>
<url-pattern>/shopping.do</url-pattern>
</servlet-mapping>
</web-app>
LoginController
package com.example.controller;
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;
public class LoginController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
HttpSession session = req.getSession();
if(req.getParameter("username")!=null && !req.getParameter("username").isEmpty()){
session.setAttribute("username",req.getParameter("username"));
}
String URL = ("loggedIn.jsp");
String encodedURL=resp.encodeRedirectURL(URL);
System.out.println(encodedURL);
RequestDispatcher view =req.getRequestDispatcher(encodedURL);
view.forward(req,resp);
}
}
ShoppingController
package com.example.controller;
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;
public class ShoppingController extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
String URL = ("shoppingCart.jsp");
RequestDispatcher view =req.getRequestDispatcher(URL);
view.forward(req,resp);
}
}
For normal urls on the page, you would use response.encodeURL(). For redirects you should use response.encodeRedirectURL()
Additional information regarding the difference between the two can be found on this SO post
Related
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 3 years ago.
I am trying to create a servlet in java, using Eclipse IDE and Tomcat7 server. When I run the HelloForm in server it shows the form but after entering numbers and clicking submit it shows:
HTTP Status 404 - /Test2/HelloWorld
type Status report
message /Test2/HelloWorld
description The requested resource is not available.
Apache Tomcat/7.0.47
Code for HelloForm.html
<!DOCTYPE html>
<html>
<body>
<form action="HelloWorld" method="post">
Enter 1st number : <input type="text" name="num1"> <br>
Enter 2st number : <input type="text" name="num2"> <br> <input
type="submit">
</form>
</body>
</html>
Code for HelloWorld.java
package mypkg;
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
System.out.println(sum);
PrintWriter out = response.getWriter();
out.println("Addition : " + sum);
}
}
Code for web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance "xmlns= "http://java.sun.com/xml/ns/javaee" xsi: schemaLocation ="http: //java.sun.com/ xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>mypkg.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/sayhello</url-pattern>
</servlet-mapping>
</web-app>
You have missed #WebServlet("/HelloWorld"). Given below is the completed code:
package mypkg;
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;
#WebServlet("/sayhello")
public class HelloWorld extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int num1 = Integer.parseInt(request.getParameter("num1"));
int num2 = Integer.parseInt(request.getParameter("num2"));
int sum = num1 + num2;
System.out.println(sum);
PrintWriter out = response.getWriter();
out.println("Addition : " + sum);
}
}
Make sure you have the following root declaration of your web.xml otherwise it will not be interpreted as Servlet 3.0 which supports #WebServlet annotation.
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
Update:
I can see that you have now added the content of your web.xml in the question. As per this update, your HTML form action should be as follows:
<form action="sayhello" method="post">
So I have a really simple java EE Web App. It is composed of a Servlet and a jsp.
Servlet is in a package named "Servlets". Filter in another one named "Filters".
Filter is something like this :
#WebFilter(filterName="AuthFilter",
urlPatterns={"/ProgettoWeb2018/*","/profile/*"})
public class AuthFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("Hello from filter");
}
}
Now with this set up i get the following error :
java.lang.ClassNotFoundException: Filters.AuthFilter
If i move the filter in the "Servlets" package it works fine tho.
How come?
For better understanding purpose Servlet Filter project view is as follows:
Servlet class is:
package com.whodesire.demos;
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;
#WebServlet("/WelcomeServlet")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public WelcomeServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { }
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + request.getParameter("username") + ", Welcome to Secured Servlet<h1>");
out.println("<hr/>");
out.close();
}
}
Servlet Filter class is:
package com.whodesire.demos;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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;
#WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {
public AuthenticationFilter() { }
public void destroy() {
System.out.println("destroy method is called in " + this.getClass().getName());
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("init method is called in " + this.getClass().getName());
String username = request.getParameter("username");
String password = request.getParameter("passwd");
String ipAddress = request.getRemoteAddr();
System.out.println("\n username and password is : " + username + ", " + password + "\n");
//Either you can write source here to fetch here DAO object for validation
if(username.equals("wsuser") && password.equals("wspassword")) {
System.out.println("User logged in " + ipAddress + " at " + (new Date().toString()));
// pass the request along the filter chain
chain.doFilter(request, response);
}else {
//if failed the servlet filter validation
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Login request rejected in " + ipAddress + " at " + (new Date().toString()) + "</h2>");
out.close();
}
}
public void init(FilterConfig fConfig) throws ServletException {
System.out.println("init method is called in " + this.getClass().getName());
}
}
Login.html initial page along with CSS(placed as login.css):
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<link rel="stylesheet" type="text/css" href="login.css"/>
<title>Login Form</title>
</head>
<body>
<h2>User Login Form</h2>
<hr/>
<form name="loginForm" method="POST" action="WelcomeServlet">
<div class="login">
<input type="text" placeholder="Username" name="username"/>
<input type="password" placeholder="Password" name="passwd"/>
<input type="submit" value="Login"/>
forgot password?
</div>
</form>
</body>
</html>
#charset "ISO-8859-1";
h2 {
display: block;
font-size: 1.8em;
font-family: sans-serif;
margin-top: 0.83em;
margin-bottom: 0.83em;
margin-left: 0;
margin-right: 0;
font-weight: bold;
}
.login {
height:110px;
width:190px;
margin:auto;
border:1px #CCC solid;
padding:10px;
}
.login input {
padding:5px;
margin:5px
}
and finally the web.xml Servlet dispatcher configuration:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>servletFilterDemo</display-name>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
<filter>
<filter-name>Authentication</filter-name>
<filter-class>com.whodesire.demos.AuthenticationFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Authentication</filter-name>
<url-pattern>/WelcomeServlet</url-pattern>
</filter-mapping>
</web-app>
Hope this will give you a simple insight on Servlet Filter example.
My problem is i mapped my servlets on web.xml. When i submit info to servlet it gives me "resuorces is not found" error. How can i solve this problem. Thanks your answers.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="Login" method="POST">
UserName:<input type="text" name="user_name">
<BR>
Password:<input type="password" name="password">
<BR>
<input type="submit" value="Gonder">
<BR>
<input type="reset" value="Reset">
</form>
</body>
</html>
SERVLET CODES are like this
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private String usr_name;
private String pass;
static Logger log=Logger.getLogger(Login.class);
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PropertyConfigurator.configure("C:\\Users\\AliArdaOrhan\\workspace2\\QuizProject\\WebContent\\WEB-INF\\log4j.properties");
usr_name=request.getParameter("user_name");
pass=request.getParameter("Password");
try {
if(Validation.validate(usr_name,pass)){
RequestDispatcher rs=request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else{
RequestDispatcher rs=request.getRequestDispatcher("login");
rs.forward(request, response);
}
} catch (ClassNotFoundException | SQLException e) {
log.error("Cannot Validate User Information", e);
}
}
}
WEB XML CODES are like this
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>QuizProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description>Login Page</description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>Welcome</display-name>
<servlet-name>Welcome</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Welcome</servlet-name>
<url-pattern>/Welcome</url-pattern>
</servlet-mapping>
</web-app>
You need to add a servlet mapping for Login action in your web.xml:
<servlet>
<description></description>
<display-name>Login</display-name>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
And make sure you restart your server after you make those changes in web.xml.
And if you are using Servlet 3.0 then you can use annotations like below in your servlet which are equivalent to above code:
#WebServlet("/Login")
public class Login extends HttpServlet {
Please change on this line
<form action="Login" method="POST">
replace "Login" with "/GuestBook"
You are sending your form to Login (relative URL), but your servlet awaits at /GuestBook. Change the servlet mapping or form's action attribute.
I am new in spring MVC.I don't know how to forward sessionExpired.jsp in Spring MVC globaly, when session expired.
I googled a lot but I didn't get any solution.What ever I am getting they are using spring security.In our application we are not using Spring security.
Please provide some sample code.
If you add this code it should solve your issue
<security:session-management invalid-session-url="SessionExpired.jsp" session-authentication-error-url="AlreadyLoggedIn.jsp">
<security:concurrency-control max-sessions="1" expired-url="SessionIsDuplicated.jsp" error-if-maximum-exceeded="false" />
</security:session-management>
Without using security, there are two ways in Spring MVC you can use HandlerInterceptorAdapter or Filters in Servlets.
Using HandlerInterceptorAdapter
In springContext.xml
<mvc:interceptors>
<bean class="com.nalashaa.interceptor.SessionValidatorInterceptor" />
</mvc:interceptors>
package com.nalashaa.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
#Component
public class SessionValidatorInterceptor extends HandlerInterceptorAdapter {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getServletPath().equals("/login.htm")) { //for Login Page
return true;
}
if(request.getSession().getAttribute("userName")!=null){
return true;
}else{
response.sendRedirect("login.htm");
return false;
}
}
}
Using Filter
In web.xml
<filter>
<filter-name>SessionValidatorFilter</filter-name>
<filter-class>com.nalashaa.filter.SessionValidatorFilteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SessionValidatorFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
package com.nalashaa.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class SessionValidatorFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
// initialization
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if(((HttpServletRequest)request).getRequestedSessionId() != null && ((HttpServletRequest)request).isRequestedSessionIdValid() == false) {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/login.jsp");
requestDispatcher.forward(request, response);
}else {
chain.doFilter(request, response);
}
}
public void destroy() {
//Destroy code
}
}
I am using Eclipse IDE, a simple HelloServlet.java file and a simple index.jsp file. When I run the local server, the program starts but the following code does not execute:
/**
* #see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Init Firing: ");
}
I have the Console tab open, and the last statement I receive is: INFO: Server startup in 1442 ms. What might I do to get the init method to fire?
The container will only call the init() method of the servlet when it's called, not on the container startup.
If you want to start things on container startup, you can use the ContextListener as suggested here call method on server startup
This code works for me
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("xyz="+config.getInitParameter("xyz"));
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}
and web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>jsp</display-name>
<servlet>
<servlet-name>mySL</servlet-name>
<servlet-class>mine.MySL</servlet-class>
<init-param>
<param-name>xyz</param-name>
<param-value>123</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mySL</servlet-name>
<url-pattern>/MySL</url-pattern>
</servlet-mapping>
</web-app>
When the server starts, nothing happens, because the init() method is called when the servlet is called.
On the first servlet call (e.g. opening in your browser something like http://myserver.mydomain:8080/myapp/MySL), you'll get
xyz=123
doGet
On the second servlet call, you'll get
doGet
Please notice that this is the "old way" of declaring things. Nowadays, Servlets configuration can be made using annotations. Careful to not mix annotations with XML declarations for the same servlet.
Servlets with annotations look like this
package mine;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(urlPatterns = { "/OtherSL" }, initParams = { #WebInitParam(name = "abc", value = "456", description = "some parameter") })
public class OtherSL extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init(ServletConfig config) throws ServletException {
System.out.println("abc=" + config.getInitParameter("abc"));
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
}