Change response based on query string in java servlet - java

Im having some trouble sending diffrenet response based on query string, I have 2 String that suppose to match a single param from the query names serviceType:
private static String restartQuery = "restarts";
private static String dbStatusQuery = "dbStatus";
And my doGet function needs to send response accordingly:
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
String requestType = request.getParameter(serviceType);
// Set response content type
response.setContentType("text/html");
if(requestType.equals(restartQuery)){
//handle response for restartQuery
PrintWriter out = response.getWriter();
out.println("response for restart ....");
}else if (requestType.equals(dbStatusQuery)){
//handle response for dbStatusQuery
PrintWriter out = response.getWriter();
out.println("response for db ....");
}
}
The problem is that I get the same response(restart...), I had check the query string from the front-end - system.println(requestType) and they are different for each request, what can I change to make it work? if there is more code needed please comment below.

I have added 2 things based on comments here:
1- added consts to my defitions:
private static final String restartQuery = "restarts";
private static final String dbStatusQuery = "dbStatus";
2- check spaces from the front-end, just use a simple prefix check.
Thanks to all the helpers.

Related

I can not make a request and the Response to a servlet

I have a servlet. in it I form a line and when I type in the browser link, he told me that rotates the line. everything is fine. Now I want to create an array of strings, and depending on the parameter in the link rotates the particular row. how to do it?
#WebServlet("/goods")
public class GoodsServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("{\"name\":\"Pavel\",\"sname\":\"Petrashov\",\"age\":24,\"params\":{\"heigth\":188, \"weight\":72, \"strong\":100}}");
}
}
and I want to have
List<String> list = new ArrayList<String>();
list.add("{\"name\":\"Pavel\",\"sname\":\"Petrashov\",\"age\":24,\"params\":{\"heigth\":188, \"weight\":72, \"strong\":100}}");
list.add("{\"name\":\"Bill\",\"sname\":\"Gey\",\"age\":99,\"params\":{\"heigth\":188, \"weight\":70, \"strong\":100}}");
list.add("{\"name\":\"Uill\",\"sname\":\"Smitt\",\"age\":12,\"params\":{\"heigth\":188, \"weight\":99, \"strong\":100}}");
and to make sure that my reference http://localhost:666/sg/goodstook some parameter, depending on which will return an array element
Do you mean depending on GET parameters you want to print out one of the strings in the list? If that is what you want then
String myParameter = request.getParameter("param");
will give you the get parameter. Pass the parameter as a query string on the url like http://localhost:666/sg/goods?param=2.
Now use the parameter to get the string from your list
try{
int index = Integer.parseInt(myParameter);
out.println(list.get(index));
} catch(IndexOutOfBoundsException|NumberFormatException ex){
System.err.println("Invalid get parameter");
}

How to add a cookie using doTag method in custom tag?

I have developed a custom tag library in Java which I use in my web application.
I am not sure why but my doTag() is not setting up cookie at all. I have cleared my cache and restarted my computer as well. Here is the code:
public class UserVersionOfSite extends EvenSimplerTagSupport {
private static final Log logger = LogFactory.getLog(UserVersionOfSite.class);
private StringWriter sw = new StringWriter();
#Override
public void doTag() throws IOException, JspException {
getJspBody().invoke(sw); //get the tag body and put it in StringWriter object
//get request object to get cookie value
PageContext ctx = (PageContext)getJspContext();
HttpServletRequest httpServletRequest = (HttpServletRequest) ctx.getRequest();
HttpServletResponse httpServletResponse = (HttpServletResponse) ctx.getResponse();
if(httpServletRequest.getParameterMap().containsKey("show_full_site")) {
logger.debug("show_full_site ");
if(!checkIfCookieExists(httpServletRequest)){
Cookie cookie = new Cookie("SHOW_FULL_SITE",httpServletRequest.getParameter("show_full_site"));
cookie.setMaxAge(86400);
httpServletResponse.addCookie(cookie);
//write the tag output
if(!httpServletRequest.getParameter("show_full_site").equalsIgnoreCase("true")){
//write the response
getJspContext().getOut().println(sw.toString());
}
}else{
String cookieValueString = getCookieValue(httpServletRequest.getCookies(),"SHOW_FULL_SITE","false");
if(!cookieValueString.equalsIgnoreCase("true")){
//write the response
getJspContext().getOut().println(sw.toString());
}
}
}
}
#Override
public String getResult() throws IOException {
return "User version of site";
}
public String getCookieValue(Cookie[] cookies,
String cookieName,
String defaultValue) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
return(cookie.getValue());
}
return(defaultValue);
}
public boolean checkIfCookieExists(HttpServletRequest httpServletRequest){
logger.debug("inside checkIfCookieExists()");
boolean cookiePresent = Arrays.asList(httpServletRequest.getCookies()).contains( "SHOW_FULL_SITE" );
return cookiePresent;
}
}
Even I tried adding the code without using if else statements but still no success. Is there any thing critical I am missing?
Any ideas guys??!!! I have checked the browser's setting as well, but there is nothing there which is blocking a creation of cookie!
I realise the horse has probably bolted by the time I'm posting this but, for the benefit of others stumbling across it, I think the problem may be related to the feature of RequestDispatcher highlighted in this question: unable to add a cookie included in JSP via jsp:include
your following line inside checkIfCookieExists() method is wrong:
Arrays.asList(httpServletRequest.getCookies()).contains( "SHOW_FULL_SITE" );
HttpServletRequest.getCookies() returns Cookie[]. You are wrapping it inside a List and checking for a string "SHOW_FULL_SITE" inside this.
Coming back to your question- how do you know cookie is not being set in the HTTP headers? Try using browser plugins like firebug to see the HTTP response headers coming from server. Also set the path of cookie before adding it to response e.g.
Cookie cookie = new Cookie("SHOW_FULL_SITE",httpServletRequest.getParameter("show_full_site"));
cookie.setMaxAge(86400);
cookie.setPath("/");

