I am trying to make my first web project using Spring MVC.
I have problem when i try to show variables that has been put into my model.
But on my page see my test parameter, but my table is empty.
Please, tell me, what i missed.
Im using tiles controller, so here is my tile of home.jsp where i want to show my list:
<div id="indexLeftColumn">
<div id="welcomeText">
<p>[ cool picture ]</p>
</div>
</div>
<div id="indexRightColumn">
<div id="deviceList">
Table with list of devices</br>
${blah}
<table class="table" border="1">
<thead>
<tr>
<th>Device ID</th>
</tr>
</thead>
<tbody>
<c:forEach items="${hubsIDList}" var="hub" >
<tr>
<td>${hub}</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
Here is part of my controller which adds values and returns my home.jsp
I added new parameter "blah" just to test, that parameters not disappear elsewhere
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String home(Model model) {
log.info("Loading homepage");
UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ArrayList<String> hubsID =(ArrayList<String>) userDetails.getParameter("hubsID"); //checked - it's not empty and truly Array list of Strings
model.addAttribute("hubsIDList",hubsID);
model.addAttribute("blah","Test if parameters still here"); //added for test that my parameters aren't dissapear
return "home";
}
And here is my includes
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="spring_form" %>
<%# taglib uri="http://www.springframework.org/security/tags" prefix="sec" %>
UPD
Tried to use controller metod as below, but still no result - test parameter is visible on page, but table is empty
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home(Model model) {
HashMap<String,Object> modelParams = (HashMap)model.asMap();
log.info("Loading homepage");
UserDetailsImpl userDetails = (UserDetailsImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ArrayList<String> hubsID =(ArrayList<String>) userDetails.getParameter("hubsID");
modelParams.put("hubsIDList",hubsID);
modelParams.put("blah","Test if parameters still here");
return new ModelAndView("home",modelParams);
}
Problem is somewhere in my tiles controller. Somehow my taglibs was not connected to my home.jsp tile so my c: tags was unusable. If i use taglib directly in my jsp - all is works.
Hope this will help someone with same problem.
Thanx #Koitoer for helping me in my tries.
Related
What I am want to do is to add a record to a table and then to display that newly added record in a jsp page.
Here is what I tried:
Controller:
#Controller
public class UserController {
#Autowired
UserRepository userRepo;
#RequestMapping("/adduser")
public String userform(Model m){
m.addAttribute("command", new Users());
return "adduser";
}
#RequestMapping("/saveuser")
public String save(#ModelAttribute("user") Users user,Model model){
userRepo.save(user);
model.addAttribute("user", user);
return "forward:/user";
}
#RequestMapping("/user")
public String user(Model model) {
return "user";
}
And the jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css"
href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
<c:url value="/css/main.css" var="jstlCss" />
<link href="${jstlCss}" rel="stylesheet" />
</head>
<body>
<div class="container">
<div class="starter-template">
<h1>Product List</h1>
<table
class="table table-striped table-hover table-condensed table-bordered">
<tr>
<th>Id</th>
<th>Color</th>
<th>Gender</th>
<th>Category</th>
</tr>
<c:forEach var="u" items="${user}">
<tr>
<td>${u.userid}</td>
<td>${u.username}</td>
<td>${u.userphone}</td>
<td>${u.useremail}</td>
</tr>
</c:forEach>
</table>
</div>
</div>
<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Upon running the code the record is getting added successfully but It is not getting displayed instead I am getting the error mentioned in the title.
What to do to make it work?
#RequestMapping("/user")
public List<User> user(Model model) {
...
return ...;
}
${user} is the result of that method user.
<c:forEach var="u" items="${user}">
The forEach tag requires as itemssomething Iterable.
In fact the name should have been plural: users.
You need something like
public class User {
int userid;
String username;
String userphone;
String useremail;
}
<td>${u.userid}</td>
<td>${u.username}</td>
<td>${u.userphone}</td>
<td>${u.useremail}</td>
I am using hibernate to get the subjects associated with a particular user. In mainPage, I want to see firstName and LastName (this works) of the user and allowed subjects. But, for some reason, I am not able to successfully iterate over the list of subjects put in mainPage.
In my Spring controller I have a method, which looks like this:
#RequestMapping(value = "/signin", method = RequestMethod.POST)
public String SignIn(#ModelAttribute("user") User user, ModelMap modelMap){
String username = user.getUsername();
String password = user.getPassword();
User user1 = userService.getUser(username, password);
if(user1 != null){
List<Subject> subjectList = userService.getUserSubjects(user1.getId());
modelMap.addAttribute("subjects", subjectList);
modelMap.addAttribute("user", user1);
return "mainPage";
}
modelMap.addAttribute("ShowNotAuthenticated", true);
return "authentication";
}
mainPage.jsp looks like this:
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>Current user: ${user.firstName} ${user.lastName}</h2> //this works
<br>
<h3>Allowed subjects:</h3>
<table>
<tr>
<td>
Subject Name
</td>
</tr>
<c:forEach items="${subjects}" var="x"> //doesn't work
<tr>
<td>
${x.name}
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
This is SignIn method during debug:
These are pictures in mainPage.jsp:
Mykhailo Moskura's suggestion doesn't work too:
From debugger screenshot I see that your subjectList has elements of type Object[]. So you either need to change what you store in that list or try to use ${x[1]} instead of ${x.name}.
How it would be better to get value from dropdown list in JSP in such case? Now 400 status error appears after pressing Submit button. I tried to search for the solution in Google, but there was no any variant which would helped me.
There are some fragments of code, which belongs to this issue.
First class:
public class Item1 {
private int id;
private Item2 item2;
//getters, setters
}
Second class:
public class Item2 {
private int id;
private String description;
//getters, setters
}
First class controller:
#Controller
public class Item1Controller {
#Autowired
private Item1DAO item1DAO;
#RequestMapping(value = "/saveItem1", method = RequestMethod.POST)
public ModelAndView saveItem1 (#ModelAttribute Item1 item1) {
item1DAO.addOrUpdateCourse(item1);
return new ModelAndView("redirect:/item1List");
}
}
JSP Form:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#page isELIgnored="false" %>
<html>
<head>
<title>Add New Item1</title>
</head>
<body>
<form:form method="POST" action="/saveItem1" modelAttribute="item1">
<table>
<form:hidden path="id"/>
<tr>
<td><form:label path="Item2">Item2</form:label></td>
<td>
<form:select path="item2">
<form:option value="null">No Item2</form:option>
<form:options items="${item2List}"/>
</form:select>
</td>
</tr>
<tr>
<td>
<input type="submit" value="Save Item1"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
You should put "get" and "set" methods (public) into the Item classes. A public constructor would be a good thing.
I would try to write the same path attribute value: description
You have multiple mistakes in the form paths. Each must reference a simple field, not a complex object.
For example, you need:
<form:input path="item2.description"/> <!-- not path="description", no description in the Item1 model -->
<form:label path="item2.id"> <!-- not "Item2" by itself, and wrong case -->
<form:select path="item2.id"> <!-- not "item2" by itself -->
Browsed the forum but didn't find solution which can solve my problem. There are 2 pages: index.jsp - start page which includes form to be populated and the list of results; edit.jsp - allows to edit data of any row from the list of results provided by index.jsp.
When I fill in the form all the data subbmitted successfully, when I try to edit any row in the list of results I redirected to edit.jsp but if I submit the changes an exception is thrown: HTTP Status 405 - Request method 'POST' not supported. I would appreciate any idea how to treat the issue.
index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="s" uri="http://www.springframework.org/tags" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title></title>
</head>
<body>
<form:form method="post" action="add" modelAttribute="account">
<table>
<tr>
<td><form:label path="number">Number</form:label></td>
<td><form:input path="number"/></td>
</tr>
<tr>
<td><form:label path="amount">Amount</form:label></td>
<td><form:input path="amount"/></td>
</tr>
<tr>
<td><form:label path="currency">Currency</form:label></td>
<td><form:input path="currency"/></td>
</tr>
<tr>
<td><form:label path="date">Date</form:label></td>
<td><form:input path="date" type="date"/>
</tr>
</table>
<input type="submit" value="Submit"/>
</form:form>
<table>
<tr border="1">
<td>Number</td>
<td>Amount</td>
<td>Currency</td>
<td>Date</td>
</tr>
<c:forEach items="${listOfAccounts}" var="items">
<tr border="1">
<td>${items.number}</td>
<td>${items.amount}</td>
<td>${items.currency}</td>
<td>${items.date}</td>
<td>edit</td>
</tr>
</c:forEach>
</body>
</html>
edit.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Edit Account</title>
</head>
<body>
<form:form modelAttribute="account" method="post" action="edited">
<form:hidden path="id" value="${account.id}"></form:hidden>
<form:label path="number">Number</form:label>
<form:input path="number" value="${account.number}"/><br>
<form:label path="amount">Amount</form:label>
<form:input path="amount" value="${account.amount}"/><br>
<form:label path="currency">Currency</form:label>
<form:input path="currency" value="${account.currency}"/><br>
<form:label path="date">Date</form:label>
<form:input path="date" type="date" value="${account.date}"/>
<input type="submit" value="Submit"/>
</form:form>
</body>
</html>
Controller.java
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
private Account account;
#RequestMapping(value="/", method = RequestMethod.GET)
public String welcomeMethod(ModelMap map) {
Account account = new Account();
map.addAttribute("account", account);
map.addAttribute("listOfAccounts", accountService.getListOfAccounts());
return "index";
}
#RequestMapping(value="add", method = RequestMethod.POST)
public String addAccount(#ModelAttribute(value="account") Account account, ModelMap map) {
accountService.addAccount(account);
map.addAttribute("listOfAccounts", accountService.getListOfAccounts());
return "index";
}
#RequestMapping(value="edit/{id}", method = RequestMethod.GET)
public String editAccount(#PathVariable("id") int id, ModelMap model) {
Account account = accountService.getAccountById(id);
model.addAttribute("account", account);
return "edit";
}
#RequestMapping(value="edited", method = RequestMethod.POST)
public String updateAccount(#ModelAttribute(value="account") Account account, ModelMap map) {
accountService.updateAccount(account);
map.addAttribute("listOfAccounts", accountService.getListOfAccounts());
return "index";
}
}
Your problem is that you are using relative mappings in your form, when you click on edit, your URL becomes /edit/{someid} and your edit.jsp form is loaded. When you edit the data and click submit, your URL will become /edit/{someid}/edited, the mapping will match the /edit/{someid} handler method witch is using a GET method and that is why you get your error.
To solve it, in your edit.jsp simple add a backslash to action, action="/edited"
Hope it helps
I'm using Spring MVC to pass a ArrayList object from my Controller to JSP and I want to iterate it over there using JSTL (forEach), but it is always crashing Java server after 10~20 seconds loading the page. It's not throwing any exception.
Trying to use "c:out" to print the String representing the array works fine. Same to not empty validation. It always crashes when program reaches the forEach.
SIMPLIFIED EXAMPLE BELOW
Controller method
#RequestMapping(value = "/main", method = {RequestMethod.POST}, params = "create")
public ModelAndView createBranch (Branch branch) throws FxtrmServiceException, JsonGenerationException, JsonMappingException, IOException{
ModelAndView branchMV = new ModelAndView("branch");
ArrayList<String> array1 = new ArrayList<String>();
array1.add("test1");
array1.add("test2");
branchMV.addObject("alertMap1", array1);
populateAutoCompletes(branchMV);
return branchMV;
}
JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
(...)
<c:if test="${not empty alertMap1}">
<c:forEach items="${alertMap1}" var="entry1">
<c:out value="${entry1}"/><br>
</c:forEach>
</c:if>