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.
Related
This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
Exact error: The requested resource [/Register/] is not available. Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
I am using tomcat and Eclipse.
Here is the code:
RegisterDao.java
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class RegisterDao {
private String dbUrl = "jdbc:mysql://localhost:3306/explorecalifornia";
private String dbUname = "dbuser";
private String dbPassword = "dbpassword";
private String dbDriver = "com.mysql.cj.jdbc.Driver";
public void loadDriver(String dbDriver)
{
try {
Class.forName(dbDriver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection()
{
Connection con = null;
try {
con = DriverManager.getConnection(dbUrl, dbUname, dbPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
public String insert(Member member)
{
loadDriver(dbDriver);
Connection con = getConnection();
String result = "Data entered successfully";
String sql = "insert into member values(?,?,?,?)";
PreparedStatement ps;
try {
ps = con.prepareStatement(sql);
ps.setString(1, member.getUname());
ps.setString(2, member.getPassword());
ps.setString(3, member.getEmail());
ps.setString(4, member.getPhone());
ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = "Data not entered";
}
return result;
}
}
Register.java
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;
#WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
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());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uname = request.getParameter("uname");
String password = request.getParameter("password");
String email = request.getParameter("email");
String phone = request.getParameter("phone");
Member member = new Member(uname, password, email, phone);
RegisterDao rDao = new RegisterDao();
String result = rDao.insert(member);
response.getWriter().print(result);
}
}
web.xml
<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>Registration</display-name>
<welcome-file-list>
<welcome-file>memberRegistration.jsp</welcome-file>
</welcome-file-list>
</web-app>
and memberRegistration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="memberRegistration" method="post">
<table>
<tr><td>User Name: </td><td><input type="text" name="uname"></td></tr>
<tr><td>Password: </td><td><input type="password" name="password"></td></tr>
<tr><td>Email: </td><td><input type="text" name="email"></td></tr>
<tr><td>phone: </td><td><input type="text" name="phone"></td></tr>
<tr><td></td><td><input type="submit" value="register"></td></tr>
</table>
</form>
</body>
</html>
Need to place the servlet class in a java package. You should always put publicly reusable Java classes in a package, otherwise they are invisible to classes which are in a package, such as the server itself.
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">
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
While running my application on tomcat server class not found exception occur in my windows 8.1 PC but this program run correctly in windows XP PC.
My servlet application contains two java file and four html file. I have to run this application on windows 8.1 Operating System
Please do not use eclipse to run this Program
This is the signin.java file for the registered user.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class signin extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
PrintWriter out=res.getWriter();
String user=req.getParameter("un");
String pass=req.getParameter("ps");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:mail");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from userinfo where user_name='"+user+"' and user_pass='"+pass+"' ");
if(rs.next())
{
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/welcome.html");
rd.forward(req,res);
}
else
{
ServletContext sc=getServletContext();
RequestDispatcher rd=sc.getRequestDispatcher("/error.html");
rd.forward(req,res);
}
}
catch(Exception ex)
{
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException
{
doGet(req,res);
}
}//end of signin
This is the signup file for my new user.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class signup extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter out=res.getWriter();
String yr=req.getParameter("yn");
String un=req.getParameter("un");
String ps=req.getParameter("ps");
String sq=req.getParameter("sq");
String ans=req.getParameter("ans");
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("Jdbc:Odbc:mail");
Statement st=con.createStatement();
st.executeUpdate("insert into userinfo values ('"+yr+"','"+un+"','"+ps+"','"+sq+"','"+ans+"')");
st.close();
con.close();
out.println("<h1>your account has been created successfully </h1>");
}
catch(SQLException ex)
{
out.println("<h1> User name is already present try with different name </h1>");
}
catch(ClassNotFoundException ex)
{
out.println("<h1> Servlet Error </h1>");
}
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
doGet(req,res);
}
}
And My Web.xml file
<web-app>
<display-name>Simple Servlet Program</display-name>
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>signup</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/xyz</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>pqr</servlet-name>
<servlet-class>signin</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>pqr</servlet-name>
<url-pattern>/a</url-pattern>
</servlet-mapping>
</web-app>
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
}
}