I'm new in Spring, and I'm trying to better undestand the MVC framework.
Considering the following jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
</head>
<body>
Welcome <%=request.getAttribute("username")%>
</body>
</html>
I see that, in a #Controller class:
#GetMapping("/EntryPoint1")
public String helloView1(Model model) {
model.addAttribute("username", "pippo");
return "HelloWorld";
}
it uses as username value the one inserted in model.
However, if I declare both the Model model parameter and I return a ModelAndView object, that is:
#GetMapping("/EntryPoint2")
public ModelAndView helloView2(Model model) {
model.addAttribute("username", "pluto");
ModelAndView mav = new ModelAndView("HelloWorld");
mav.addObject("username", "paperino");
return mav;
}
I obtain that the value used by the view is the one contained in mav ignoring the value in model. Is there an explanation for this (for example, any kind of precedence between the objects considered by the view)?
see, here in model.addAttribute("username", "pluto");
and in mav.addObject("username", "paperino");
username is same so priorities goes to ModelAndView, However u change the name then u can render them both and access.
Related
I'm making a simple SpringBoot app that returns a word inserted by the user via a form. I managed to get the response in another view (the form is in home.html, the answer in answer.html) but now I want to get the response in the "home" view. I tried to adapt the code from the two-view version, but it doesn't work. Any thoughts? Thanks!
the HTML view:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add a word</title>
</head>
<body>
<th:form action="/" object="word" method="POST">
<label>Dictionary - Add a word</label>
<br>
<input name="value">
<br>
<button type="submit">Submit</button>
</th:form>
<p th:text="${value}"></p>
</body>
</html>
The controller:
#RestController
public class Controller {
#GetMapping("/")
public ModelAndView home() {
return new ModelAndView("home", "word", new Word());
}
#PostMapping("/")
public ModelAndView home(#ModelAttribute("word") Word w, Model model) {
ModelAndView mAv = new ModelAndView("home", "word", model);
model.addAttribute("value", w.getValue());
return mAv;
}
}
I want to pass a data from controller method to jsp page. In doing so, using HttpServletRequest.setAttribute().
Now, I can pass it to the just next jsp page. But, I want to hold that data for few more pages.
In this case, what should I do?
Flow of Data:
Controller method1 --> jsp page1 --> jsp page2 --> jsp page3 --> jsp page4 --> Controller method2
I tried setting attribute in each page but it returns null value, as follows
<% request.setAttribute("accId", request.getAttribute("accountId")); %>
You have to use session in jsp when sending data from one page to another.
A demo to show this.
For example :
Create a DemoController class.
#Controller
public class DemoController {
#RequestMapping(value = "/getid", method = RequestMethod.POST)
public String getAccountID(Model model) {
model.addAttribute("accountId", "ABC1234"); // example
return "account";
}
}
Suppose, create an account.jsp.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String accountId = request.getAttribute("accountId");
out.println("account.jsp -> " + accountId);
session.setAttribute("accId", accountId);
%>
<form action="account2.jsp" method="post">
<input type="submit" name="Submit">
</form>
</body>
</html>
Create another page with the name account2.jsp :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<%
String accId = (String) session.getAttribute("accId");
out.println("account2.jsp -> " + accountId);
// now you want to sent it to the another controller
// set the parameter in the session and retrieve it in the controller.
session.setAttribute("accountId", accId);
%>
</body>
</html>
Create a DemoController2 class :
#Controller
public class DemoController2 {
#RequestMapping(value = "/getid2", method = RequestMethod.POST)
public String getAccountId2(HttpSession session) {
String id = (String) session.getAttribute("accountId"); // example
System.out.println(id);
return "some-page-name";
}
}
I am trying to create a simple function using a post method. What I want is whatever is entered in the form and submitted- it should appear on the same page below the form. However the text just disappears once I click "submit". Here is my code
Contoller
#Controller
public class SearchController {
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String goToSearch(Model model) {
model.addAttribute("item", new Item());
return "itemsearch";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Item item, Model model, #RequestParam String itemId) throws IOException{
model.addAttribute("item", new Item());
return "itemsearch";
}
}
Jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h2>Search for an item</h2>
<sf:form action="search" method="POST" modelAttribute="item">
<label>Please enter the item Id number:<sf:input type="text" name="itemId" id="itemId" path="itemId" /></label><br/>
<input type="submit" value="Submit" path="submit" />
<br> You are trying to search for Id Number: <b><h3>${item.itemId}<h3></h3></b>
</sf:form>
Item class
public class Item {
private String itemId;
private List<String> itemDetails;
public List<String> getItemDetails() {
return itemDetails;
}
public void setItemDetails(List<String> itemDetails) {
this.itemDetails = itemDetails;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
Many thanks
I think you need a basic understanding how Spring MVC works.
Have a look at this picture:
You see an incoming request (your POST request) from the client which is redirected to the desired controller. The controller (your SearchController) makes some business magic and returns the model to the front controller. The model is by default empty. You can add objects that should be rendered via model.addAttribute("someId", someObject);
The passed model is now handled by the view template (itemsearch) which connects the template and the model to a (static) response that is passed to the client.
And there is the problem. You are passing in your controller new Item() to the model. It is an empty object which has no values (and no id which you want to render after the form submition). Therefore on your JSP page could be nothing displayed. Just pass the found item or the item from your request to the model.
I am implementing simple CRUD Operation using spring restful webservices and angular js.I trying to load all the details when the page is loading.But its not getting any response.
Controller :-
#RestController
public class EmployeeController {
public List<Employee> appList=new ArrayList<Employee>();
#RequestMapping(value="/employee",method=RequestMethod.GET)
public ModelAndView loadEmployee(){
return new ModelAndView("employee", "webemployee", new Employee());
}
#RequestMapping(value="/employees",method = RequestMethod.GET,headers="Accept=application/json")
public List<Employee>loadAllApps() {
Employee app=new Employee();
System.out.println(".........................loadAllApps.............");
app.setAppID("test_id");
app.setAppName("test_name");
appList.add(app);
return appList;
}
#RequestMapping(value="/employees/insert/{appID}/{appDescr}",method = RequestMethod.POST,headers="Accept=application/json")
public List<Employee> addApps(#PathVariable String appID,#PathVariable String appDescr) throws ParseException {
System.out.println("appID"+appID+"appDescr..........."+appDescr);
Employee app=new Employee();
app.setAppID(appID);
app.setAppName(appDescr);
appList.add(app);
return appList;
}
}
Jsp :-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html ng-app="AppManger">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>WebService Example</title>
<script data-require="angular.js#*" data-semver="1.2.13" src="http://code.angularjs.org/1.2.13/angular.js"></script>
</head>
<div ng-controller="appController">
<div>
<table>
<tr ng-repeat="app in appList">
<td >{{ app.appID }}</td>
<td >{{ app.appName }}</td>
</tr>
</table>
</div>
<script type="text/javascript">
var appModule = angular.module('AppManger', []);
appModule.controller('appController', function ($scope,$http) {
var url="http://localhost:8080/Apps";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get(url+'/employee').
success(function(data, status, headers, config) {
alert(status);
$scope.appList = data;
});
});
</script>
</script>
</html>
when i am trying to checking status value in $http.get method.its not showing any alert message.Please let me know what issues here.
You seem to call your /employee endpoint but expecting a list of employees , because you assigning data response to the:
$scope.appList = data;
First, change that to the other endpoint you created (/employees) which returns the list.
What is the servlet-path of your mvc dispatcher servlet? This would be my first point of failure to check for. I see that you call:
var url="http://localhost:8080/Apps";
Does that mean that you deploy your app in context 'Apps' or is that your servlet path? If this is the context name then I assume that mvc is resolved to the 'root' path i.e. '/'. If not, check what is servlet path for the dispatcher and add that to your url (on the client side). This would explain why you get 404.
And also, check that you can call your API directly in the browser to rule out the server-side errors as user Chandermani suggested.
I am sending Object with help of ModdelAndView in Spring controller, but i am not able to read it on jsp?
JSP:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
Tried with EL:
${user}
Try with JSTL:
<c:out value="${user}"></c:out>
</body>
</html>
controller:
#Controller
public class StudentHome {
#RequestMapping(value = "/auth/Home")
public ModelAndView RedirectLogin() {
ModelAndView modelAndView = new ModelAndView("/auth/Home");
modelAndView.addObject("user", "Alex");
return modelAndView;
}
}
I have tried both Spring EL and jstl its not working. Do i need to include anything else?
We need to include org.springframework.web.servlet.ModelAndView instead of org.springframework.web.portlet.ModelAndView;
The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.
update your code as follows
#Controller
public class StudentHome {
#RequestMapping(value = "/auth/Home")
public ModelAndView RedirectLogin() {
return new ModelAndView("yourJspName","user", "Alex");
}
}
then in your jsp, to display the message, you will do
Hello ${user}!
hope this will help you..!