Communicate with backend method through Ajax - java

I am trying to communicate with a method using Ajax and AngularJS but I'm not getting a response and the alert outputs undefined.
Index.cshtml
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="myApp">
// Displaying the table is working
<div>
<table class="table" ng-controller="UpdateController">
<tr>
<th>Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tr ng-repeat="c in cities">
<td>{{c.Id}}</td>
<td>{{c.City1}}</td>
<td>{{c.Country}}</td>
</tr>
</table>
</div>
// Here I add the controller for adding records -->
<div ng-controller="AddRecord">
<form id="form1" ng-submit="send()">
<table>
<tr>
<td>City: </td>
<td>
<input type="text" id="txtCity" ng-model="addCity" />
</td>
</tr>
<tr>
<td>Country: </td>
<td>
<input type="text" id="txtCountry" ng-model="addCountry" />
</td>
</tr>
<tr>
<td>
<input type="submit" id="btnSubmit" value="Submit" />
</td>
</tr>
</table>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('UpdateController', function ($scope, $http) {
$http.get("http://localhost:50366/api/cities")
.success(function (response) { $scope.cities = response });
});
app.controller('AddRecord', function ($scope, $http) {
// Function responsible for communicating with backend
$scope.send = function () {
$.ajax({
type: "POST",
url: "AddCity.asmx.cs/PostCity",
data: "{'city':'" + $scope.addCity + "','country':'" + $scope.addCountry + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
//Here is one I tried using text as the datatype:
$.ajax({
type: "POST",
url: "AddCity.asmx/PostCity",
data: "city=" + $scope.addCity + "&country=" + $scope.addCountry,
dataType: "text",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
};
});
</script>
</body>
</html>
AddCity.asmx with the method I'm trying to access
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using AngularWebApi.Models;
using AngularWebApi.Controllers;
namespace AngularWebApi.Views
{
/// <summary>
/// Summary description for AddCity
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class AddCity : System.Web.Services.WebService
{
[WebMethod]
public string PostCity(string city, string country)
{
City newCity = new City();
newCity.City1 = city;
newCity.Country = country;
//Eventually I want to add the city to the database
CitiesController controller = new CitiesController();
controller.PostCity(newCity);
return "Posted!";
}
}
}
Index.cshtml resides in Views/Home and AddCity.asmx resides in Views. I tried to use url: "../AddCity.asmx/PostCity" as well.
Edit
I quickly created a new project and set it up, the exact same thing is happening, here are the steps:
New web api project
New ADO.net Entity data model and link it to my DB
New Web API 2 controller with actions using Entity Framework passing the table from DB and entity I got from pevious step.
Then I edit Index.cshtml to show the XML from API/CITIES as a table. This time I added my service in the root of the project and just trying to call the auto created HelloWorld with the $.ajax POST function.
I do see a warning in the FF error console. Literal translation from dutch: Cross-Origin-Request blocked: ....
Furthermore the error is triggered within the ajax call. The WebService is not being reached afaik.
This is the complete reply I get when I click the button:
<!DOCTYPE html>
<html>
<head>
<title>The resource cannot be found.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>The resource cannot be found.</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
<br><br>
<b> Requested URL: </b>/Home/MyWebService.asmx/HelloWorld<br><br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
</font>
</body>
</html>
<!--
[HttpException]: A public action method 'MyWebService.asmx' was not found on controller 'AngularTutorial.Controllers.HomeController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->
Edit
The POST method in the controller:
// POST: api/Cities
[ResponseType(typeof(City))]
public IHttpActionResult PostCity(City city)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Cities.Add(city);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = city.Id }, city);
}

hmmm, I think I got it: you try to create a new POST-Method, but according to the tutorial, there is already a POST-Method in the City-Controller:
By clicking on Add, we are able to create the Cities Web API using the scaffolding. The created controller class will have a Web API for all the CRUD operations on the city table.
that means you simply need to send your ajax-call to http://localhost:50366/api/cities:
$.ajax({
type: "POST",
url: "http://localhost:50366/api/cities",
data: "{'country':'" + country + "','name':'" + cityName + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (msg) {
alert(msg.d);
}
});
Make sure you only have 1 web application running, so you can avoid unnecessary problems.
btw. I'm not sure, if the controller will accept json maybe you need to send the data as xml...
EDIT:
I updated the json data. Your city-object has 3 properties: country, id and name. If you send a POST request you are about to create a new object, so you don't need to send the id.
For PUT and DELETE (if you want to implement this functions) you will need to add the idto the url:
http://localhost:50366/api/cities/:id
EDIT2:
ok, the xml should looks like this:
data: "<City><Country>" + country + "</Country><Name>" + cityName + "</Name></City>",
don't forget to change:
contentType: "application/xml; charset=utf-8",
dataType: "xml",

Don't use ajax, even if it worked you would still have problems because $.ajax calls are not in Angular.js context and you would have to manually $scope.apply() the returned value. Use angular $http service instead. You can find how to use it in official documentation. It is very flexible, supports all request methods, query params, request body, etc... also supports interceptors to handle all your requests. All $http calls return promise by default (also use .then() handler instead of success and failure handlers).

Related

Upload cropped "croppie" image to server using Java PlayFramework 2.6

I've googled for the past 2 days and still can't find a solution to this problem. I can upload fine using the input element with type attribute set to file. But I cannot upload the cropped image using croppie to the server.
Here is my register.scala.html:
#helper.form(action = routes.ProfilesController.upload, 'id -> "profileForm", 'class -> "", 'enctype -> "multipart/form-data") {
#CSRF.formField
<div class="col-6 col-md-3 pic-padding">
<div id="upload-demo" class="upload-demo pic-1 mx-auto d-block rounded">
</div>
<div class="pic-number" href="#">1</div>
<label for="upload-pic1" class="pic-control-bg">
<img src="#routes.Assets.versioned("images/plus.png")" class="pic-control">
</label>
<input type="file" id="upload-pic1" name="pic1" class="upload-btn" accept="image/*">
<button type="button" class="upload-result">Result</button>
<script>
Demo.init();
</script>
</div>
}
Here is my main.js:
$('.upload-result').on('click', function (ev) {
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function (resp) {
$.ajax({
url: "http://localhost:9000/upload",
type: "POST",
data: {"image":resp},
success: function (data) {
alert(resp);
}
});
});
});
Here is my ProfilesController.java
public Result upload() {
File file = request().body().asRaw().asFile();
return ok("File uploaded");
}
Here is a snippet from routes file:
POST /upload controllers.ProfilesController.upload()
The error i get with the above solution is:
[CompletionException: java.lang.NullPointerException]
Please help! This has been stressing me out for the past 2 days, I just can't figure it out.
This is not fully solved, but i've progressed enough to produce a different problem. I ended up changing my ajax request in main.js to:
$.ajax({
url: "http://localhost:9000/upload",
type: "POST",
data: resp,
success: function (data) {
alert(resp);
Then I also changed the profilecontroller.java to
public Result upload() {
String dataUrl = request().body().asText();
System.out.println(dataUrl);
return ok("Data URI Passed");
}
This gave me the Data URI from javascript and passed it to the JAVA code. Now I need to try and upload the image using the Data URI. If you know the answer to this then please contribute to this post.

Sending Cyrillic string from jsp to java class trough ajax with correct encoding

I am having a few input fields in my jsp page that get a Cyrillic input which I am then upon pressing a button trying to send to this java method using ajax. The strings in the java method end up being gibberish.
The fields in the jsp page:
<div class="span1">
<form:label cssClass="control-label" path="">
<spring:message code="web.messages.someMessage" />
</form:label>
<form:input cssClass="input-block-level" path="" id="articleId" />
</div>
<div class="span1">
<label> </label>
<button type="button" id="search-btn" class="btn" >
<spring:message code="web.messages.buttonMessage" />
</button>
</div>
The ajax in the script:
$("#search-btn").on("click", function(e) {
e.preventDefault();
showDialog("${pageContext.request.contextPath}");
});
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
if (article) {
article = "?article=" + article;
}
$.ajax({
type : "GET",
url : "${pageContext.request.contextPath}/sync/getFilter"
+ article,
success : function(data) {
onClickTable();
}
});
}
This is part of the java method, where the value turns into gibberish:
#RequestMapping(value = "/getFilter", method = RequestMethod.GET)
public #ResponseBody ModelAndView getFilter(HttpServletRequest request) {
String article = (String) request.getParameter("article");
.
.
Fixed the problem by putting the information in a JSON and sending it like that.
The changed made:
The ajax in the script part of the jsp:
function showDialog(baseContext) {
var article = $('#articleId').val().replace(/\s+/g, "");
var data = {
"article": $('#articleId').val().replace(/\s+/g, ""),
// other keys and values
"lastKey": $('#lastValueId').val().replace(/\s+/g, "")
}
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/sync/getFilter",
data: data,
success : function(data) {
onClickTable();
}
});
}
The java method handling the data:
#RequestMapping(value = "/getFilter", method = RequestMethod.POST)
public #ResponseBody ModelAndView getFilter(SomeObject receivedData) {
String article = receivedData.getArticle();
// rest of the method
Where SomeObject is an object containing the values that we receive in the data with proper set and get methods for them.

