Adding custom HTTP headers in java - java

I'm trying to create a simulation for our web Portal and need to add custom HTTP headers. I am to assume the user has already been authenticated and these headers are just for storing user information (ie, "test-header: role=user; oem=blahblah; id=123;").
I've setup a filter to extract the header information but I can't find a way to inject the header information. They don't want it to be stored in cookies and maybe they will want to setup a global filter to include the headers on every page; is it possible to do something like this with the filter interface or through any other methods?

You would need to utilize HttpServletRequestWrapper and provide your custom headers in when the various getHeader* methods are called.

Maybe you can store that information in the session:
import java.io.IOException;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* #author rodrigoap
*
*/
public class UserInfoFilter implements Filter {
/**
* #see javax.servlet.Filter#destroy()
*/
public void destroy() {
// TODO
}
/**
* #see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
* javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest))
throw new ServletException("Can only process HttpServletRequest");
if (!(response instanceof HttpServletResponse))
throw new ServletException("Can only process HttpServletResponse");
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpRequest.getSession().setAttribute("role", "user");
httpRequest.getSession().setAttribute("id", "123");
filterChain.doFilter(request, response);
}
/**
* #see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
public void init(FilterConfig filterConfig) throws ServletException {
// TODO
}
}

You can use addHeader.

Related

NullPointerException when `RequestDispatcher` is fired

I am using Retrofit to connect to my REST API. Please check the below code
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
*
* #author The Ace
*/
public class SignUpLoaderServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println("RUNNING!!!!!!!!!!!");
try {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.MESSAGING_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<List<ProfesionalBodyList>> call = endPoint.getAllProfesionalBodyLists();
call.enqueue(new Callback<List<ProfesionalBodyList>>() {
#Override
public void onResponse(Call<List<ProfesionalBodyList>> call, Response<List<ProfesionalBodyList>> rspn)
{
try {
List<ProfesionalBodyList> body = rspn.body();
for(int i=0;i<body.size();i++)
{
System.out.println(body.get(i).getProfessionalBody());
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/create-account.jsp");
requestDispatcher.forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public void onFailure(Call<List<ProfesionalBodyList>> call, Throwable ex) {
ex.printStackTrace();
}
});
} finally {
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
This code fires the below exception
java.lang.NullPointerException
at com.tekhinno.xxx.signup.SignUpLoaderServlet$1.onResponse(SignUpLoaderServlet.java:80)
at retrofit2.OkHttpCall$1.callSuccess(OkHttpCall.java:132)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:111)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
However if I replace the below code line into the finally() block, the issue is gone.
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/create-account.jsp");
requestDispatcher.forward(request, response);
I am not sure why it is not working inside the onResponse(). It is imporant to run there because I load items from the REST API before the forward action take place.
Any idea?
The issue is mainly because the call was Asynchronous and the requestDispatcher object was already executed. Then the answer is to stay until the REST call complete its work load. That means, do it Synchronous.
Retrofit can be done in Synchronous manner as well. Below is the code.
protected void processRequest(final HttpServletRequest request, final HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
System.out.println("RUNNING!!!!!!!!!!!");
try {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateTypeDeserializer());
Gson gson = gsonBuilder.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseURLs.MESSAGING_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
RestEndPointsInterface endPoint = retrofit.create(RestEndPointsInterface.class);
Call<List<ProfesionalBodyList>> call = endPoint.getAllProfesionalBodyLists();
body = call.execute().body();
for (int i = 0; i < body.size(); i++) {
System.out.println(body.get(i).getProfessionalBody());
}
} finally {
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/create-account.jsp");
request.setAttribute("ProfesionalBodyList", body);
requestDispatcher.forward(request, response);
}
}
Simpy pay attention to the place where it says call.execute().body();. This is the Synchronous call.

spring mvc-calling to function before controller functions are called

I want to create "pre" function. and in this function to check the session,
When some function in controller is called, I want that my "pre" function will called before it. and from the "pre" function I will pass the user to logIn page or to do the function.
something like this pseudo code:
if(!session)
return "redirect:login";
else
//calling to the selected function,
I saw some solutions to create this function, but the solution was to create it by: #ModelAttribute. and the problem is that with #ModelAttribute I didn't find any way to pass to another function in my controller.
More than, the selected function is always called after my #ModelAttribute finish,
How can I do that? there is a way to do something like this?
You can achieve that by using a servlet Filter. Here is a code snippet:
import java.io.IOException;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class RestrictionFilter implements Filter {
private static final String ACCES_PUBLIC = "/loginPage.jsp";
private static final String ATT_SESSION_USER = "user";
public void init( FilterConfig config ) throws ServletException {
}
public void doFilter( ServletRequest req, ServletResponse res, FilterChain chain ) throws IOException,
ServletException {
final HttpServletRequest request = (HttpServletRequest) req;
final HttpServletResponse response = (HttpServletResponse) res;
final HttpSession session = request.getSession();
/**
* check if user is not connected.
*/
if (session.getAttribute( ATT_SESSION_USER ) == null) {
/* Redirection to login page */
response.sendRedirect( request.getContextPath() + ACCES_PUBLIC );
} else {
/** access granted for the user*/
chain.doFilter( request, response );
}
}
public void destroy() {
}
}
Then add the filter to your web.xml like below:
<filter>
<filter-name>RestrictionFilter</filter-name>
<filter-class>yourPackage.RestrictionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RestrictionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Bypass jasig CAS authentication

I have integrated an application on tomcat to use Jasig Cas. Now i have made the entire application(SampleApp) to be authenticated by CAS. But there is a certain URL that i need to bypass this authentication i.e. (SampleApp/HomeListener).
I have written a new application Filter for this. But what parameter do i need to modify in the Servlet request object to achieve this.
Filter
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class PatternFilter implements Filter {
private FilterConfig config;
public void destroy() {
//nothing here
}
/**
* Filters the HTTP requests
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filter) throws IOException, ServletException {
filter.doFilter(request, response);
}
public void init(FilterConfig filterConfiguration) throws ServletException {
// TODO Auto-generated method stub
config = filterConfiguration;
}
}
You do not need to write your own filter. Try adding the "ignorePattern" parameter to your authentication filter configuration in your web.xml.
<init-param>
<param-name>ignorePattern</param-name>
<param-value>http://<your url pattern to bypass>/(.*)</param-value>
</init-param>

Authentication Filter in java, help me in removing this error

the error comes at "session = request.getSession();"
when i alter dofilter() method as a normal method "dofilter(HttpServletRequest request, HttpServletResponse response)" then i have to make a real "dofilter(ServletRequest request, ServletResponse response)" method.
package pk.edu.zab.cs;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.*;
/**
* Servlet Filter implementation class AuthenticationFilter
*/
public class AuthenticationFilter implements Filter {
/**
* Default constructor.
*/
public AuthenticationFilter() {
// 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 {
// TODO Auto-generated method stub
// place your code here
String username = request.getParameter("username");
String password = request.getParameter("password");
HttpSession session = null;
RequestDispatcher dispatcher = null;
if (("admin".equalsIgnoreCase(username) && "mypass".equals(password))) {
session = request.getSession(); //the error comes here but when i remove i have to make this dofilter() method as a normal method which use HttpServletRequest and afterwards I have to make the original dofilter() method with ServletRequest.
session.setAttribute("username", username);
dispatcher = request.getRequestDispatcher("Welcome.jsp");
} else {
dispatcher = request.getRequestDispatcher("failure.jsp");
}
dispatcher.forward(request, response);
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* #see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
When you override a method, the signature of your method must match with the signature of the overridden method. So you can't change the type of the arguments of the method. That's basic OO, that you should learn before using servlets.
Now, you know that the servlet request, of type ServletRequest, is actually an HttpServletRequest. So cast it, to be able to get the associated session:
HttpServletRequest httpRequest = (HttpServletRequest) request;
session = httpRequest.getSession();
And, final note: always read error messages. They contain valuable information. If you can't understad them, then post them, so that we know precisely what and where the error is, and that we can explain the message to you.

Best Way to output SoyTemplates from a Servlet

What is the best waya to render or output Soy Templates from closure-templates to a browser?
Currently i have the following:
package de.envisia.erp.web.servlet;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
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 com.google.template.soy.SoyFileSet;
import com.google.template.soy.tofu.SoyTofu;
/**
* Servlet implementation class EntryPoint
*/
#WebServlet("/EntryPoint")
public class EntryPoint extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public EntryPoint() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext servletContext = this.getServletContext();
String pathContext = servletContext.getRealPath("/WEB-INF/");
//response.getWriter().println(pathContext);
SoyFileSet sfs = new SoyFileSet.Builder().add(new File(pathContext + "\\templates\\hello.soy")).build();
SoyTofu tofu = sfs.compileToTofu();
String out = tofu.newRenderer("hello.world").render();
response.getWriter().println(out);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
But i don't think it is a good practice to use the println or even print() method of the response object, are there any better ways?
Take a look at https://github.com/codedance/silken.
The basic idea is to make a special servlet and forward requests to it:
RequestDispatcher rd = getServletContext().getRequestDispatcher("/soy/products.boat.sailingBoatView");
rd.forward(req, resp);

Categories

Resources