AJAX response conflict - ajax

I have a problem with my ajax redirection on response.
The redirection works perfectly, but when, later, I have to return a Boolean with response, it returns the redirection.
Here is the code. The concerned lines have comments :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Worker extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String firstName = "";
private static String lastName = "";
private static boolean doAnimWheel = false;
private static String portion;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// begin recovering form
Worker.firstName = request.getParameter("firstName");
Worker.lastName = request.getParameter("lastName");
response.sendRedirect("launch.html"); // TODO find why it blocks response
// end recovering form
String param = request.getParameter("srcId");
if(param != null) {
if(param.equals("launch")) {
Worker.doAnimWheel = new Boolean(request.getParameter("doAnimWheel")).booleanValue();
return;
}
else if(param.equals("wheel")) {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(Worker.doAnimWheel); // Here I have to return my Boolean, but it return launch.html
out.flush();
out.close();
return;
}
else if(param.equals("result")) {
Worker.portion = request.getParameter("portion");
Worker.doAnimWheel = new Boolean(request.getParameter("doAnimWheel")).booleanValue();
return;
}
}
}
}

I think the problem is that you always send the redirect at the beginning of your method
response.sendRedirect("launch.html"); // TODO find why it blocks response
// end recovering form
Java documentation for the sendRedirect method HttpServletResponse states: "After using this method, the response should be considered to be committed and should not be written to."
What you try to return later is evidently ignored.
You may want to move the sendRedirect calling to the branches of code that actually need to perform the redirect, like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// begin recovering form
Worker.firstName = request.getParameter("firstName");
Worker.lastName = request.getParameter("lastName");
String param = request.getParameter("srcId");
if(param.equals("launch")) {
Worker.doAnimWheel = new Boolean(request.getParameter("doAnimWheel")).booleanValue();
response.sendRedirect("launch.html");
return;
}
else if(param.equals("wheel")) {
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
out.print(Worker.doAnimWheel); // Here I have to return my Boolean, but it return launch.html
out.flush();
out.close();
return;
}
else if(param.equals("result")) {
Worker.portion = request.getParameter("portion");
Worker.doAnimWheel = new Boolean(request.getParameter("doAnimWheel")).booleanValue();
response.sendRedirect("launch.html");
return;
}
}
}
}

Related

Spring boot application filter response body

