How to handle servlet response in JSP through AJAX call? - ajax

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

Related

Session timeout with Filter in Spring Boot

I'm trying to implement Session timeout logic in Spring Boot project with Filter.
The filter intercepts every request and checks whether the session is new
If the session is timed out, it should redirect to login page.
Since there is an iFrame, the redirection is happening inside iframe. how to redirect main page to login page?
Here is the code below:
<body>
<a
class="nav-link dropdown-toggle menu-submenu"
role="button"
data-toggle="collapse"
aria-haspopup="true"
aria-expanded="false"
target="basefrm"
th:attr="href='#'+${submenu.shortCode}, title=${submenu.title}">
<iframe
class="embed-responsive-item justify-content justify-content-center "
height="100%"
width="100%"
id="basefrm"
name="basefrm"
scrolling="overflow-x:no ;overflow-y:no"
frameborder="0"
allowTransparency="false"
style="height: 100%;"></iframe>
</body>
#WebFilter("/*")
#Order(1)
public class TransactionFilter extends HttpFilter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
if(session !=null && !session.isNew() && session.getAttribute("login") != null) {
if(req.getRequestURI().equalsIgnoreCase(req.getContextPath()+"/")) {
res.sendRedirect(req.getContextPath()+"/loginpage.html");
}
else {
chain.doFilter(request, response);
}
}
else {
logger.debug("session timed out!");
session = req.getSession(true);
session.setAttribute("login", true);
logger.debug("path:{}"+req.getContextPath());
res.sendRedirect(req.getContextPath()+"/loginpage.html");
}
}
}

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 .

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.

jstree ajax call to servlet failing?

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

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