Previous page reloaded after pressing back button - java

I'm trying to do a servlet filter for a JSP project. What I want to do is to disallow a user to go back to previous page once he logouts. I followed this tutorial:
Prevent user from seeing previously visited secured page after logout
So I have this java file as my Filter class (file name is LogoutFilter.java):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class LogoutFilter implements Filter {
FilterConfig config;
#Override
public void destroy() {
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse hsr = (HttpServletResponse) res;
hsr.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
hsr.setHeader("Pragma", "no-cache"); // HTTP 1.0.
hsr.setDateHeader("Expires", 0); // Proxies
chain.doFilter(req, res);
}
#Override
public void init(FilterConfig config) throws ServletException {
// TODO Auto-generated method stub
this.config = config;
}
}
I've also added the filter entry in my web.xml page. And the filter is working as I've checked it but the back button is still taking it back to the previous page after logout.
Here is my logout page where "admin_name" is a variable which I've added to session attribute during login.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page session="false" %>
<!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>
<%
HttpSession session = request.getSession(false);
String admin_name = (String)session.getAttribute("admin_name");
session.invalidate();
admin_name="";
response.sendRedirect("admin_login.jsp");
%>
</body>
</html>
I can't understand what am I doing wrong.

Related

My application with Spring Security don't go beyond login page

