Ajax GET error with AngularJS and Spring MVC - java

I have an angular function that uses $http request with GET and params :
$scope.getMatchingRecipe = function(){
$http({
method: "GET",
url: "/recipemanagement/getMatchingRecipeList",
params: {
matchingText : $scope.matchingRecipe.text
}
}).success(function (data) {
console.log(data);
$scope.recipeList = data;
console.log($scope.recipeList[0]);
})
.error(function (data) {
console.log(data);
});
};
And the MVC controller as :
#RequestMapping(value="/getMatchingRecipeList")
public #ResponseBody String getRecipeDropdownList(#RequestParam(value="matchingText") String matchingText){
List<Recipe> recipeList = recipeServiceImpl.getMatchingRecipes(matchingText);
for(Recipe recipe : recipeList){
System.out.println("recipe :"+recipe.getName());
}
List<RecipePO> recipePOList = new ArrayList<RecipePO>();
System.out.println("List Size :"+recipeList.size());
for(Recipe recipe : recipeList){
RecipePO recipePO= new RecipePO();
recipePO.setId(recipe.getId());
recipePO.setName(recipe.getName());
recipePO.setDifficulty(recipe.getDifficulty());
recipePO.setServes(recipe.getServes());
recipePOList.add(recipePO);
}
try {
return new ObjectMapper().writeValueAsString(recipePOList);
} catch (JsonProcessingException e) {
e.printStackTrace();
return "Error";
}
}
However, when the function getMatchingRecipeList is called, it returns 404. But when I check the backend console (i.e. the controller function getRecipeDropdownList makes a database call through hibernate, so it shows query executed in console), the function is executed.

It seems that the problem isnt in the ajax call. The server was throwing an error from backend and hence returned error.jsp page.
The problem :
Service class was made #Transactional.In DAO layer, I used session.close() (yeah, duh);
The analysis :
I wrapped up all the functions in try-catch block and got to know of this error. It threw hibernate session already closed error in stacktrace. That's where it was returning error.jsp page
The solution :
I removed session.close() from DAO class. That solved the issue.

Related

rest controller works but ajax post method return an error