I am working on a spring boot application. I want to modify the response of the request by request body field "Id".
I have implemented below, but still getting just the name in the output while implementing.Any suggestions on implementing below would be helpful:
Below is the requestBody:
{
"id" : "123"
}
In response, I want to append that field to response id(fieldname from request body).
responseBody:
{
"name" : "foo123" //name + id from request
}
MyCustomFilter:
public class TestFilter implements Filter {
#Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
MultiReadHttpServletRequest wrapper = new MultiReadHttpServletRequest((HttpServletRequest) request);
MyRequestWrapper req = new MyRequestWrapper(wrapper);
String userId = req.getId();
chain.doFilter(wrapper, new HttpServletResponseWrapper(res) {
#Override
public ServletOutputStream getOutputStream() throws IOException {
return new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps)
);
}
#Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(new DelegatingServletOutputStream(new TeeOutputStream(super.getOutputStream(), ps))
);
}
});
String responseBody = baos.toString();
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(responseBody);
String name = node.get("name").astext();
((ObjectNode) node1).put("name", name + userId);
chain.doFilter(wrapper, res);
}
MyRequestWrapper:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ServletInputStream input;
public MyRequestWrapper(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getId() throws IOException {
if (input == null) {
try {
JSONObject jsonObject = new JSONObject(IOUtils.toString(super.getInputStream()));
String userId = jsonObject.getString("id");
userId = userId.replaceAll("\\D+","");
return userId;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
MultiReadHttpServletRequest.java
public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
private byte[] body;
public MultiReadHttpServletRequest(HttpServletRequest request) {
super(request);
try {
body = IOUtils.toByteArray(request.getInputStream());
} catch (IOException ex) {
body = new byte[0];
}
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
ByteArrayInputStream wrapperStream = new ByteArrayInputStream(body);
#Override
public boolean isFinished() {
return false;
}
#Override
public boolean isReady() {
return false;
}
#Override
public void setReadListener(ReadListener readListener) {
}
#Override
public int read() throws IOException {
return wrapperStream.read();
}
};
}
}
Any suggestions are appreciated. TIA.
Nte: After update i am not able to see the updated response as output. I am still seeing just the name but not id appended to it.
The one issue I see with your own implementation of ServletRequest is that you call super.getInputStream() instead of request.getInputStream(). Your own request is empty by default, that's why you're getting time out exception. You have to delegate a call to the actual request:
public class MyRequestWrapper extends HttpServletRequestWrapper {
private ServletInputStream input;
public MyRequestWrapper(ServletRequest request) {
super((HttpServletRequest)request);
}
public String getId() throws IOException {
if (input == null) {
try {
JSONObject jsonObject = new JSONObject(IOUtils.toString(/*DELETEGATE TO ACTUAL REQUEST*/request.getInputStream()));
String userId = jsonObject.getString("id");
userId = userId.replaceAll("\\D+","");
return userId;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}

Spring Interceptor

I need to create an interceptor that will intercept HTTP requests and responses, but it seems to me that I'm doing something wrong, can someone tell me what I should change or add?
public class HttpInterceptor extends HandlerInterceptorAdapter implements ClientHttpRequestInterceptor
{
#Override
public ClientHttpResponse intercept(final HttpRequest httpRequest, final byte[] bytes, final ClientHttpRequestExecution clientHttpRequestExecution) throws IOException
{
RestTemplate restTemplate = new RestTemplate();
final ClientHttpResponse response = clientHttpRequestExecution.execute(httpRequest, bytes);
final String httpResponseName = response.toString();
final HttpHeaders httpHeaders = response.getHeaders();
final HttpStatus httpStatusCode = response.getStatusCode();
final String statusText = response.getStatusText();
final String body = httpHeaders.toString() + httpStatusCode.toString() + statusText;
//And then i will put body to DB
return response;
}
xml
<bean id="httpInterceptor" class="HttpInterceptor"/>
<bean id="httpInterceptor" class="de.hybris.platform.servicelayer.interceptor.impl.InterceptorMapping">
<property name="interceptor" ref="httpInterceptor"/>
<property name="typeCode" value="Message"/>
</bean>
I understood that you try to create service (it can be rest, soap or any other). If I am right, you need to create controller for handling http request.
#Controller("MyController")
public class MyController extends AbstractController {
#RequestMapping(value = "/mymethod/{id}", method = RequestMethod.GET)
public void myMethod(#PathVariable final String id, final HttpServletRequest request, final HttpServletResponse out) throws Exception {
try {
if (StringUtils.isEmpty(id))
throw new UnknownIdentifierException("id is null!");
out.setContentType(MediaType.APPLICATION_TXT_VALUE);
IOUtils.copy(myStream, out.getOutputStream());
} catch (UnknownIdentifierException ex) {
out.setStatus(HttpServletResponse.SC_BAD_REQUEST);
out.setContentType(MediaType.TEXT_PLAIN_VALUE);
String message = "My error text!";
IOUtils.copy(new ByteArrayInputStream(message.getBytes()), out.getOutputStream());
}
}
I recommande to implements Filter to transform or use the information contained in the requests or responses. and not Interceptor , it provide more information then Interceptor Here's an exemple of the use of Filter for logging :
#Component
public class HttpLoggingFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(HttpLoggingFilter.class);
#Value("${output.trace.actif}")
private boolean isOutputActif;
private static String getRequestData(final HttpServletRequest request) throws UnsupportedEncodingException {
String payload = null;
ContentCachingRequestWrapper wrapper = WebUtils.getNativeRequest(request, ContentCachingRequestWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
}
}
return payload;
}
private static String getResponseData(final HttpServletResponse response) throws IOException {
String payload = null;
ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
if (wrapper != null) {
byte[] buf = wrapper.getContentAsByteArray();
if (buf.length > 0) {
payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
wrapper.copyBodyToResponse();
}
}
return payload;
}
#Override
public void init(FilterConfig filterConfig) {
logger.info("start http filter");
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
ContentCachingRequestWrapper requestToCache = new ContentCachingRequestWrapper(httpServletRequest);
ContentCachingResponseWrapper responseToCache = new ContentCachingResponseWrapper(httpServletResponse);
HttpUtil.majMDCRestInfo(httpServletRequest);
long start = System.currentTimeMillis();
chain.doFilter(requestToCache, responseToCache);
long elapsedTime = System.currentTimeMillis() - start;
String requestBody = new String(requestToCache.getContentAsByteArray());
String responseBody = new String(responseToCache.getContentAsByteArray());
final StringBuilder logMessage = new StringBuilder().append("[METHOD:").append(httpServletRequest.getMethod())
.append("] [PARAMS:")
.append(httpServletRequest.getQueryString()).append("] [BODY:").append(requestBody).append("]");
if (isOutputActif) {
String respContent = responseBody;
if (respContent.equals("")) {
respContent = "no data";
}
logMessage.append(" [RESPONSE:").append(respContent).append("]");
}
logMessage.append(" [STATUS:").append(responseToCache.getStatus()).append("] [Time:").append(elapsedTime).append("ms]");
String[] nonLoggingPaths = {"/api/"};
String urlPath = httpServletRequest.getRequestURL().toString();
if ((Arrays.stream(nonLoggingPaths).parallel().anyMatch(urlPath::contains))) {
logger.info("{}", logMessage);
}
getRequestData(requestToCache);
getResponseData(responseToCache);
}
}

How to read httpServletResponse in the interceptor?

I have a spring boot application. And now I need to read request and response in interceptor.I use a HttpServletRequestWrapper replace the request in DispatcherServlet
#Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
super.doDispatch(requestWrapper, response);
} catch (Exception e) {
super.doDispatch(request,response);
}
}
}
And in my interceptor , I can read the request body. But when I want to read the response body, it doesn't works.when I replace the response in the CustomerDispatcherServlet I got nothing response.I have tried ContentCachingResponseWrapper , but I got the payload with "".
It's a old question.and I have search some questions but didn't find a suitable solution.
I know I can solve the problem with AOP.But I want to know how can I do it in the interceptor?
here is my interceptor code
public class CustomerInterceptor extends HandlerInterceptorAdapter{
#Override
public void postHandle(...){
MultiReadHttpServletRequest req = (MultiReadHttpServletRequest) request;
ContentCachingResponseWrapper res = new ContentCachingResponseWrapper(response);
Byte[] body = res. getContentAsByteArray();
...
}
}
the body I got is [].
After few days .I find the answer.In the CustomerDispatcherServlet I should add responseWrapper.copyBodyToResponse()
the CustomerDIspatcherServlet like this:
#Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
if (!(response instanceof ContentCachingResponseWrapper)) {
ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper(response);
super.doDispatch(requestWrapper, responseWrapper);
responseWrapper.copyBodyToResponse();
}else {
super.doDispatch(requestWrapper, response);
}
} catch (Exception e) {
super.doDispatch(request, response);
}
}
}
Try this:
#Component("dispatcherServlet")
public class FofDisPatcherServlet extends DispatcherServlet {
#Override
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
MultiReadHttpServletRequest requestWrapper = null;
try {
requestWrapper = new MultiReadHttpServletRequest(request);
super.doDispatch(requestWrapper, new ContentCachingResponseWrapper(request));
} catch (Exception e) {
super.doDispatch(request,response);
}
}
}
.
public class CustomerInterceptor extends HandlerInterceptorAdapter{
#Override
public void postHandle(..., HttpServletResponse response){
if (response instanceof ContentCachingResponseWrapper) {
Byte[] body = ((ContentCachingResponseWrapper)response). getContentAsByteArray();
}
...
}
}
The error is in your code
public class CustomerInterceptor extends HandlerInterceptorAdapter{
#Override
public void postHandle((HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView){
MultiReadHttpServletRequest req = (MultiReadHttpServletRequest) request;
ContentCachingResponseWrapper res = new ContentCachingResponseWrapper(response);
Byte[] body = res. getContentAsByteArray();
...
}
}
You are passing request in ContentCachingResponseWrapper.
See this question very similar problem .

Servlet Filter modify header value with servlet request wrapper not working

I am attempting to change the Content-Type header in a request and change it to "application/json" before it reaches my spring rest controller. I have created a servlet request wrapper to change the values, but when the request reaches the controller it is still "text/plain". The logging shows that the header value has been changed before hitting doFilter();
Here is my class extending HttpServletRequestWrapper
class HttpServletRequestWritableWrapper extends HttpServletRequestWrapper {
private final Logger logger = org.slf4j.LoggerFactory.getLogger(HttpServletRequestWritableWrapper.class);
private final ByteArrayInputStream decryptedBody;
HttpServletRequestWritableWrapper(HttpServletRequest request, byte[] decryptedData) {
super(request);
decryptedBody = new ByteArrayInputStream(decryptedData);
}
#Override
public String getHeader(String name) {
String headerValue = super.getHeader(name);
if("Accept".equalsIgnoreCase(name))
{
logger.debug("Accept header changing :");
return headerValue.replaceAll(
MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE
);
}
else if ("Content-Type".equalsIgnoreCase(name))
{
logger.debug("Content type change: ");
return headerValue.replaceAll(MediaType.TEXT_PLAIN_VALUE, MediaType.APPLICATION_JSON_VALUE);
}
return headerValue;
}
#Override
public Enumeration<String> getHeaderNames() {
return super.getHeaderNames();
}
#Override
public String getContentType() {
String contentTypeValue = super.getContentType();
if (MediaType.TEXT_PLAIN_VALUE.equalsIgnoreCase(contentTypeValue)) {
logger.debug("Changing on getContentType():");
return MediaType.APPLICATION_JSON_VALUE;
}
return contentTypeValue;
}
#Override
public BufferedReader getReader() throws UnsupportedEncodingException {
return new BufferedReader(new InputStreamReader(decryptedBody, UTF_8));
}
#Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
#Override
public int read() {
return decryptedBody.read();
}
};
}
And here is my filter:
#WebFilter(displayName = "EncryptionFilter", urlPatterns = "/*")
public class EncryptionFilter implements Filter {
private final Logger logger = org.slf4j.LoggerFactory.getLogger(EncryptionFilter.class);
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
byte[] data = "{\"currentClientVersion\":{\"majorElement\":\"1\",\"minorElement\":\"2\"}}".getBytes();
logger.debug("data string " + data.toString());
logger.debug("Content-type before: " + servletRequest.getContentType());
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletRequestWritableWrapper requestWrapper = new HttpServletRequestWritableWrapper(request, data);
//logger.debug("Accept Header: " + requestWrapper.getHeader("Accept"));
//logger.debug("Content-Type: " + requestWrapper.getHeader("Content-Type"));
//logger.debug("Contenttype" + requestWrapper.getContentType());
filterChain.doFilter(requestWrapper, servletResponse);
}
#Override
public void destroy() {
}
}
It appears that the getHeaders method was being called somewhere else after my filter and not returning the headers with my updated values.
I added this override in my HttpServletRequestWrapper and it is now working:
#Override
public Enumeration<String> getHeaders(String name) {
List<String> headerVals = Collections.list(super.getHeaders(name));
int index = 0;
for (String value : headerVals) {
if ("Content-Type".equalsIgnoreCase(name)) {
logger.debug("Content type change: ");
headerVals.set(index, MediaType.APPLICATION_JSON_VALUE);
}
index++;
}
return Collections.enumeration(headerVals);
}

