jstree ajax call to servlet failing? - ajax

was trying to implement a simple demo of jstree using jstree json and servlet but my ajax call to servlet is not working must be a minor error but still not working please guide me
on this would very grateful.
1) The jsp page called the jsp tree initialization on page load
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Chetan Jtree</title>
<link rel="stylesheet"
href="${pageContext.request.contextPath}/themes/default/style.min.css" />
<script
src="${pageContext.request.contextPath}/jquery-1.9.1.js"></script>
<script src="${pageContext.request.contextPath}/jstree.min.js"></script>
<script src="${pageContext.request.contextPath}/jtreedemo.js"></script>
</head>
<body onload="initTrees()">
<div id="jstreeloaddiv"></div>
</body>
2) The js file where the inittree function is written jtreedemo
function initTrees() {
$("#jstreeloaddiv").jstree({
"plugins" : [ "themes", "json_data", "ui" ],
"json_data" : {
"ajax" : {
"type" : "POST",
"url" : "/JSTreeDemoServlet",
"data" : function(n) {
return {
"criteria" : "get_children"
};
},
"success" : function(new_data) {
alert(new_data);
return new_data;
},
"error" : function(xhr, textStatus, errorThrown) {
alert('request failed' + textStatus);
},
"fail" : function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}
}
});
}
3) The servlet from where the json data is being send and to which ajax call fails.
#WebServlet("/JSTreeDemoServlet")
public class JSTreeDemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public JSTreeDemoServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(request.getParameter("criteria"));
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
JSONArray jsonarr = new JSONArray();
JSONArray jsonarrattr = new JSONArray();
PrintWriter out= response.getWriter();
System.out.println(request.getParameter("criteria"));
for(int i =0;i<5;i++){
JSONObject jsonobj = new JSONObject();
try {
jsonarrattr = new JSONArray();
jsonobj.put("data", "Bmw"+i);
jsonarr.put(jsonobj);
jsonobj = new JSONObject();
jsonobj.put("id", i);
jsonobj.put("name", "chetan");
jsonarrattr.put(jsonobj);
jsonobj = new JSONObject();
jsonobj.put("attr", jsonarrattr);
jsonarr.put(jsonobj);
jsonobj = new JSONObject();
jsonobj.put("state", "closed");
jsonarr.put(jsonobj);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonarr);
}
}

i think you have to use:
$(document).ready(function(){
initTrees();
});

Related

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 .

How I get the HandlerMethod matchs a HttpServletRequest in a Filter