I'm making a post method using $.ajax which is this
$(function(){
$("#postMembers").click(function(){
let member ={
firstName: "khookina",
lastName : "khooak",
age:1,
sex:"female",
duty:"undefined",
dailyJeton:2
}
$.ajax({
type: "post",
url: "http://localhost:8080/RCP2/members",
data: member,
dataType: "application/json",
success: function (response) {
alert("success");
},
error: function(error){
alert("error");
}
});
});
and my rest controller is this
#PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String createMembers(Member member) {
if (member.hasError()) {
throw new CreatePersonException("All the fields must be filled properly in order to create a new member.");
}
if (personDao.createMember(member)) {
return "Member: " + member.getFirstName() + " " + member.getLastName() + " successfully created.";
}
return "couldn't create member, please try again later.";
}
I have a create member button in the webpage that executes this ajax post method, when I press it, everything works fine, the member information gets sent to the rest controller, It gets created (100% working) and returns {"readyState":4 status":200, "statusText":"parsererror"} and error: function(error) of ajax post method gets called
What's the problem?
it's the first day I'm working with ajax and javascript, I don't really understand what's happening.
Thanks in advance
P.S I've tried changing data-type text json, json and some others that been suggested in similar questions, but they didn't work for me, so i decided to make a question myself.
Try changing
data: JSON.stringify(member) and you will have your response in your success in the result/
Remove data type from ajax request and it works.
Remove this.
dataType: "application/json"
For details refer this

How do I create an Alfresco site programmatically from a repository webscript?

I've implemented an Alfresco repository webscript (in Java) to programmatically create a new site.
I notice that there's a SiteService interface which I thought could be used to do this -
SiteInfo site = siteService.createSite("site-dashboard", "mySite",
"mySite", "", SiteVisibility.PUBLIC);
However, this results in the creation of a non-functional site, and although it's visible within the Alfresco Share dashboard, I'm not able to use it.
I then came across this code sample, which is doing exactly what I want. BUT the code includes a section to do authentication, involving sending the user's login and password details to a dologin web service. Don't really want to do this.
But as the user has already logged in via Alfresco Share, they should already be authenticated.
If I call the create-site webscript from my code, as shown in the example (without the initial call to dologin), I'm getting a 401 (unauthorised) return code.
So my question is, how do I tell the create-site webscript about my authentication?
I read about using an authentication ticket here. Is this ticket stored in the session, and if so, how do I access it within my Java code? If I could get the ticket, then this would be sufficient to invoke the create-site webscript.
Update: I've added the alf_ticket parameter as suggested by the comment, but I'm still getting a 401 response.
My current code is:
public NodeRef createServiceChange(String serviceChangeName) {
HttpClient client = new HttpClient();
String ticket = authService.getCurrentTicket();
PostMethod createSitePost = new PostMethod("http://localhost:8081/share/service/modules/create-site");
JSONObject siteObject = new JSONObject();
try {
siteObject.put("shortName", serviceChangeName);
siteObject.put("visiblity", "Public");
siteObject.put("sitePreset", "site-dashboard");
siteObject.put("title", serviceChangeName);
siteObject.put("description", serviceChangeName);
siteObject.put("alf_ticket", ticket);
createSitePost.setRequestHeader("Content-Type", "application/json");
createSitePost.setRequestHeader("Accept", "application/json");
createSitePost.setRequestEntity(new StringRequestEntity(siteObject.toString(), "application/json", "UTF-8"));
int status = client.executeMethod(createSitePost);
System.out.println("create a site script status :: " + status);
if (status == HttpStatus.SC_OK) {
System.out.println("Site created OK");
}
else{
System.out.println("There is error in site creation");
}
} catch (JSONException err) {
err.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
So I've managed to successfully create a site, programmatically, and here's what I did:
First, forget about writing a repository (platform) webscript. Creation of sites in Alfresco is done by invoking a Share module, so you'll need to implement either a page, or custom menu item to create a site. I was also getting a lot of problems with authentication, but if you log in to the system via Alfresco Share, and in your Javascript, use the provided Alfresco Ajax request, then authentication shouldn't be a problem.
Here are the components I used:-
Create a Share page to create your site. In the Freemarker template (.ftl) add a form to collect the site details.
Attach a button on the form to the following Javascript function. Note that I cobbled this together from various code fragments on the web, so it could use some cleaning up. But it basically works for me -
function create_site()
{
var sc_form = document.forms.namedItem('sc_form');
var name = sc_form.elements.namedItem('name').value;
var url = Alfresco.constants.URL_CONTEXT + "service/modules/create-site";
Alfresco.util.Ajax.request({
method : Alfresco.util.Ajax.POST,
url : url,
dataObj: {
sitePreset: "site-dashboard",
visibility: "PUBLIC",
title: name,
shortName: name,
description: name
},
requestContentType: Alfresco.util.Ajax.JSON,
successCallback:
{
fn: function(res){
alert("success");
alert(res.responseText);
},
scope: this
},
failureCallback:
{
fn: function(response)
{
Alfresco.util.PopupManager.displayPrompt(
{
title: Alfresco.util.message("message.failure", this.name),
text: "search failed"
});
},
scope: this
}
});
}

Spring: Test JSP Output in JUnit Test

We have a API, which returns the JSP as the view, for example:
#RequestMapping(value = "/cricket/{matchId}", method = RequestMethod.GET)
public String getCricketWebView(HttpServletRequest request, #PathVariable("matchId") Integer matchId, ModelMap mv){
try{
return "webforms/cricket";
}catch(Exception e){
e.printStackTrace();
}
return "";
}
I wrote a unit test to test this out as follows:
#Test
public void test_cricket()
{
try {
MvcResult result =this.mockMvc.perform(get(BASE + "/cricket/123")
.accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andReturn();
String json = result.getResponse().getContentAsString();
System.out.println(json);
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is that, the unit tests only returns the string webforms/cricket and not the actual HTML from the cricket.jsp page. I understand this is happening because I am using the Mock MVC.
But, is there a way I can test the actual HTML? The reason is that we use some complex JSTL tags and we have seen in the past that unit test succeeds but the actual JSP page returns 500 error because of parsing failure.
I tried the following code:
try {
WebConversation conversation = new WebConversation();
GetMethodWebRequest request = new GetMethodWebRequest(
"http://localhost:8080/cricket/123");
WebResponse response = conversation.getResponse(request);
System.out.println(response.getResponseMessage());
}
catch (Exception e)
{
e.printStackTrace();
org.junit.Assert.fail("500 error");
}
But this gives, connection refused exception. Again I understand this is because web server is not setup at the time of test.
This is my configuration:
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = "file:src/main/webapp/WEB-INF/spring-resources/applicationcontext.xml")
public class MobileApiControllerTest {
...
}
I also tried using #WebIntegrationTest, but the same problem. It seems this only works for Spring boot application. Our application is a typical WAR application deployed on Tomcat.
Any idea how can I achieve the actual JSP output in unit test?
Reading and googling I think that this can't happen using the Spring Test framework. Spring test does not run the code(java code, jstl, i18n messages) inside the jsp! This is also a useful answer from so.
If you wish to test the jsp source, you have to use a client side test framework like Selenium or HttpUnit.

Calling a java method in ajax

I am creating a jsp application in Netbeans Ide. I am having problems in calling a java class method in ajax.Is it possible to do so
My java class is something like this:
public class Hello
{
public String execute(String s)
{
return "success";
}
}
I am not able to figure out how to call the execute method using ajax :
My current ajax code is:
var val="test string";
$.ajax({
type: "GET",
url: "http://localhost:8084/Shade/src/java/mail/Main.execute",
data: val,
async: true,
cache: false,
success: function (msg) {
alert("hi");
$(".col-1").html(msg);
});
Thanx in advance :)
AJAX is an acronym for Asynchronous JavaScript And XML. It provides an ability to communicate with the server asynchronously.
To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
So, you can not access Java Class directly as url to make your Ajax request. It should any mapped url like JSP, Servlets, PHP etc.
Create a JSP (e.g. hello.jsp)
<%
String strResponse;
mail.Main objMain = new mail.Main();
strResponse = objMain.execute();
%>
<%=strResponse %>
In Ajax request
url: "hello.jsp",
EDIT: Added Example:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function getData() {
var dataToBeSent = {
uName : $("#userName").val() , //
passwd: $("#password").val()
}; // you can change parameter name
$.ajax({
url : 'getDataServlet', // Your Servlet mapping or JSP(not suggested)
data :dataToBeSent,
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
In Servlet/JSP access your parameters request.getParameter("uName");
You cannot call the method directly. You should map an URL to the method you want to call.
This can be done in a servlet. If you're already serving pages through your Java code, you just add a new method to serve a page with the content you want.

How to get Parameter from Ext.Ajax.request in java controller

I am having one problem in retrieving the parameter which i am passing using Ext.Ajax.request to my JAVA controller class.
I am sending request to my controller using below code
Ext.Ajax.request({
url : 'projecttask/GetprojectTasks.action',
method: 'POST',
jsonData: {
sampledata: record.data
},
type: 'json',
scope: this, // add the scope as the controller
callback : function(options, success, response) {
console.log('RESPONSE FROM SERVER :'+response);
}
});
my java controller method to receive the request is
#RequestMapping(value="/projecttask/GetprojectTasks.action")
public #ResponseBody Map<String, ? extends Object> getprojectTasks(HttpServletRequest request,
HttpServletResponse response,#RequestBody Project project) throws Exception {
try {
System.out.println("PROJECT ::"+project);
System.out.println("RPOJECT DATA ::"+request.getParameter("sampledata"));
Object data = request.getParameter("sampledata");
Project prj = (Project) data;
System.out.println("CREATE TASK DATA IS ::"+prj.getProjectid());
return null;
}catch(Exception e) {
return getModelMapError("Error trying to create contact");
}
}
but it gives me error mentioned below
org.codehaus.jackson.map.JsonMappingException: Unrecognized field "sampledata" (Class com.kintu.projectmgt.model.Project), not marked as ignorable
so what i am doing wrong which not allowed my function to get sampledata passed as parameters. How can i get my Parameters passed value any idea ?
My firebug shows that sampledata contains all values. Please help me to find the problem and solve it as soon as possible.
I am using Ext JS 4.0.2a and JAVA as my serverside technology.
you can use
String postParamsJSON = request.getReader().readLine();
to get the POST data.

Categories