Ajax status 0 when calling the servlet

Hi I'm trying to just get a simple string returned from the servlet using Ajax, but nothing was ever returned 'cause the status is always 0 while readystate is 4.
Here's the .js code
function validate(choice) {
//var url = "http://localhost:8080/examples/validate.do?id=" + escape(choice);
var url = "../../validate.do"
if(window.XMLHttpRequest) {
req = new XMLHttpRequest();
}else if(window.ActiveXObject) {
req = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}
alert("IM IN VALIDATE() with " + choice);
req.open("GET", url, true);
req.onreadystatechange = callback;
req.send(null);
return false;
}
function callback() {
if(req.readyState == 4 ) {
if(req.status == 200){
var check = req.responseText;
alert(check);
}
else
alert(req.status);
}
}
and Java code
package model;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DoAjaxServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
response.setContentType("text/html");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
String resultStr = "JUST RETURNING THIS STRING";
out.write(resultStr);
} finally {
out.close();
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}
}
I'm running this on Tomcat 7 using Chrome, and accessed the html file from localhost:8080 not instead of running local, so a lot of solutions floating around won't work.
Going to
http://localhost:8080/examples/validate.do
in Chrome it prints the string just fine, so I think I didn't write the url wrong. The .js file are at somewhere like
http://localhost:8080/examples/jsp/HTE/my.js
I also tried using "http://localhost:8080/examples/validate.do" directly as url in .js and adding the setHeader("Access-Control-Allow-Origin", "*") to Java file but nothing changes.
After searching around in the posts I'm running of ideas on this one... Would you kindly tell me where this might go wrong?

Resources