I'm writing a simple proxy app, and want mapped url will be handled by my controller, but other url (includes error) can be forwarded to another different address. So I use Filter rather than HandlerInterceptorAdapter that cannot be invoked if the resourece is not found because certain "resourece path handler" deals it.
Expectation
http://localhost:8090/upload.html > Filter > http://localhost:8092/upload.html
http://localhost:8090/files/upload > Controller > http://localhost:8092/files/upload
Not
http://localhost:8090/upload.html > Filter > http://localhost:8092/upload.html
http://localhost:8090/files/upload > Controller > http://localhost:8092/files/upload
Or
http://localhost:8090/upload.html > Interceptor > http://localhost:8090/error Not found
http://localhost:8090/files/upload > Filter > http://localhost:8092/files/upload
Demo
I set up a Filter in my subclass of WebMvcConfigurerAdapter.
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
private javax.servlet.Filter proxyFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
System.out.println("[doFilterInternal]isCommitted=" + response.isCommitted() + ", URI = " + request.getRequestURI());
// if(!isRequestMappedInController(request, "my.pakcage"))
httpProxyForward(request, response);
}
};
}
// #Bean
// private FilterRegistrationBean loggingFilterRegistration() {
// FilterRegistrationBean registration = new FilterRegistrationBean(proxyFilter());
// registration.addUrlPatterns("/**");
// return registration;
// }
Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptorAdapter() {
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// How I determine a controller has handled the request in my interceptor?
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = ((HandlerMethod) handler);
if (handlerMethod.getMethod().getDeclaringClass().getName().startsWith("nxtcasb.casbproxy")) {
System.out.println("[preHandle]dealt: request uri = " + request.getRequestURI() + ", HandlerMethod = " + ((HandlerMethod) handler).getMethod());
return true;
} else {
System.out.println("[preHandle]isCommitted=" + response.isCommitted() + ", HandlerMethod = " + ((HandlerMethod) handler).getMethod());
}
}
// act as an api-gateway
System.out.println("[preHandle]undealt: request uri = " + request.getRequestURI() + ", handler = " + handler);
//ModelAndView modelView = new ModelAndView("redirect: http://www.bing.com");
//throw new ModelAndViewDefiningException(modelView);
httpProxyForward(request, response);
return false;
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
if (handler instanceof HandlerMethod) {
System.out.println("[postHandle]dealt: uri = " + request.getRequestURI() + ", handler = " + ((HandlerMethod) handler).getMethod());
} else {
System.out.println("[postHandle]undealt uri = " + request.getRequestURI() + ", handler = " + handler);
}
}
}).addPathPatterns("/**", "/error");
}
/**
* this is the same as <mvc:default-servlet-handler/> <!-- This tag allows for mapping the DispatcherServlet to "/" -->
*
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations("classpath:/public");
}
protected void httpProxyForward(HttpServletRequest request, HttpServletResponse response) {
HttpClient httpClient = CreateHttpClient();
HttpUriRequest targetRequest = null;
HttpResponse targetResponse = null;
try {
targetRequest = createHttpUriRequest(request);
targetResponse = httpClient.execute(targetRequest);
} catch (IOException e) {
e.printStackTrace();
} finally {
// make sure the entire entity was consumed, so the connection is released
if (targetResponse != null) {
EntityUtils.consumeQuietly(targetResponse.getEntity()); // #since 4.2
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
}
}
The api url /files/upload:
#RestController
#RequestMapping(value = "/files")
public class FileUploadProxyController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadProxyController.class);
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public ResponseEntity upload(HttpServletResponse response, HttpServletRequest request) {
try {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
Iterator<String> it = multipartRequest.getFileNames();
MultipartFile multipart = multipartRequest.getFile(it.next());
String fileName = multipart.getOriginalFilename();
File dir = new File("files", "proxy-uploaded");
dir.mkdirs();
logger.debug("current dir = {}, uploaded dir = {}", System.getProperty("user.dir"), dir.getAbsolutePath());
File file = new File(dir, fileName);
Files.copy(multipart.getInputStream(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
//FileCopyUtils.copy(multipart.getInputStream())
// byte[] bytes = multipart.getBytes();
// BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream("upload" + fileName));
// stream.write(bytes);
// stream.close();
RestTemplate restTemplate = new RestTemplate();
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
//// if Spring version < 3.1, see https://jira.springsource.org/browse/SPR-7909
// requestFactory.setBufferRequestBody(false);
restTemplate.setRequestFactory(requestFactory);
String url = "http://localhost:8092/files/upload";
// [resttemplate multipart post](https://jira.spring.io/browse/SPR-13571)
// [Spring RestTemplate - how to enable full debugging/logging of requests/responses?](https://stackoverflow.com/questions/7952154/spring-resttemplate-how-to-enable-full-debugging-logging-of-requests-responses?rq=1)
MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
param.add("file", new FileSystemResource(file));
param.add("param1", fileName);
param.add("param2", "Leo");
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String,Object>>(param);
ResponseEntity responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
//String string = restTemplate.postForObject(url, param, String.class);
//ResponseEntity e = restTemplate.exchange(url, HttpMethod.POST,
// new HttpEntity<Resource>(new FileSystemResource(file)), String.class);
return responseEntity;
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity("Upload failed", HttpStatus.BAD_REQUEST);
}
}
#RequestMapping("/hello")
public String hello() {
return "hello word";
}
}
Afer reading Spring mvc autowire RequestMappingHandlerMapping or Get destination controller from a HttpServletRequest
The following code works:
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
// https://stackoverflow.com/questions/129207/getting-spring-application-context
#Autowired
private org.springframework.context.ApplicationContext appContext;
private static final String MY_CONTROLLER_PACKAGE_NAME = "nxtcasb.casbproxy";
#Bean
protected javax.servlet.Filter proxyFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
HandlerMethod handlerMethod = null;
try {
RequestMappingHandlerMapping req2HandlerMapping = (RequestMappingHandlerMapping) appContext.getBean("requestMappingHandlerMapping");
// Map<RequestMappingInfo, HandlerMethod> handlerMethods = req2HandlerMapping.getHandlerMethods();
HandlerExecutionChain handlerExeChain = req2HandlerMapping.getHandler(request);
if (Objects.nonNull(handlerExeChain)) {
handlerMethod = (HandlerMethod) handlerExeChain.getHandler();
if (handlerMethod.getBeanType().getName().startsWith(MY_CONTROLLER_PACKAGE_NAME)) {
filterChain.doFilter(request, response);
return;
}
}
} catch (Exception e) {
logger.warn("Lookup the handler method", e);
} finally {
logger.debug("URI = " + request.getRequestURI() + ", handlerMethod = " + handlerMethod);
}
httpProxyForward(request, response);
}
};
}
// #Bean
// private FilterRegistrationBean loggingFilterRegistration() {
// FilterRegistrationBean registration = new FilterRegistrationBean(proxyFilter());
// registration.addUrlPatterns("/**");
// return registration;
// }
/**
* this is the same as <mvc:default-servlet-handler/> <!-- This tag allows for mapping the DispatcherServlet to "/" -->
*
* #param configurer
*/
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//registry.addResourceHandler("/**").addResourceLocations("classpath:/public");
}
protected void httpProxyForward(HttpServletRequest request, HttpServletResponse response) {
HttpClient httpClient = CreateHttpClient();
HttpUriRequest targetRequest = null;
HttpResponse targetResponse = null;
try {
targetRequest = createHttpUriRequest(request);
targetResponse = httpClient.execute(targetRequest);
} catch (IOException e) {
e.printStackTrace();
} finally {
// make sure the entire entity was consumed, so the connection is released
if (targetResponse != null) {
EntityUtils.consumeQuietly(targetResponse.getEntity()); // #since 4.2
//Note: Don't need to close servlet outputStream:
// http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter
}
}
}
}

