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..!
Related
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.
This way is not greatest. I'm looking for a better way. Is it possible to do without Lists?
My PageController:
public class CreateUserPageController {
#Autowired
private UserServiceImpl userServiceImpl;
#RequestMapping(value = "/create-user", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("admin/create-user");
model.addObject("user", new User());
UserRoleDTO[] roles = UserRoleDTO.values();
List<String> roleNames = new ArrayList<>();
for (UserRoleDTO role : roles) {
roleNames.add(role.getName());
}
model.addObject("roleNames", roleNames);
return model;
}
#RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView submitForm(#ModelAttribute("user") User user) {
userServiceImpl.create(user);
return showForm();
}
}
My JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Create test</title>
</head>
<body>
<h1>Create Test</h1>
<form:form method="POST" action="/create-test" modelAttribute="topicTestDTO">
<form:input path="topic.name" type="text" list="topic_list" placeholder="choose or create topic"/>
<datalist id="topic_list">
<c:forEach items="${topicList}" var="topic">
<option>${topic}</option>
</c:forEach>
</datalist>
<br>
<form:input path="test.name" type="text" placeholder="create test name"/>
<input type="submit">
</form:form>
</body>
</html>
Thanks for help.
If you need more information, tell me which one and I'll complete the code.
Here the problem is for every request it goes to Database to retrieve the data, even data is not changing also it reduces the performance of application.
By using local cache we can achieve performance, so while application loading it self data will be queried from database and store it in cache,then we can reuse the data from cache.
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 new to spring MVC .My abc page is have one submit button. On click of submit button, abcHandler called which is inside xyzController.
Just wondering how to achieve this scenario.
-- If some error occurs then it should return some message.
-- It should stay in the same page , for me its abc page.
I have tried this.The problem I am facing is that , i am getting the alert message as "You must have something...",
but it is navigating to error page means a blank page. This is not suppose to happen.I want to show the message and stay in the same page.
How can i achieve easily with spring MVC.
Please suggest some idea.
public class xyzController extends MultiActionController implements InitializingBean {
public ModelAndView abcHandler(HttpServletRequest request,HttpServletResponse response)throws Exception {
// session
HttpSession session = request.getSession(true);
String abc = "";
if(abc != ""){
}else{
String error = "You must have xyzzzzzz";
return new ModelAndView("2.0/error", "downloaderror", error);
}
return new ModelAndView();
}
}
My error.jsp is like this
<!DOCTYPE html>
<html>
<head>
<script src="abc/js/jquery-1.9.0.min.js"></script>
</head>
<body>
<c:if test="${not empty downloaderror}">
<script>
alert("You must have something...");
</script>
</c:if>
</body>
</html>
You can implement HandlerExceptionResolver on your own.Refer to this tutorial: http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
Add an error flag in controller method like this
public ModelAndView abcHandler(HttpServletRequest request, HttpServletResponse response)throws Exception {
ModelAndView model=new ModelAndView();
model.addObject("error", true);
return model;
}
In JSP
<!DOCTYPE html>
<html>
<head>
<script src="abc/js/jquery-1.9.0.min.js"></script>
</head>
<body>
<c:if test="${error}">
<script>
alert("You must have something...");
</script>
</c:if>
</body>
</html>
You can achieve the scenario by going in following way:
import org.springframework.web.servlet.ModelAndView;
public ModelAndView abcHandler(HttpServletRequest request, HttpServletResponse response)throws Exception {
ModelAndView model=new ModelAndView();
model.addObject("ERROR_CODE", "Error Occurred");
model.setViewName("page1");
return model;
}
and your jsp page will be like following:
page1.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<body>
<c:if test="${!empty ERROR_CODE }">
<c:out value="${ERROR_CODE }"></c:out>
</c:if>
</body>
</html>
On validation failure do not return to error page, instead return to same page so your code in else block should be
}else{ String error = "You must have xyzzzzzz";
return new ModelAndView("2.0/error", "downloaderror", abc); }
And also store the errormessage in your modelmap against some key like "errormsg" and on your abc page check for this key and then print the message.