post comments using jsp, servlet and ajax

I am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.
Highly appreciate any kind of help.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBtn').click(function() {
var cmt = $('#cmt').val();
$.ajax({
type : 'POST',
data : {
cmt : cmt,
action : 'EnterMsg'
},
url : 'SubmitComment',
success : function(result) {
$('#view2').text(result);
}
});
});
});
</script>
</head>
<body>
<fieldset>
<legend>Enter Message</legend>
<form>
Ques.<input type="text" id="cmt"> <input type="button"
value="Send" id="submitBtn"><br> <span id="post1"></span>
</form>
</fieldset>
<fieldset>
<legend>View Message</legend>
<form>
<div id='view2'></div>
<br>
</form>
</fieldset>
Try
var html='';
$.ajax({
dataType: "json",
url: "SubmitComment",
error: function () {
alert('error occured');
},
success: function (result) {
for(var key in result) {
var value = result[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#view2").append(html);
}
});
Instead of
success : function(result) {
$('#view2').text(result);
}
Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag

Send response from REST to JSP after #POST

I have a JSP page (client-side)
<form action="http://localhost:8080/REST-WS/rest/token" method="POST">
<label for="email">Email</label>
<input name="email" />
<br/>
<label for="password">Password</label>
<input name="password" />
<br/>
<input type="submit" value="Submit" />
</form>
It points to a function in REST Web Service (server-side)
#POST
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Code verify(#FormParam("email") String email,
#FormParam("password") String password,
#Context HttpServletResponse servletResponse) throws IOException {
Code code = generateRandomCode(email,password);
return token;
}
The problem is I want to give response to the client side containing the random-generated code from the server side.
First, it will be redirected to another JSP page and then the client side can receive the random-generated code from server.
How do I do it?
The problem is that you can't send arbitrary Java objects in a redirect. You can however add the data into query parameters. For example
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response post(#FormParam("name") String name,
#FormParam("email") String email) {
String message = "Hello " + name + ". Your email is " + email;
URI uri = UriBuilder.fromPath("/index.jsp")
.queryParam("message", message)
.build();
return Response.seeOther(uri).build();
}
Here, you are building a URI from the location of the jsp page, and adding a query parameter to the end of the URI. So the redirect will go to
http://localhost:8080/index.jsp?message=<the message>
From the index.jsp page you can get the parameter with request.getParameter("message"). For example
<h1><%= request.getParameter("message") %></h1>
Another option to work with JSP and Jersey is to implement MVC, which Jersey provides support for. You can check out this answer, though the examples use Maven (to get all the required jars). If you are interested and don't know how to use Maven, let me know and I'll see if I can help you get all the jars you need.
UPDATE
Ajax Example.
Easiest Javascript library to get started with (if you have no experience) is jQuery. I won't really give much explanation about the code, that's kinda out of scope. I would go through some tutorials (W3Schools has some good getting started guides), and there are answers all over SO that can answer your questions.
Here's a complete working html page. Just change var url = "/api/submit"; to whatever endpoint you are sending the request to.
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(document).ready(function(){
var url = "/api/submit";
$("#submitBtn").click(function(e) {
e.preventDefault();
var formData = $("#nameForm").serialize();
$.ajax({
url: url,
data: formData,
dataType: "json",
type: "POST",
success: function(data) {
var message = data.message;
var date = data.date;
var h1 = $("<h1>").text(message);
var h3 = $("<h3>").text(date);
$("#content").empty()
.append(h1).append(h3);
},
error: function(jqxhr, status, errorMsg) {
alert(status + ": " + errorMsg);
}
});
});
});
</script>
</head>
<body>
<div id="content">
<form id="nameForm">
First Name: <input type="text" name="fname"/><br/>
Last Name : <input type="text" name="lname"/><br/>
<button id="submitBtn">Submit</button>
</form>
</div>
</body>
</html>
Here is the test resource class
#Path("submit")
public class FormResource {
public static class Model {
public String message;
public String date;
}
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Model post(#FormParam("fname") String fname,
#FormParam("lname") String lname) {
String message = "Hello " + fname + " " + lname;
Model model = new Model();
model.message = message;
model.date = new Date().toString();
return model;
}
}
You will need to make sure you have a JSON provider to handle the JSON Pojo serialization or it won't work (the Model won't be able to serizalize to JSON).

Ajax call not hitting controller

hi I am trying to Use Ajax with Spring Mvc Porltet In liferay.I Have a Jsp File and Controller Class.I want to insert a data in the form but my controller class is Not Called.So please Help Me to Solve this Problem.When I Click on submit My COntroller class is not called.
my .jsp code as follws:
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects/>
<portlet:renderURL var="renderOneMethodURL">
<portlet:param name="action" value="renderOne"></portlet:param>
</portlet:renderURL>
<portlet:actionURL var="actionOneMethodURL">
<portlet:param name="action" value="actionOne"></portlet:param>
</portlet:actionURL>
Call RenderOne method
<%-- <form action="${actionOneMethodURL}" method="post">
User Name: <input type="text" name="userName">
<input type="submit">
</form> --%>
<div id="request">
<div id="bigForm">
<h2> REQUEST</h2>
<h3> Enter Request Details :</h3>
<p>Name: <input name="name">
Code: <input name="code" size="6">
Request: <input name="request">
Type: <input name="type" size="6"></p>
<hr></hr>
<div class="block2">
<h2> Attribute Value Pair(Avp)</h2>
<p class="remark"> Recursive structure of avp. You can nest one AVP inside another..</p>
<div data-holder-for="branch"></div>
</div>
<div class="clear"></div>
<p> </p>
<p class="remark" align="right" padding-right:"1cm";>Click here to generate JSON representation of the form</p>
<p align="right">
<input type="submit" id="saveBigForm"></p>
</div>
<style type="text/css">a {text-decoration: none}</style>
<!-- Subforms library -->
<div style="display:none">
<div data-name="branch">
<table>
<td>Name:</td> <td><input name="name"></td>
<td>Code:</td> <td><input name="code"></td>
<td>Vendor:</td> <td><input name="vendor"></td>
<td>Multiplicity:</td><td><input name="multiplicity"></td>
<td>Index:</td><td><input name="index"></td>
<td>CDR-Index:</td><td><input name="cdrIndex"></td>
<tr>
<td >Type:</td><td><input name="type"></td>
<td>Value:</td><td><input name="value"></td>
</tr>
</table>
<div style="margin:10px; border-left:3px solid black" data-holder-for="branch"></div>
</div>
</div>
<div id="popup"></div>
</div>
and my javascript
$('#saveBigForm').click(function(){
var json = $('#bigForm').jqDynaForm('get');
showFormJson(json);
// var myInfoUrl = "<c:out value="${actionOneMethodURL}" />";
$.ajax({
type: "POST",
//url: "http://localhost:9090/first-spring-mvc-portlet//WEB-INF/servlet/view",
//url : myInfoUrl,
url : "${actionOneMethodURL}",
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});
});
and controller class as follows
package com.myowncompany.test.springmvc.controller;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.ParamUtil;
#Controller(value = "MyFirstSpringMVCTestController")
#RequestMapping("VIEW")
public class MyFirstSpringMVCTestController {
private static Log log = LogFactoryUtil.getLog(MyFirstSpringMVCTestController.class);
/*
* maps the incoming portlet request to this method
* Since no request parameters are specified, therefore the default
* render method will always be this method
*/
#RenderMapping
public String handleRenderRequest(RenderRequest request,RenderResponse response,Model model){
return "defaultRender";
}
#RenderMapping(params = "action=renderOne")
public String openSaveSearchPopup(RenderRequest request, RenderResponse response, Model model){
return "render1";
}
#RenderMapping(params = "action=renderTwo")
public String openDeeplinkForInfoI(RenderRequest request, RenderResponse response){
return "render2";
}
#RenderMapping(params = "action=renderAfterAction")
public String testRenderMethod(RenderRequest request, RenderResponse response){
log.info("In renderAfterAction method");
return "renderAfterAction";
}
#ActionMapping(params = "action=actionOne")
public void actionOne(ActionRequest request, ActionResponse response) throws IOException {
String userName=ParamUtil.get(request, "userName", "");
log.info("server input stream is :::"+ request.getPortletInputStream().toString());
System.out.println("we ri nnnnnnnnn");
log.info("userName is==>"+userName);
response.setRenderParameter("action", "renderAfterAction");
}
#ActionMapping(params = "action=actionTwo")
public String addMyChannelAction(ActionRequest actionRequest, ActionResponse actionResponse) {
return "action2";
}
}
iam getting the log as follows:
09:36:56,291 INFO [DispatcherPortlet:119] Portlet 'firstspringmvc' configured successfully
09:36:56,300 INFO [localhost-startStop-19][PortletHotDeployListener:454] 1 portlet for first-spring-mvc-portlet is available for use
10:09:49,460 WARN [http-bio-9090-exec-138][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
10:09:54,325 WARN [http-bio-9090-exec-139][404_jsp:121] {msg="/$%7BactionOneMethodURL%7D", uri=/$%7BactionOneMethodURL%7D}
Try with jsp core tag,
url : "<c:url value='/VIEW/actionOne' />"
OR
url : "<c:out value='${actionOneMethodURL}' />"
Include JSTL core in JSP i.e.:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
and Change your ajax URL
url : "${actionOneMethodURL}"
to
url : "<c:url value='/VIEW/actionOne' />",
From what you have told us so far I can identify those causes:
your javascript has a problem and is not running at all (open with google chrome or firefox and press F12. Go to the Console tab and tell us if you have any errors there.
since you have a different javascript file, as the warning said, ${actionOneMethodURL}is not defined there. So you can do it like this:
In your HTML (the .jsp file you postet at top):
<script type="text/javascript">
ajaxLink = "${actionOneMethodURL}";
</script>
In your javascript file:
url : window.ajaxLink;
Experiment with this, I have no way to test it may need some tweaks like where you add the script (near the beginning of the document, near the end), and if the " surrounding the ${actionOneMethodURL} are needed.
in .jsp page add
var actionurl =${actionOneMethodURL};
in example.js on ajax call
$.ajax({
type: "POST",
url : actionurl,
data: JSON.stringify(json),
dataType: "json",
success: function(response){
// we have the response
if(response.status == "SUCCESS"){
$('#info').html("Success........!Request has been added......... ");
}else{
$('#info').html("Sorry, there is some thing wrong with the data provided.");
}
},
error: function(e){
alert('Error: ' + e);
}
});

Categories

Resources