More URL options HttpServletRequest

I pass parameters to the server line
"login=testAva4&nick=testAvaNick&social=vk&saurl=http://domain.example?param1=1&param2=2&param3=3&maurl=1"
waiting as the value saurl="http://domain.example?param1=1&param2=2&param3=3"
but i get http://domain.example?param1=1 and param2=2 param3=3
From Eclipse debug
req->_parameters
{maurl=1, nick=testAvaNick, param2=2, saurl=http://domain.example?param1=1, param3=3, social=vk, login=testAva4}
Gets the parameters in the code like this:
public class AddProfileServlet extends PlacerServlet {
//Add new profile method
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//Receive variables from URL
String login = req.getParameter("login");
String nick = req.getParameter("nick");
String social = req.getParameter("social");
String saurl = req.getParameter("saurl");
You should use URLEncoding on the saurl parameter.
Look at URLCodec at the commons codec enter link description here project.
I don't think you will need to encode the entire parameters part, but just the value for this specific parameter.
You can encode a string using:
URLCodec codec = new URLCodec();
String encodedValue = codec.encode(valueToEncode);
And you should use encodedValue as the value passed to the saurl parameter.

Java NullPointerException on HttpServletResponse line

Ok I am running the JSf application and I get an error of NullPointerException on line 220 which is
response.setContentType("text/html");
not sure why would this be the issue. The full method in which the line is present is below:
public void reserveDates(String eventTitle, Date startDate,
Date endDate, String requestType, int terminals,
String lastName, String firstName, String middleInitials,
int badgeNo, String networkID, String telephoneNo,
String orgCode, String justification)
throws ServletException, IOException{
MapCreation mapCreate = new MapCreation(startDate, endDate);
newMap = mapCreate.getDatesTreeMap();
MapStorage mapStore = new MapStorage();
mapStore.storeMap(newMap);
//create instance of reservation class
rsvObj = new Reservation(eventTitle, startDate,
endDate, requestType, terminals, lastName, firstName,
middleInitials, badgeNo, networkID, telephoneNo,
orgCode, justification);
boolean possible = rsvObj.checkRange();
if(possible == true)
{
try{
HttpServletResponse response = null;
response.setContentType("text/html");
response.sendRedirect("main");
CreateTempStorage();
}catch(IOException ioe){
System.err.print(ioe);
}
}else if(possible == false){
try{
HttpServletResponse response = null;
response.setContentType("text/html");
response.sendRedirect("error");
}catch(IOException ioe){
System.err.print(ioe);
}
}
}
P.s.: The response giving the error is in the first condition where i check if(possible==true)
I am just trying to use response to redirect to the pages mentioned either "main" or "error"
I appreciate the support.
Thanks!
you initialize response to null on the line immediately before the exception is thrown
response is null at that point. You set it to that right on the line before.
You need a concrete class that implements the abstract HttpServletResponse. If you have a class called MyHttpServletResponse that implements HttpServletResponse, then your code might look like this:
MyHttpServletResponse response = new MyHttpServletResponse();
(Perhaps you mean to use HttpServletResponseWrapper or something like that?)
Where is response assigned a value?
Also, your code has "poor" style. Consider replacing this
if (possible == true) {
...
else if (possible == false) { // there is no other possibility
...
}
with
if (possible) {
...
else {
...
}
HttpServletResponse response = null;
response.setContentType("text/html");
response.sendRedirect("main");
You cannot call a method on an object after you set it to null. You shouldn't set the response to null. There should be a response object around somewhere. Pass it to your method.
Well, the best option for an answer I believe was found in FacesContext. The code that replaced the redirection in this case was:
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext ec = facesContext.getExternalContext();
ec.redirect("progress.xhtml");
Hope this helps others. Regards,
The thing is if you are writing this code inside the servlet then you will already have the response object otherwise if you writing this code in any method then pass the response object from servlet while calling the method. Actually we need not create an object of HttpServletResponse.
try{
response.setContentType("text/html");
if(possible){
response.sendRedirect("main");
CreateTempStorage();
}else{
response.sendRedirect("error");
}
}catch(IOException ioe){
System.err.print(ioe);
}
A small improvement in code quality.

Get a URL from an Action name: Struts 2

In struts 2 there is a struts tag where you can specify an action name and it gives you the url to that action:
<s:url action="action_name" />
I've been looking for a while now to see if it is possible to do this in an Struts2 Action/Interceptor. I found the class that relates to this struts tag I think (org.apache.struts2.components.URL) but can't figure out how to use it.
This is as far as I got but it might not be how to use it (if its possible at all) but any method I call after this just gives me NullPointerExceptions.:
public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
URL url = new URL(ai.getStack(), request, response);
url.setAction("login");
//e.g. url.start(<with stringwriter>);
}
Hoping this can be done as it would save a lot of troube!
Thanks.
EDIT
URL url = new URL(invocation.getStack(), request, response);
url.setActionMapper(new DefaultActionMapper());
String redirectUrl = url.getUrlProvider().determineActionURL("action_name",
invocation.getProxy().getNamespace(), invocation.getProxy().getMethod(),
request, response, request.getParameterMap(), "http", true, true, false, false);
This code does work and gives me a redirect URL but I was wondering if there was a way to get the CURRENT ActionMapper rather than create a new one. I've done a quick google but can't find anything.
Well this is the method in the component class inside struts2 which is creating action URL
protected String determineActionURL(String action, String namespace, String method, HttpServletRequest req, HttpServletResponse res, Map parameters, String scheme,
boolean includeContext, boolean encodeResult, boolean forceAddSchemeHostAndPort, boolean escapeAmp)
{
String finalAction = findString(action);
String finalMethod = method == null ? null : findString(method);
String finalNamespace = determineNamespace(namespace, getStack(), req);
ActionMapping mapping = new ActionMapping(finalAction, finalNamespace, finalMethod, parameters);
String uri = actionMapper.getUriFromActionMapping(mapping);
return UrlHelper.buildUrl(uri, req, res, parameters, scheme, includeContext, encodeResult, forceAddSchemeHostAndPort, escapeAmp);
}
now the question is how we can get various values for this
action=invocation.getAction();
namespace=invocation.getProxy().getNamespace();
methos= invocation.getProxy().getMethod();
similar other values can be find out from ActionIvocation
This is just an idea and i have not applied it myself.Hope it might help you.
Here is how I get the CURRENT ActionMapper rather than create a new one:
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.dispatcher.mapper.ActionMapper;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.inject.Inject;
#Namespace("MyNamespace")
public class MyAction extends ActionSupport {
private ActionMapper actionMapper;
private UrlHelper urlHelper;
#Inject
public void setActionMapper(ActionMapper mapper) {
this.actionMapper = mapper;
}
#Inject
public void setUrlHelper(UrlHelper urlHelper) {
this.urlHelper = urlHelper;
}
private String getAbsoluteUrl(String actionName, String namespace) {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ActionContext context = ActionContext.getContext();
ActionInvocation invocation = context.getActionInvocation();
URL url = new URL(invocation.getStack(), request, response);
url.setActionMapper(actionMapper);
url.setUrlHelper(urlHelper);
return url.getUrlProvider().determineActionURL( //
actionName, //
namespace, //
"" , /* Method name */
request, response, //
request.getParameterMap(), "http", //
true, true, true, false);
}
// ...
}

Categories

Resources