More URL options HttpServletRequest - java

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.

Related

Change response based on query string in java servlet

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.

How to get the text from addTextBody in a MultipartEntityBuilder?

I am using an Android client to post data and some file in Google cloud storage:
MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
entityBuilder.addBinaryBody("file", file);
entityBuilder.addTextBody("author", author);
On the server side I am using a servlet to get that request.
However, while I am able to get the file and store it, I don't know how to get what's in the addTextBody (the "author" String in my case)
I have been searching for a while and just found someone that posted quite the same question but no one answered him. (How to get the text from a addTextBody in a miltipartentitybuilder)
Assuming you're using Servlet 3.0+, just use HttpServletRequest#getParts(). For example, if you wanted the content of the multipart part named author, you'd configure your servlet with #MultipartConfig, retrieve the appropriate Part object and consume its InputStream.
#MultipartConfig()
#WebServlet(urlPatterns = { "/upload" })
public class UploadServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Collection<Part> parts = req.getParts();
for (Part part : parts) {
if (!part.getName().equals("author"))
continue;
try (InputStream in = part.getInputStream()){
String content = CharStreams.toString(new InputStreamReader(in));
System.out.println(content); // prints the value of author
}
}
}
}

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");
}

Parse HttpServletRequest contains jsonp string

When I try to send cross-domain jsonp request with:
$.getJSON(url + "?callback=?",
value : 'John',
record : {
value : 'a',
list : [ 1, 2 ]
});
Then i try to get it with java servlet like this:
public class TestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String output = request.getParameter("callback")
+ "({\"response\":\"test\"});";
response.setContentType("application/javascript;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(output);
}
}
Inside servlet request string has parameter names:
_=1353482336546
value=John
record[value]=a
How can i parse request string to original JSON?
Im using embedded jetty server and I want to use "JSON to Object" jetty parser on JSON string
You can apply flexjson to parse json string to an object. Please take a look at:
live example
flexjson library

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