Liferay AJAX Request: No handler found for portlet request

Asked on this Liferay Forum post
I am trying to make an AJAX request from my Lifery portlet utilizing <portlet:resourceURL>.
index.jsp
<portlet:resourceURL var="search" id="recordId"></portlet:resourceURL>
CLICK ME
<script>
var id = 100;
function ajaxCall(ajaxUrl){
$.ajax({
url : ajaxUrl,
data : {
id: id
},
type: 'GET',
dataType : "json",
success : function(data) {
// do stuff on success
},
error: function () {
//do stuff on error
console.log('Error Occurred');
}
});
}
</script>
And my #Controller
#Controller
#PropertySource("classpath:application.properties")
#RequestMapping(value = "VIEW")
public class SearchController {
#ActionMapping
public void handleActionRequest(ActionRequest request, ActionResponse response)throws Exception {
System.out.print("In the Action Mapping Handler");
return;
}
#RenderMapping
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response, ModelMap model) {
return new ModelAndView("index", model);
}
#ResourceMapping(value = "search")
#ResponseBody
public void getPlan(ResourceRequest request, ResourceResponse response) throws PortalException, SystemException, IOException {
System.out.println("In the search Controller");
}
}
However I am getting the error and am not sure why
org.springframework.web.portlet.NoHandlerFoundException: No handler found for portlet request: mode 'view', phase 'RESOURCE_PHASE', parameters map[[empty]]
The Request URL:
http://localhost:8090/portal/web/mySite/home?p_p_id=MyApp_WAR_MyApp&p_p_lifecycle=2&p_p_state=normal&p_p_mode=view&p_p_resource_id=recordId&p_p_cacheability=cacheLevelPage&p_p_col_id=column-1&p_p_col_count=1&id=100
Any ideas?
#ResourceMapping(value="recordId") would work as mentioned by Pankaj.

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?

How to handle servlet response in JSP through AJAX call?

I want to display servlet response in my JSP page (as a hyperlink) through an ajax call. Can anyone please tell me how I could display the content in my jsp page? I am also not too sure if I am doing it the right way. There could be some errors in either my servlet class or Ajax.js. I'm still in learning phase. Here is my code snippet:
JSP page
<script type="text/javascript"> var AJAX_SERVLET="<%=renderResponse.encodeURL(renderRequest.getContextPath())%>/ajaxServlet";
</script>
<label for="push">Push to start</label>
<button dojoType="dijit.form.Button" style="width: 4em" type="button" name="submitButton" value="Submit" onclick="ajaxFunction()"></button>
Ajax.js
function ajaxFunction() {
if (xmlhttp) {
xmlhttp.open("GET", AJAX_SERVLET, true); //AJAX_SERVLET has the servlet path
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
//alert(xmlhttp.status);
if (xmlhttp.status == 200) {
var resultContent =httpRequest.getResponseHeader("Content-Type");
} else {
alert("Error during AJAX call. Please try again");
}
}
Getters/Setters
public class SearchResponse {
private String productNumber;
private String productType;
private String funcDesignation;}
Servlet Class
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
List result = new ArrayList();
result.add(new SearchResponse("001", "User Manual", "Operator"));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(result));
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doPost(request, response);
}

Resources