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.
Related
i'm working on create a java web app using servlet in controller side and the angular in front-end.. this app uses javamail api to get emails from an email account (like gmail) then return them as a json format .. i did all of that .. i can bring the emails messages and i return them in json format using servlet but my problem here is that i can't display them using angular.. i tried to test my code with this website "http://jsonplaceholder.typicode.com/users" to test my angular with json and it bring all data but when i modify it and try it with my app it doesn't bring any thing..
here is an example of json data from my app..
and that's the servlet code who print this data:
// TODO Auto-generated method stub
doGet(request, response);
EmailAccount emailaccount= new EmailAccount("myemail#gmail.com","HardPas$$word!#");
EmailServices read = new EmailServices();
ArrayList<Email> emails = new ArrayList<Email>();
emails = read.readEmail(emailaccount);
String json = new Gson().toJson(emails.get(2));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
and this this the codes in angular to get the json data and display it:
html
<form action="http://127.0.0.1:8080/oneBox/ReadEmail" method="POST" (submit)="onSubmit()">
<input type="submit" value="submit">
</form>
<ul >
<li>
{{users.id}}
</li>
<li>
{{users.title}} ---- {{users.from}}
</li>
<li>
{{users.to}}
</li>
</ul>
component:
import { Component, OnInit } from '#angular/core';
import { MyServiceService } from '../../services/my-service.service';
import {EmailModel} from '../../models/user.model'
#Component({
selector: 'app-my-compo',
templateUrl: './my-compo.component.html',
styleUrls: ['./my-compo.component.css']
})
export class MyCompoComponent implements OnInit {
users:EmailModel;
constructor(public service:MyServiceService) {
}
onSubmit(){
this.service.getUsers().subscribe(
users => {this.users=users;});
}
ngOnInit(): void {
}
}
and my service code:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import {map, catchError} from "rxjs/operators";
import { Observable, throwError } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MyServiceService {
url="http://127.0.0.1:8080/oneBox/ReadEmail";
getUsers():Observable<any>{
return this.http.get(this.url)
.pipe(map(res => res.json()));
}
constructor(public http: Http) { }
}
so my question here is how can i bring these json data from my local server and print it using angular ?
Your backend seems to be working fine, as you get a proper JSON response from the Java side of things.
Try the following in your service class:
getUsers(): Observable<any>{
return this.http.get<any>(this.url);
}
Add the error callback inside your component controller and log the result of both fields, provide us with the result afterwards in the comments:
onSubmit(){
this.service.getUsers().subscribe(
users => {
console.log(users);
this.users=users;
},
error => {
console.log(error);
});
}
Further more, I think that there is a misconception between POST and GET requests, as I saw this in your form. Remove the method and action attribute in your form, since in Angular this will have no effects. You submit your forms with the (submit) event, so that is enough.
Last but not least, have you considered CORS policy in your backend? This is an issue with frontend/backend separation, since the backend will only allow request coming from the same IP and Port, thus not your Angular frontend. Probably this could help you: https://howtodoinjava.com/servlets/java-cors-filter-example/
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
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.
In my Spring Application have Display some Existing Users in Database In Jsp
<a id="details" href="#"class="copyright-text read_link" title="FAQs" onclick="sendForm()";>
<label for="subject">${user.name}</label>
</a>
When we Click above Hyper link one Popup will open and show his Details
And my Controller class i'm mapping action to hyperlink click event.
#RequestMapping(value = "search", method = RequestMethod.POST)
public String header(SearchForm form, BindingResult result,
Model model) throws Exception {
-----
-----
model.addAttribute("SEARCH_RESULT", form);
return "search";
}
So this search.jsp should display on above popup window.
In this Purpose i'm doing like this..
Prepare ajax form submitting , i'm writing success event so popup.
function ajaxFormSubmit(options) {
$.ajax({
url : options.action,
success : function(data, textStatus, jqXHR) {
$('#' + options.successElem).html(data);
}
},
error : function(jqXHR, textStatus, errorThrown) {
apprise(textStatus +" " + errorThrown);
}
});
}
But this is not working. so is this procedure correct or not ?
Other wise tell me how to Open popup window in Spring ?
According to your code, HTTP method is specified as POST in the #RequestMapping, while GET method is used for sending the ajax request. Is this the cause of your problem?
I'm quite new to JSP/Liferay portlet development and I'm trying to add a progress bar using jQuery, I found this question but wasn't very specific to how it will be done using AJAX.
I was wondering if anyone can point me in the right direction to help me get started.
thanks.
EDIT:
I used JSON simple, and manage to make some changes but I am getting a bad request(error code 400 when using fire bug) and a 404 not found on my JS
below is my code:
public void processAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
//some code here
this.generateJSON(actionRequest, actionResponse);//manual call the method?
public void generateJSON(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
try{
//just want to see a progress bar so do static for now...
JSONObject obj=new JSONObject();
obj.put("percent",new Integer(30));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
}catch(Exception ex){
System.out.print(ex);
}
}
}//end of class
JS here
function checkStatus(){
$.ajax({
type: 'POST',
//url: '<%=request.getContextPath()%>/checkStatusServlet',
url: '<%=request.getContextPath()%>/generateJSON',
dataType: 'json',
success: function( data )
{
alert(data.statusPercent);
var statusPercent = data.percent;
//Update your jQuery progress bar
$( "#progressbar" ).progressbar({value: statusPercent});
}
});
//below works and alert is being called...
/*for (i=0;i<=5;i++)
{
$( "#progressbar" ).progressbar({value: i+10});
}
alert('got here');
*/
}
HTML/JSP
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects/>
<portlet:renderURL var="resourceUrl"></portlet:renderURL>
<!-- Javascript files -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/main.js"></script>
<!-- end of Java script files -->
<script type="text/javascript">
setTimeout('checkStatus()',1000);
</script>
<div id="progressbar"></div>
You can't generate JSON in processAction. This method is meant to change the portlet state, but not generate output. The portal-way to accomplish what you need it to use the serveResource method/lifecycle-phase: you get the URL for this from the portal ( < portlet:resourceURL / >). Specifically you shouldn't create them yourself.
An alternative (but not the portal way) is to use a servlet - but in this you don't have the portlet state that you might need.
And you might want to use < portlet:namespace / > to disambiguate your global names - or use proper namespacing - because you can never say how many times your portlet will be placed on a page.
(added spaces to jsp-tags so that they don't get eaten by markup)
Short: Read about resource-serving for portlets, this will most likely solve your underlying problem: With the code you give above you won't be able to access your JSON at all - no matter what you do on the JS side.
The answer really depends on your specific needs. Are you trying to display how much time is actually left for some task, or how much time till a page loads or what?
You could poll from the client and update the progress bar in the browser depending on how much is left to process. A simple jQuery ajax example:
function checkStatus
{
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/checkStatusServlet',
dataType: 'json',
success: function( data )
{
var statusPercent = data.statusPercent;
//Update your jQuery progress bar
$( "#progressbar" ).progressbar({value: statusPercent });
}
});
}
Then you can simply poll this function till its done
setTimeout('checkStatus()' 1000);
Of course you will also need to construct a servlet or struts action or portlet to handle the processing on the server, and return the appropriate status for the task.
EDIT:
Use the JSON library
From your servlet or action. (code below is from struts2 action)
public String checkStatus()
{
try
{
Integer percentDone = 50; //Calculate how much time is left
JSONObject statusResult = new JSONObject();
statusResult.put("statusPercent", percentDone);
//Obtain HttpServletResponse..
//implementation depends on your framework.
//PortletResponse should work too.
PrintWriter out = this.response.getWriter();
out.write( statusResult.toString(4) );
out.flush();
out.close();
}
catch (IOException e) {}
catch (JSONException e) {}
return null;
}