Goal: To load different jsp's into a div of main.jsp dynamically on the basis of user click.
This is what I have done so far -
Java Script
function getPageContent( pageName, containerID, path ){
$.ajax({
type : "GET",
url : "getPageContent/"+pageName+".test",
cache : false,
data: "path=" + path,
success : function(response) {
alert(response);
$("#"+containerID).load( response );
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
}
Controller
#RequestMapping(value="getPageContent/{pageName}")
public String dynamicIncludePage( ModelMap model, #PathVariable String pageName,
#RequestParam(value="path") String path, HttpSession session ){
if( pageName.equals("manageDashBoard") ){
List<Report> reports = reportService.getAllReportsByUserID( (int)session.getAttribute("userID") );
model.addAttribute("reports", reports);
}
return path+"/"+pageName;
}
main.jsp
I am calling the JS method
getPageContent( 'manageDashBoard', 'containerID', 'home' );
path for manageDashBoard.jsp is --> EVIP14ReportSS\src\main\webapp\WEB-INF\views\home\manageDashBoard.jsp
But the spring is trying to locate the jsp in the below path --> EVIP14ReportSS\getPageContent\WEB-INF\views\home\manageDashBoard.jsp
Please suggest what is wrong.
Thanks
I am not sure if your paths are correct. You should check that anyway.
But for sure you should change way how you are rendering page using AJAX and Spring.
You should change return type from String to
public #ResponseBody JsonObjectToRender dynamicIncludePage( ModelMap model, #PathVariable String pageName,
#RequestParam(value="path") String path, HttpSession session )
JsonObjectToRender is your custom object with some properties. In success handler JsonObjectToRender you should analyze and render part of the page depending on that object.
Related
I'm making an ajax request and I have two situations, where if everything is ok I return a page which will be rendered in a modal else return empty string and don't show any modal at all.
Here is a sample of how should my controller look like:
#PostMapping(value = "/path")
public String serve(final Model model)
{
if (everything_fine)
{
return "path_to_page_which_will_be_handled_by_view_controller";
}
return StringUtils.EMPTY;
}
and the ajax request is something like this:
$.ajax({
type: 'POST',
url: '/path',
error: function (data) {
//handle error
},
success: function (data) {
if (data) {
// render response in modal
} else {
// show some other stuff
}
}
});
For the situation where jsp is returned request works fine, when empty string is returned I get 404 and ajax request goes on the error branch when finished. I guess this is because view controller doesn't find any view for the empty string returned, do you have any idea how can I accomplish my scenario?
You trying to return empty path to browser and you get 404. It's normal.
Try to return String with path to controller that returns empty page:
#PostMapping(value = "/path")
public String serve(final Model model)
{
if (everything_fine)
{
return "path_to_page_which_will_be_handled_by_view_controller";
}
return "path_to_EMPTY_page_which_will_be_handled_by_view_controller";
}
Eventually split this in two requests, one to get the data on which deciding if the modal will be shown or not, and finally request the modal contents if needed.
I have backend springboot that does the redirect
#RequestMapping(value = "/test/page", method = RequestMethod.POST)
public #ResponseBody void getPage(#RequestBody custRequest req, HttpServletRequest request, HttpServletResponse response) {
response.sendRedirect("https:www.google.com");
}
And the service call like this
getPage(user: User) {
const bodyString = JSON.stringify(user);
const header = new HttpHeaders({ 'Content-Type': 'application/JSON' ,
'Accept' : 'text/html' });
return this.httpclient.post('/test/page', bodyString, {headers: header, responseType: 'text'} );
}
Button when clicked.
onSubmit(user: User) {
if (user && user.userID && user.password) {
this.user.session = this.uuid;
this.loginService.getLogin(user).subscribe(
(res) => {
console.log('post res');
console.log(res);
// window.location.href = data.url; sanitizer
this.data = this.sanitizer.sanitize(SecurityContext.HTML, res);
},
error => {
console.log('Error', error);
},
() => {
console.log('POST is completed');
});
But in the result page I am not getting a proper landing page. Instead I am staying in the same page and the console would print
<!doctype html>
<html lang="en">
<head>
...
</html>
My question is how do I show the actual content?
Simply put, your code fetches the source code of google.com. I'm not sure whether this is the behaviour you want, or you want just a browser redirect. Please explain in more detail what you're trying to achieve. Despite not understanding, I'll do my best to answer.
To do a browser redirect, just do window.location.href = "http://www.w3schools.com";
If you want to fetch a page and show the content of an external page, I think iframe would be the most straight-forward approach.
The one below is NOT RECOMMENDED if the response is a full html page as it's invalid HTML (i.e. can't have html, head, body inside body). It'll also probably download unnecessary files.
Otherwise, create a property in the angular component, let's name it 'myHTML'. Then bind that to the innerHTML property of a html element you create
<div [innerHTML]="myHTML"></div>
Then once you fetch your URI (I recommend doing it directly -- GET to the final url, the way you did it is odd) just assign the response to the 'myHTML' property
I am pretty new in Spring MVC and I have the following problem trying to handle an AJAX request that send an array of int to a controller method.
So I have the following situation. I have this JQuery function:
// It is global and it is initiazilized by another function:
var checkedRowList = new Array();
// SOME OTHER CODE THAT INIZIALIZED THE checkedRowList array here
...............................................
...............................................
...............................................
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: {'checkedRowList' : checkedRowList},
url: "validaProgetti"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
So the checkedRowList is correctly initizialized (I checked it) and I use the ajax() function to send it toward the validaProgetti resource using a POST request.
Then into a controller class I have this method that have to handle the previous request:
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public String validaProgetti(#RequestParam List<Integer> checkedRowList, Model model, HttpServletRequest request) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
As you can see it handle HTTP Post request toward the validaProgetti resource. And Inside it I have specify the RequestParam List checkedRowList to retry the array passed by the AJAX request.
But it don't work because when the AJAX request is performed it don't enter into the validaProgetti() method and it shown the alert("SUCCESS"); popup.
Why? What am I missing? How can I fix this situation?
as I see you missed two things.
The first one is that in the Spring Web MVC controller. You don't pass a RequestParam but RequestBody.
#RequestMapping(value = "validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
The second one is related with your Ajax request. You should send javascript array formatted as JSON. This is done via the function JSON.stringify(), which converts js value into json.
$('#validaButton').click(function() {
alert("validazione");
alert("CHECKED ROWS: " + checkedRowList.length);
alert(checkedRowList[0]);
$.ajax({
type: "POST",
data: JSON.stringify(checkedRowList),
url: "validaProgetti",
contentType:"application/json"
}).done(function(response) {
alert("SUCCESS");
}).error(function(xhr) {
alert("ERROR");
manageError(xhr);
});
});
Also you may change the request mapping when defining in java code. Since it is a relative path, it would be confusing in some cases.
#RequestMapping(value = "/validaProgetti", method=RequestMethod.POST)
public #ResponseBody String validaProgetti(#RequestBody List<Integer> checkedRowList) {
System.out.println("Numero progetti da validare: " + checkedRowList);
return "blablabla";
}
I have a controller wich handles URL studentEdit.html. When I pass to controller value 'get' using AJAX I need to redirect to another page viewStudents.html, but nothing happens. I stay on the same page. The method returns the ModelAndView, but why it does not redirect to another page I do not know.
I also tried to set url as:
redirect:viewStudents.html and redirect:viewStudents
but it did not helped.
#RequestMapping(value = "/studentEdit.html", method = RequestMethod.GET)
public ModelAndView getStudentProfile(#RequestParam(value = "get", required = false) String get) {
if(get != null && get.equals("get")) {
return new ModelAndView("redirect:/viewStudents.html");
} else {
ModelAndView mav = new ModelAndView("studentEdit");
return mav;
}
}
function getStudent() {
$.ajax({
type: "GET",
url: "/IRSystem/studentProfileEdit.html",
data: "get=" + 'get',
success: function(response) {
},
error: function(e) {
alert('Error' + e);
}
});
}
I would appreciate any information, thank you.
If you want to redirect to another page after request, there is no need to use AJAX.
A simple link should be enough:
click me
What happens when you click on the link:
a GET request to /IRSystem/studentProfileEdit.html is performed
get=get is passed as request data
by default, user is redirected to link's href (i.e /IRSystem/studentProfileEdit.html), but you can redirect him somewhere else
Assuming the rest of your code is correct, using <a> as mentioned above together with redirect:/viewStudents.html should redirect as desired.
Also check the docs about redirect: prefix to make sure your redirect is interpreted correctly.
I have 2 files named Admin.java and index.jsp.
In Admin.java through a function I retrieve the value of the varible named res. This variable needs to be passed to a JSP page.
The Admin.java is in C:\Users\praveen\workspace\SemanticWeb\src\controller whereas the index.jsp is in C:\Users\praveen\workspace\SemanticWeb\WebContent.
The code of Admin.java is:
public Admin()
{
super();
}
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
if (action.equals("login"))
{
String userName="";
String password="";
userName = request.getParameter("username");
password = request.getParameter("password");
response.setCharacterEncoding("UTF-8");
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
return;
}
The code of index.jsp is
function login(user, pass)
{
$.ajax({
type:"GET",
url: "Admin?action=login",
dataType: "text",
data: { username: user, password: pass },
success: function(response){
}
within the
function(response)
{
......
}
I need to access the value of res passed by Admin.java. I am not able to get any proper help for my code on the Internet. Please can someone help me with this.
From your code,
request.setAttribute("rest", res);
You shouldn't set it as request attribute. Setting request attributes is only useful if you're forwarding to a JSP file. You need to write it straight to the response yourself. Replace the line by
response.getWriter().write(res);
This way it'll end up in the response body and be available as variable response in your JS function.
See also:
How to update current page by Servlet/Ajax?
Seems like you're doing AJAX, so I'd say your response would need to be encoded in an AJAX-compatible way (JSON, XML, ...).
If you do AJAX-encoding, your function might look like this:
function(response)
{
var toplevel = response.<your_top_level_element>;
}
Edit:
We're using JSON Simple for JSON encoding.
Our Java backend then looks like this (simplified version without error checking):
public String execute()
{
JSONObject jsonResult = new JSONObject();
jsonResult.put( "result", "ok");
return jsonResult.toJSONString();
}
And in the Javascript function:
function(response)
{
var result = response.result; //now yields "ok"
}
If this is an ajax request, you can forward the request into another jsp page rather than return. With this
getServletContext().getRequestDispatcher("/ajax.jsp").forward(request, response);
create the jsp page(ajax.jsp) on your webcontent and add this sample code.
<p>${rest}</p>
<!-- Note: You can actually design your html here.
You can also format this as an xml file and let your js do the work.
//-->
Another way is replace your System.out.println with this
PrintWriter out = response.getWriter();
out.print("The value of res been passed is "+res);
but I guess this is a bad practice. See example here.