I want send を伴う出力となって to backend java code via http get request.
My get call url is http://localhost:8080/test/getID?id=%E3%82%92%E4%BC%B4%E3%81%86%E5%87%BA%E5%8A%9B%E3%81%A8%E3%81%AA%E3%81%A3%E3%81%A6
Java code:
#RequestMapping(value = "/getCaseId")
public ModelAndView showCaseId(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String msg = request.getParameter("id");
System.out.println("URL:"+msg);
return new ModelAndView("showID", "idList", null);
}
Above piece of code prints URL:ãä¼´ãåºåã¨ãªã£ã¦.
So what's change i need to do get the exact Japanese text what i have passed from front end.
Try changing your msg line to:
String msg = new String(
request.getParameter("id").getBytes(StandardCharsets.ISO_8859_1),
StandardCharsets.UTF_8
);
If that will work it means that your application server (Tomcat? jetty?) is not configured correctly to handle UTF-8 in URLs.
If you use eclipse IDE, you need to check Text File encoding. Please check with the following figure.
The problem is that the submitted query string is getting mutilated on the way into your server-side script, because getParameter() uses ISO-8559-1 instead of UTF-8.
So i modified my code as below and now its working
#RequestMapping(value = "/getCaseId")
public ModelAndView showCaseId(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
String msg = new String(request.getParameter("id").getBytes("iso-8859-1"), "UTF-8")
System.out.println("URL:"+msg);
return new ModelAndView("showID", "idList", null);
}
I found this solution in http://help-forums.adobe.com/content/adobeforums/en/experience-manager-forum/adobe-experience-manager.topic.html/forum__lxgr-hi_i_am_havi.html.
Related
In the development of springboot project, a requirement needs to forward the error Chinese information string to the corresponding controller for processing, so I first use urlencoder Encode (message, "UTF-8"), then splice the encoded string to the URL, and use httpservletresponse.Sendredirect("url") redirects to the target controller with the following code:
private void responseError(ServletResponse response, String message) {
try {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
message = URLEncoder.encode(message, "UTF-8");
httpServletResponse.sendRedirect("/unauthorized/" + message);
} catch (IOException e) {
e.printStackTrace();
}
}
In the controller, use #Requestmapping(value = "/unauthorized/{message}") to get the dynamic parameter message on the path. The code is as follows:
#RequestMapping(value="/unauthorized/{message}")
public ResultMap unauthorized(#PathVariable("message") String message){
return ResultMap.fail(message);
}
During the test, it is found that the encoded Chinese string is similar to the form of %E7%99%BB%E5%BD%95%E8%Ba%AB%E4%BB%BD%E5%A4%B1%E6%95%88. During redirection, the request keeps cycling. The controller cannot capture the request, and finally reports an error: exceeded maxredirects Probably stuck in a redirect loop.
However, after I remove % from the parameter string, the controller method can capture and process the request normally. Therefore, I guess #Requestmapping() cannot match the special character %. Does anyone have a solution?
I'm receiving a file using multipart/form-data like I'll show you right below (Using Spark, not SpringBoot):
#Override
public Object handle(Request request, Response response) throws Exception {
request.attribute("org.eclipse.jetty.multipartConfig", new MultipartConfigElement(""));
Part filePart = request.raw().getPart("file");
String regex = request.raw().getParameter("regex");
String fileName = filePart.getSubmittedFileName();
byte[] fileBytes = filePart.getInputStream().readAllBytes();
The thing is, I want to unit test this Controller, and in order to do so, I need a way to mock the request to have a multipart/form-data inside, or at least a way to use "when...theReturn" to mimic that part of code...
Any ideas?
Thanks in advance!
So I managed to find the answer to this question and I thought maybe I could help other people by answering it:
#Test
public void whenValidRegex_returnOkAndTotalAmount() throws Exception {
final Part file = mock(MultiPartInputStreamParser.MultiPart.class);
final Request mock = mock(Request.class); //Spark request
final Response mockResponse = mock(Response.class); //Spark response
final HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); //Javax servlet
when(mock.raw()).thenReturn(httpServletRequest);
when(file.getSubmittedFileName()).thenReturn("file.pdf");
when(mock.raw().getParameter("regex")).thenReturn(String.valueOf("SOME REGEX"));
when(mock.params("numPage")).thenReturn(String.valueOf("1"));
when(file.getInputStream()).thenReturn(IOUtils.toInputStream("ARGENTINIAN PESOS", Charset.defaultCharset())); //Here you are mocking the input stream you might get from the part file.
when(mock.raw().getPart("file")).thenReturn(file);
Now that you have the multipart/form-data mocked, you can continue your test mocking the service calls and such things.
Please ignore things that are from my specific code, like the "Page number" mocking, you don't need that.
Hope this helps for someone else.
Bye!
#RequestMapping(value = {"sms"},method = RequestMethod.POST)
public string rplyMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
Body body = new Body.Builder("Response message").build();
Message sms =
new Message.Builder().body(body).build();
MessagingResponse twiml = new MessagingResponse.Builder().message(sms).build();
response.setContentType("application/xml");
try {
response.getWriter().print(twiml.toXml());
} catch (TwiMLException e) {
e.printStackTrace();
}
}
This is how I handle the twilio response message.I want to get the content from the response message. and i want to store it in the database.How I can get the content from the response message.
Twilio developer evangelist here.
When Twilio makes a request to your application it sends the parameters encoded as application/x-www-form-urlencoded in the body of the POST request.
I've never written Java Spring MVC before, so excuse me if this isn't spot on, but I believe you can then read those parameters out of the body using the #RequestParam annotation.
#RequestMapping(value = {"sms"},method = RequestMethod.POST)
public string rplyMessage(
HttpServletRequest request,
HttpServletResponse response,
#RequestParam("Body") String message,
#RequestParam("From") String from
) throws IOException {
storeMessage(from, message);
// respond to the request
}
The message body and the number that sent it are the parameters "Body" and "From", you can see all the available request parameters here. So, for example with the message, you set the argument to #RequestParam to the name of the parameter, then you set the type and what you want the variable to be called within the method, thus: #RequestParam("Body") String message.
I don't know how you plan to use the database, but that's what I can tell you. You can read more about #RequestParam here and see some Twilio Java and Spring tutorials here.
Let me know if that helps at all.
I can't retrieve the values from a request.
Servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String location_id = request.getReader().readLine(); // <---- null
location_id = request.getParameter("location_id"); // <--- null
PrintWriter out = response.getWriter();
out.write(this.get_events_json(location_id));
}
On the client-side:
$.get("EventServe", {location_id : location_id}).done(function() {
var events = JSON.parse(responseText);
outer_this.events = events.map(function(event){
var event = new Event(event.address, event.name, event.event_start, event.event_end)
return event;
});
outer_this.events.map(function(event){outer_this.insert_event(event)});
});
I've also tried to pass it in directly without jQuery, using only literals.
When you use $.get('EventServe', {location_id: location_id}, ...) to make a HTTP GET request, you are passing the value of location_id as a query string parameter to the specified URL. Essentially you are requesting: EventServe?location_id=4, where 4 would be the value of location_id.
On the server side, you can access the query string parameters via getParameter(String name):
public void doGet(...) {
String locationId = request.getParameter("location_id");
}
A few extra notes:
You should remove your call to request.getReader().readLine(). (Also, doesn't readLine(byte[] b, int off, int len) require arguments?)
As a followup to the previous point, manually reading from the request via a BufferedReader, InputStream, or anything similar is a bad (used loosely) habit to get into, as doing so may interfere with getParameter(String name) in some cases:
If the parameter data was sent in the request body, such as occurs with an HTTP POST request, then reading the body directly via getInputStream() or getReader() can interfere with the execution of this method.
Source for the above quote.
Your client side code has a error where you define the function to run when the Ajax call is completed. The function should take events as an argument, as jQuery will automagically parse a JSON response:
.done(function (events) {
// Do things with the events
});
(Puts on pedant hat.) Your method name get_events_json does not follow Java conventions. Consider renaming it to getEventsJson or something to that effect.
Servlet Request Doc
Just look at getAttribute(String name) or getParameter(String name).
Edit: getParameter(String) is for POST request, but you perform a GET request. Use getAttribute(String) instead
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("/");