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.
Related
I have an interface and a servlet file ,whenever I try to run the application program it gives me following error
SEVERE: Class [ LDir/DirSessionLocal; ] not found. Error while loading [ class DirServlet ]
code for interface
package Dir;
import javax.ejb.Local;
#Local
public interface DirSessionLocal {
String getContact(String name1);
String getDetails(String name2);
void rater(String r);
}
code for servlet
import Dir.DirSessionLocal;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
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(urlPatterns = {"/DirServlet"})
public class DirServlet extends HttpServlet {
#EJB
private DirSessionLocal dirSession;
/**
* 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(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet DirServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet DirServlet at " + request.getParameter("name") + "</h1>");
out.println("<br>");
out.println("<h1>" + request.getParameter("nameD") + "</h1>");
out.println("<br>");
out.println("<h1>" + request.getParameter("rate") + "</h1>");
String a=request.getParameter("nameD");
if(a.equals("abc"))
out.println("<h1>" + dirSession.getContact(a) + "</h1>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
// <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);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
It means that the JVM running your servlet / webapp cannot find the ".class" file for a class with the name Dir.DirSessionLocal.
Depending on how you are "deploying" your servlet, you either need to add the missing class to a JAR file, an WAR file, the webapp's tree on the web server, etc.
I did use OpenID 2.0 which is going to be deprecated (obsolete) in 2015 for Google. What is a simple way to migrate if I'm using servlets?
Here is an example of servlet app that supports "login with Google".You can do OAuth2 to Google with servlets.
https://github.com/riversun/google-login-servlet-example-on-jetty.git
I spent several hours reading from Google website and if you think that Google API Client is unfriendly or over complex you should continue reading this. I took look at Apache Oltu, however, the documentation doesn't have example for Google and also I've found several people complaining. Finally, after several hours of frustration and Googling, somehow I stumbled across great post
http://highaltitudedev.blogspot.com/2013/10/google-oauth2-with-jettyservlets.html
So I accomodated it to my needs.
This is how I build login request :
public static String getOauthUrlGoogle(HttpServletRequest request) {
String redirectUrl = "http://www.tralev.com/web/oauth2callback";
if (Html.isRunningLocally()) {
redirectUrl = "http://localhost:8080/TralevServer/web/oauth2callback";
}
StringBuilder oauthUrl = new StringBuilder();
oauthUrl.append("https://accounts.google.com/o/oauth2/auth")
.append("?client_id=").append(GOOGLE_CLIENT_ID) // the client id from the api console registration
.append("&response_type=code")
.append("&scope=profile%20email") // scope is the api permissions we are requesting
.append("&redirect_uri=").append(redirectUrl) // the servlet that google redirects to after authorization
.append("&state=").append(request.getSession().getId())
//.append("&access_type=offline") // here we are asking to access to user's data while they are not signed in
.append("&approval_prompt=force"); // this requires them to verify which account to use, if they are already signed in
return oauthUrl.toString();
}
And this is Servlet which performs the rest:
package com.tralev.server.web;
import commons.StringUtils;
import commons.UsualHtmlUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
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.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* #author mladen
*/
#WebServlet(name = "OAuth2CallbackServlet", urlPatterns = {"/web/oauth2callback"})
public class OAuth2CallbackServlet extends HttpServlet {
public static String GOOGLE_CLIENT_ID = "your id";
public static String GOOGLE_CLIENT_SECRET = "your secret";
public String getCallbackUrl() {
String redirectUrl = "http://www.tralev.com/web/oauth2callback";
if (Html.isRunningLocally()) {
redirectUrl = "http://localhost:8080/TralevServer/web/oauth2callback";
}
return redirectUrl;
}
/**
* 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(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// google redirects with
//http://localhost:8089/callback?state=this_can_be_anything_to_help_correlate_the_response%3Dlike_session_id&code=4/ygE-kCdJ_pgwb1mKZq3uaTEWLUBd.slJWq1jM9mcUEnp6UAPFm0F2NQjrgwI&authuser=0&prompt=consent&session_state=a3d1eb134189705e9acf2f573325e6f30dd30ee4..d62c
// if the user denied access, we get back an error, ex
// error=access_denied&state=session%3Dpotatoes
if (req.getParameter("error") != null) {
Html.printPage(req, resp, "Error", StringUtils.toString(req.getParameter("error")));
} else {
// google returns a code that can be exchanged for a access token
String code = req.getParameter("code");
LinkedHashMap<String, String> params = new LinkedHashMap<String, String>();
params.put("code", code);
params.put("client_id", GOOGLE_CLIENT_ID);
params.put("client_secret", GOOGLE_CLIENT_SECRET);
params.put("redirect_uri", getCallbackUrl());
params.put("grant_type", "authorization_code");
// get the access token by post to Google
String body = post("https://accounts.google.com/o/oauth2/token", params);
// ex. returns
// {
// "access_token": "ya29.AHES6ZQS-BsKiPxdU_iKChTsaGCYZGcuqhm_A5bef8ksNoU",
// "token_type": "Bearer",
// "expires_in": 3600,
// "id_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjA5ZmE5NmFjZWNkOGQyZWRjZmFiMjk0NDRhOTgyN2UwZmFiODlhYTYifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwiZW1haWxfdmVyaWZpZWQiOiJ0cnVlIiwiZW1haWwiOiJhbmRyZXcucmFwcEBnbWFpbC5jb20iLCJhdWQiOiI1MDgxNzA4MjE1MDIuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdF9oYXNoIjoieUpVTFp3UjVDX2ZmWmozWkNublJvZyIsInN1YiI6IjExODM4NTYyMDEzNDczMjQzMTYzOSIsImF6cCI6IjUwODE3MDgyMTUwMi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImlhdCI6MTM4Mjc0MjAzNSwiZXhwIjoxMzgyNzQ1OTM1fQ.Va3kePMh1FlhT1QBdLGgjuaiI3pM9xv9zWGMA9cbbzdr6Tkdy9E-8kHqrFg7cRiQkKt4OKp3M9H60Acw_H15sV6MiOah4vhJcxt0l4-08-A84inI4rsnFn5hp8b-dJKVyxw1Dj1tocgwnYI03czUV3cVqt9wptG34vTEcV3dsU8",
// "refresh_token": "1/Hc1oTSLuw7NMc3qSQMTNqN6MlmgVafc78IZaGhwYS-o"
// }
JSONObject jsonObject = null;
// get the access token from json and request info from Google
try {
jsonObject = (JSONObject) new JSONParser().parse(body);
} catch (ParseException e) {
throw new RuntimeException("Unable to parse json " + body);
}
// google tokens expire after an hour, but since we requested offline access we can get a new token without user involvement via the refresh token
String accessToken = (String) jsonObject.get("access_token");
// you may want to store the access token in session
req.getSession().setAttribute("access_token", accessToken);
// get some info about the user with the access token
String json = get(new StringBuilder("https://www.googleapis.com/oauth2/v1/userinfo?access_token=").append(accessToken).toString());
try {
jsonObject = (JSONObject) new JSONParser().parse(json);
} catch (ParseException e) {
throw new RuntimeException("Unable to parse json " + body);
}
String email = (String) jsonObject.get("email");
String fullName = (String) jsonObject.get("name");
Logger.getLogger(this.getClass().getName()).log(Level.INFO, "email= {0} ,name={1}", new Object[]{email, fullName});
//do the rest stuff
}
}
// makes a GET request to url and returns body as a string
public String get(String url) throws ClientProtocolException, IOException {
return execute(new HttpGet(url));
}
// makes a POST request to url with form parameters and returns body as a string
public String post(String url, Map<String, String> formParameters) throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}
request.setEntity(new UrlEncodedFormEntity(nvps));
return execute(request);
}
// makes request and checks response code for 200
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}
return body;
}
// <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);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private String getAfterLoginUrl(HttpServletRequest req) {
String afterLoginUrl = "http://www.tralev.com/web/main";
if (Html.isRunningLocally()) {
afterLoginUrl = "http://localhost:8080/TralevServer/web/main";
}
return afterLoginUrl;
}
}
Hope you'll find this useful or original post, I spent many hours looking into other overcomplex libraries and this was exactly what I was looking for.
I'm having a hard time with this code, every time I test and run it, I always get the same error but cant seem to fix it. The error I'm getting is, can anyone help? Its the last thing I need to get done to get this project working!
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
Servlets.addFunds.processRequest(addFunds.java:43)
Servlets.addFunds.doPost(addFunds.java:95)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.34 logs.
/*
* To change this template, choose Tools > Templates
and open the template in the editor.
*/
package Servlets;
import beans.UserBean;
import eventaccess.DatabaseConnector;
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;
import javax.servlet.http.HttpSession;
/**
*
* #author sberry3
*/
#WebServlet(name = "addFunds", urlPatterns = {"/addFunds"})
public class addFunds 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(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = null;
double addFunds = Double.parseDouble(request.getParameter("addFunds"));
String username = request.getParameter("username");
HttpSession session = request.getSession();
UserBean userSession = (UserBean) session.getAttribute("userSession");
double balance = userSession.getBalance();
balance = balance + addFunds;
userSession.setBalance(balance);
session.setAttribute("userSession", userSession);
DatabaseConnector db = new DatabaseConnector();
String queryString = "UPDATE USERS SET balance=" + balance + " WHERE userID=" + userSession.getUserID();
try {
db.createConnection();
db.pstmt = db.conn.prepareStatement(queryString);
db.pstmt.execute();
db.closeConnection();
url = "/store.jsp";
} catch (Exception e) {
e.printStackTrace();
response.setHeader("dbError", "Coudn't connect to database");
}
request.getRequestDispatcher(url).forward(request, response);
}
// <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);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
It's hard to tell exactly what line it is where your NullPointerException is happening.
Some possibilities:
Missing request parameters. For example, if you requested the page without including the addFunds parameter, you get a NullPointerException on this line:
double addFunds = Double.parseDouble(request.getParameter("addFunds"));
Missing session attribute:
What does the line
UserBean userSession = (UserBean) session.getAttribute("userSession");
return? Is userSession null? If so then later on:
userSession.setBalance(balance);
would cause a NullPointerException. I thinks that's the most likely problem. Do you something like
session.setAttribute("userSession", new UserSession());
anywhere?
On your first request to this jsp
HttpSession session = request.getSession();
will create a new session since there isn't an existing one. So
UserBean userSession = (UserBean) session.getAttribute("userSession");
will set userSession to null, since no Attribute userSession has been created up to this point.
Servlet Mapping
I am new to java ee 6.I am trying to get a servlet request.Every other mapping works fine except /category mapping. Here is my ControllerServlet class.I have used #webServlet annotion for mapping.I have tried to do the mapping in web.xml but no luck.Using netbeans IDE 7.2,Server Glassfish opensource.
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(name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/addToCart",
"/viewCart",
"/updateCart",
"/checkout",
"/purchase",
"/chooseLanguage",
"/category"})
public class ControllerServlet extends HttpServlet {
/**
* 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 {
String userPath = request.getServletPath();
// if cart page is requested
if (userPath.equals("/viewCart")) {
userPath = "/cart";
}
//if category page is requested
else if (userPath.equals("/category")) {
}
// if ckeckout page is requested
else if (userPath.equals("/checkout")){
// System.out.println("check");
}
// if user switches language
else if (userPath.equals("/chooseLanguage")){
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/View" + userPath + ".jsp";
System.out.print(url);
try{
request.getRequestDispatcher(url).forward(request, response);
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* 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 {
String userPath = request.getServletPath();
// if addToCart action is called
if (userPath.equals("/addToCart")) {
// TODO: Implement add product to cart action
// if updateCart action is called
} else if (userPath.equals("/updateCart")) {
// TODO: Implement update cart action
// if purchase action is called
} else if (userPath.equals("/purchase")) {
// TODO: Implement purchase action
userPath = "/confirmation";
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Link to image of web-inf directory
/categories is not mapped in your servlet. /category is mapped however.
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.