I am working on ajax for getting data from my server as back-end i am using java-servlets
Now what issues i am facing is:
i have to call two data for two different work via ajax
So what i am doing currently is creating two servlet class and making two ajax call to both of them
i am writing all my codes in doGet method of one servlet
and via ajax call in url i am giving servlet class name
What i am trying to do
can't i create one servlet and inside it i can make several methods and make ajax call on that servlet class method
what i am doing
Servlet1 code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String categoryCode, categoryName, quantity,sql,str = null;
Gson gson = new Gson();
LinkedHashMap<Object, Object> lhm = null;
LinkedList<LinkedHashMap<Object, Object>> mainList = new LinkedList<LinkedHashMap<Object, Object>>();
try {
sql = "1";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
lhm = new LinkedHashMap<Object, Object>();
categoryCode = "A101";
categoryName = "drinks";
lhm.put("Category Code", categoryCode);
lhm.put("Category Name", categoryName);
mainList.add(lhm);
str = gson.toJson(mainList);
}
response.setContentType("application/json");
response.getWriter().write(str);
}}
Servlet2 code
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String itemName, itemCode, quantity,sql,str = null;
Gson gson = new Gson();
LinkedHashMap<Object, Object> lhm = null;
LinkedList<LinkedHashMap<Object, Object>> mainList = new LinkedList<LinkedHashMap<Object, Object>>();
try {
sql = "2";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
lhm = new LinkedHashMap<Object, Object>();
itemName = "pepsi";
itemCode = "AA00";
lhm.put("Item Code", itemCode);
lhm.put("Item Name", itemName);
mainList.add(lhm);
str = gson.toJson(mainList);
}
response.setContentType("application/json");
response.getWriter().write(str);
}
and my ajax call code
$.ajax({
async: true,
url : "Servlet1",
method : "GET",
dataType : "json",
contentType: "application/json; charset=utf-8",
success : function(tableValue) {
addTable(tableValue)
}
});
Now i have to get data from my data base and run 2 queries and have to do two different thing with there result,but doing it with creating new-new servlets now dosn't looks good
Can't i create one doGet and inside that two methods or any two methods inside servlet so that both the servlet codes can be written in oneservlet
Note :- i don't have knowledge on spring framework , so i want to do it with help of servlets only
anyone please guide me how can i do that
Thanks in advance
There isn't a good solution for HttpServlet classes, as you can only have one doGet method. A decent workaround would be adding a parameter in your url, for example Servlet1?action=action1 and then implementing logic in your doGet()
method to decide what to do based on that parameter. For example:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
switch(action){
case "action1":
doAction1(request, response); //Method with the logic of your Servlet1 class
break;
case "action2":
doAction2(request, response);
break;
default:
throw new ServletException("Invalid action parameter");
}
}
Edit - this would be your final ajax call:
$.ajax({
async: true,
url : "Servlet1?action=action1", // Here you set the parameter
method : "GET",
dataType : "json",
contentType: "application/json; charset=utf-8",
success : function(tableValue) {
addTable(tableValue)
}
});
Related
I am new to servlets and JSPs.
Recently.. I have been trying to send data from my Servlet to JSP using requestDispatcher.
This is my Servlet code responsible:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sampleClass sampleObject = new sampleClass(1, "myname");
ObjectMapper mapper = new ObjectMapper();
String jsonstring = mapper.writeValueAsString(sampleObject);
request.setAttribute("values", jsonstring);
request.setAttribute("valuees", "testing");
request.getRequestDispatcher("/somejsp").forward(request, response);
}
My JSP part responsible for retrieving data:
${values}
${valuees}
<%
//out.println(Message);
Enumeration enume = request.getParameterNames();
for (Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
String name = entry.getKey();
String value = entry.getValue()[0];
// ...
}
String value = request.getParameter("values");
out.println(value);
String valuee = request.getParameter("valuees");
out.println(valuee);
%>
But the output I get is:
{"n":1,"name":"myname"} testing null null
as you can see both the EL gives correct output, the implementation with the Enumeration returns nothing and the other two return null.
I donot understand this. I couldn't find any solution online.
You're confusing attributes (any object that you choose to store in the request, under a name you choose), with parameters (strings sent by the browser as part of the request, as in foo=bar&baz=2.
I created InformationServlet that whenever I need some details I can send it what I want (with AJAX) and it will return me the information.
I searched how to do it on Ajax and according to:
How to send parameter to a servlet using Ajax Call
I used: url: "InformationServlet?param=numberOfPlayers"
But on the servlet the request's attributes doesn't contain the parameter I sent so I suppose I am not doing it correctly:
you can see that the attributes size is zero
Servlet:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Gson gson = new Gson();
Engine engine = (Engine)getServletContext().getAttribute("engine");
String responseJson = "";
if(request.getAttribute("numberOfPlayers") != null)
{
String numberOfPlayers = "";
numberOfPlayers = gson.toJson(String.valueOf(engine.GetNumOfPlayers()));
responseJson = numberOfPlayers;
}
out.print(responseJson);
} finally {
out.close();
}
}
JavaScript (AJAX request):
function getNumberOfPlayersAndPrintSoldiers()
{
$.ajax({
url: "InformationServlet?param=numberOfPlayers",
timeout: 2000,
error: function() {
console.log("Failed to send ajax");
},
success: function(numberOfPlayers) {
var r = numberOfPlayers;
}
});
}
Edit:
you probably want to use getParameter and not getAttribute
Moreover, please pay attention to the order of parameter name and his value:
request.getParameter("param");
instad of:
request.getParameter("numberOfPlayers");
because the url form contains parameter name first and then the parameter value. for example:
myurl.html?param=17
and if more parameters needed then use the separator & sign
myurl.html?firstName=bob&age=5
i have a servlet my goal is to return a customer object from the process request, where i can then access this object in my jquery. Does anyone know how i can go about doing this?
e.g. myObject.getMethod()
Servlet Code:
Customer loginResult;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
//request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
out.println(loginResult);
} finally {
out.close();
}
}
JSP CODE:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "get",
data: dataf,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
Can someone please assist me in resolving this issue, thank you for your help in advance.
Since you want to handle an ajax request using a Servlet, the best bet you have is writing the data of your custom object into the response. The easier way I found to accomplish this is using JSON. There are lot of libraries that handles JSON conversion from objects to Strings and vice versa, I recommend using Jackson. This is how your code should look like.
Servlet code:
import com.fasterxml.jackson.databind.ObjectMapper;
#WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {
//Jackson class that handles JSON marshalling
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
//login operation should be handled in POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer loginResult = ...; //process data and get the loginResult instance
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//marshalling the data of your loginResult in JSON format
String json = OBJECT_MAPPER.writeValueAsString(loginResult);
response.getWriter().write(json);
}
}
Javascript code:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "post", //login action MUST be post, NEVER a get
data: dataf,
success: function(data) {
//shows the relevant data of your login result object in json format
alert(data);
//parsing your data into a JavaScript variable
var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
//now you can use the attributes of your loginResult easily in JavaScript
//for example, assuming you have a name attribute in your Customer class
alert(loginResult.name);
}
});
return false;
});
});
</script>
More info:
How to use Servlets and Ajax?
Parse JSON in JavaScript?
I am trying to implement REST type architecture without using any framework. So I am basically calling a JSP from my client end which is doing a doPost() on to the remote server providing services. Now I am able to pass the data from client to server in JSON format but I don know how to read the response. Can someone help me out with this.
Client Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
....
....
HttpPost httpPost = new HttpPost("http://localhost:8080/test/Login");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//Send post it as a "json_message" paramter.
postParameters.add(new BasicNameValuePair("json_message", jsonStringUserLogin));
httpPost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse fidresponse = client.execute(httpPost);
....
....
}
Server Side:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String jsonStringUserLogin = (String)request.getParameter("json_message");
....
....
request.setAttribute("LoginResponse", "hello");
// Here I need to send some string back to the servlet which called. I am assuming
// that multiple clients will be calling this service and do not want to use
// RequestDispatcher as I need to specify the path of the servlet.
// I am looking for more like return method which I can access through
// "HttpResponse" object in the client.
}
I just started with servlets and wanted to implement a REST service by myself. If you have any other suggestion please do share... Thank You,
in doPost you simply have to do :
response.setContentType("application/json; charset=UTF-8;");
out.println("{\"key\": \"value\"}"); // json type format {"key":"value"}
and this will return json data to client or servlet..
reading returned data using jquery ajax ...
on client side using jquery do the following :
$.getJSON("your servlet address", function(data) {
var items = [];
var keys= [];
$.each(data, function(key, val) {
keys.push(key);
items.push(val);
});
alert(keys[0]+" : "+items[0]);
});
on servlet you know how to read json data
After you executed the post you can ready the response like this.
HttpEntity entity = fidresponse.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String l = null;
String rest = "";
while ((l=br.readLine())!=null) {
rest=rest+l;
}
Here rest will contain your json response string.
You can also use StringBuffer.
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);
}
// ...
}