I just started a project with uses Spring Security for authentication which uses Java configuration instead XML. That's my class SecurityConfig.java:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("kleber")
.password("123")
.roles("USER");
}
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/spring/index").permitAll()
.loginProcessingUrl("/spring/login").permitAll()
.usernameParameter("login")
.passwordParameter("senha")
.defaultSuccessUrl("/spring/home")
.failureUrl("/spring/erro-login")
.and()
.logout()
.logoutUrl("/spring/logout")
.logoutSuccessUrl("/spring/index").permitAll();
}
}
With this configuration, I can reach the login page, but after I inform my credencials (username and password) the system return to this same login page, despite the username and password informed are correct.
All this URLs informed in the class SecurityConfig are mapped in this controller:
#Controller
#RequestMapping(value="spring")
public class SpringController {
#RequestMapping(value="index")
public ModelAndView index() {
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
return mav;
}
#RequestMapping(value="home")
public ModelAndView home() {
ModelAndView mav = new ModelAndView();
mav.setViewName("home");
return mav;
}
#RequestMapping(value="doLogin", method=RequestMethod.POST)
public void doLogin(HttpServletRequest request, HttpServletResponse response) {
//
}
#RequestMapping(value="logout")
public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath());
}
}
What I am doing wrong?
-->Still related to topic above:
I need implement this 'loginProcessingUrl', which is mapped in my controller this way:
#RequestMapping(value="doLogin", method=RequestMethod.POST)
public void doLogin(HttpServletRequest request, HttpServletResponse response) {
//
}
I already have in my application two classes which, according to the articles I read, will be necessary for this process, but I could be wrong and maybe i need another approach:
SampleAuthenticationManager
public class SampleAuthenticationManager implements AuthenticationManager {
static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
static
{
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_USER"));
}
public Authentication authenticate(Authentication auth) throws AuthenticationException
{
if (auth.getName().equals(auth.getCredentials()))
{
return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES);
}
throw new BadCredentialsException("Bad Credentials");
}
}
DefaultAuthenticationProcessingFilter
public class DefaultAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {
private static final String INTERCEPTOR_PROCESS_URL = "/spring/doLogin";
private static AuthenticationManager am = new SampleAuthenticationManager();
protected DefaultAuthenticationProcessingFilter() {
super(INTERCEPTOR_PROCESS_URL);
// TODO Auto-generated constructor stub
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
// TODO Auto-generated method stub
String login = request.getParameter("login");
String senha = request.getParameter("senha");
Authentication input = new UsernamePasswordAuthenticationToken(login, senha);
Authentication output = null;
try {
output = am.authenticate(input);
SecurityContextHolder.getContext().setAuthentication(output);
getSuccessHandler().onAuthenticationSuccess(request, response, output);
} catch (AuthenticationException failed) {
getFailureHandler().onAuthenticationFailure(request, response, failed);
}
return output;
}
}
In this scenario, how I should implement the method doLogin from my controller? Take in consideration that in this moment I am using inMemory authentication, for later extend my project for use a database.
Ok, I managed to solve my problem; it happens I make some mess with the Url informed in the SecurityConfig and the Url's in my views. I need remember in the future: in the class, use always //. In the view, always use .
In my case, the views was written this way:
index.jsp -> the login page
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# 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>
<c:url value="/spring/login" var="loginUrl"/>
<form method="post" action="${loginUrl}">
usuário: <input type="text" name="login" size=20> <br/>
senha: <input type="password" name="senha" size=20> <br/>
<input type="submit" value="entrar"> <br/>
</form>
</body>
</html>
home.jsp -> the "destiny" page (dashboard): only for test purposes in this state of project
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# 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>
<h2>
<c:out value="${pageContext.request.remoteUser}"/>
Logout
</h2>
</body>
</html>
Final code for the class SecurityConfig.java
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("kleber")
.password("123")
.roles("USER");
}
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/css/**", "/fonts/**", "/image/**", "/js/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/spring/index").permitAll()
.loginProcessingUrl("/spring/login").permitAll()
.usernameParameter("login")
.passwordParameter("senha")
.successHandler(new CustomAuthenticationSuccessHandler())
.failureHandler(new CustomAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/spring/logout")
.logoutSuccessUrl("/spring/index").permitAll();
}
}

Result redirection not working with jsp

I'm getting a ping result in my servlet.I'm trying to redirect it to another jsp file.
the jsp file for output opens.But nothing shows in it.
This is my servlet main code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String ip = request.getParameter("ip");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// out.println("The ip address is:"+ip+"\n");
String result = pingTest(ip);
out.println(result);
String redirect = "Output.jsp";
RequestDispatcher view = request.getRequestDispatcher(redirect);//Is it good approach to redirect request in ajax based servlet?
view.forward(request, response);
}
This is my output.jsp page
<%# 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>Ping Check Result</title>
</head>
<body>
</body>
</html
Do I need to add anything in output.jsp?
In your servlet:
request.setAttribute("result", result);
request.getRequestDispatcher("/WEB-INF/Output.jsp").forward(request, response);
In your JSP:
<pre>The data from servlet: ${result}</pre>
your servlet must be :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String ip = request.getParameter("ip");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("The ip address is:"+ip+"\n");
String result = pingTest(ip);
out.println(result);
RequestDispatcher view = request.getRequestDispatcher();
view.forward(request, response);
}

neglect it--------------Sending an array to servlet from jsp page and recieving it in servlet------------ neglect it

*
neglect it
*
I am lerner in JSP and java field. I am stuck in a problem. I hv mentioned my code below.
My JSP 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>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$("#save").click( function ()
{
var arrayxx= new Array(5);
arrayxx[0]=0;
arrayxx[1]=3;
arrayxx[2]=4;
arrayxx[3]=9;
$.get('Save1',{arrayX:arrayxx},function(responseJson)
{
} );
});
});
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" id="save" value="save" ></input>
</body>
</html>
My servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Save1 extends HttpServlet {
private static final long serialVersionUID = 1L;
public Save1() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("INSIDE SERVLET");
String [] yourList = request.getParameterValues("arrayX");
System.out.println(request.toString());
System.out.println(yourList[0]);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
I cant able to pass the array from JSP to servlrt.
Please help me with this. When i receive the array, i found that array does not contain any element.
Thanks in advance
As per your requirement I would suggest you to go for ajax like this way
$.ajax(
{
type: "POST",
url: "servlet", //Your full URL goes here
data: { parametername: parametervalue},
success: function(data, textStatus, jqXHR){
//alert(data);
}

doPost() of GAE servlet doesn't work

I'm begginer in JSP and I have the following servlet:
#SuppressWarnings("serial")
public class HelloAppIgorServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
RequestDispatcher disp = req.getRequestDispatcher("/mainpage.jsp");
disp.forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
pw.print("Test");
pw.close();
}
}
and one JSP file called mainpage.jsp:
<%# 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>
<p>Hello there!<p>
<form action="." method="post">
<input type="text" name="name1" />
<input type="submit" value="name2" />
</form>
</body>
</html>
The problem is that doPost() method doesn't work. It's redirecting me to index.html page when I click the button. I'm sure that problem is not in servlets, so where can it be?
You need to set the appropriate action in <form action="." method="post">. The action is the (relative) URL of the servlet that you defined via <servlet-mapping> in the web.xml.

How do I call an arrays methods from the JSP page in JSTL?

I stumbled upon servlets and I just love them compared to scriptlets since they perfectly divide logic and view. But I'm having trouble calling instance methods in my JSP page.
I have the following JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>
<c:forEach items="${stringarray}">
${stringarray}
<br/>
</c:forEach>
</body>
</html>
And the following Servlet:
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Servlet
*/
#WebServlet("/Servlet")
public class Servlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Servlet()
{
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String[] strarray = new String[5];
strarray[0] = "zero";
strarray[1] = "one";
strarray[2] = "two";
strarray[3] = "three";
strarray[4] = "four";
request.setAttribute("stringarray", strarray);
request.getRequestDispatcher("index.jsp").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
}
}
Why can't I call the arrays methods with the dot separator in my JSP page?!
I think what you're looking for is the following:
<c:forEach var="stringElement" items="${stringarray}">
${stringElement}
<br/>
</c:forEach>
The c:forEach tag loops over each element in the ${stringarray}, but to access each item, you have to define a variable. See also the TLD docs

Categories

Resources