How to Handle Popup Window in Spring? - java

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?

Related

communicate between servlet and angular 4

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/

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

Ajax GET error with AngularJS and Spring MVC

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.

broadcast message to all online users jsp ajax

I am trying to broadcast a message entered by an admin to be visible to online users as a pop up. i am using ajax to make a call to database with a time interval like the code below. This code runs for each and every online users and returns message if the message_Flag is 1 in the database
setInterval( function()
{
getChatText();
}, 5000);}
function getChatText() {
$.ajax({
type : "POST",
url : "/easyoffice/commonAjax.do",
data : "method=" + "getMessages",
success : function(responseText) {
if (responseText.trim() != ''){
$("#dialog-message").html(responseText);
$("#dialog-message").dialog({
modal: true,
draggable: false,
resizable: false,
position: ['center'],
show: 'blind',
hide: 'blind',
width: 400,
dialogClass: 'ui-dialog-osx',
buttons: {
"I've read and understand this": function() {
$(this).dialog("close");
}
}
});
}
},
error : function(e) {
alert('Error: ' + e);
}
});
}
This is working correctly , but being a webapp with a lot of users , this causes a performance drop. I've heard websockets doesn't support Broadcasting. Is there any alternative .?? Thanks in advance

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.

Categories