I have been searching around for reason why I have error Neither BindingResult nor plain target object for bean name 'addItemForm' available as request attribute but can't understand.
The page is loading fine but if I click on Add new item button, a lightbox containing a form appears, I click on Add item and I got same error as above but bean name is searchForm.
The controller looks fine, I think there is a binding problem between the view and the form. Can someone explain please?
Also, it is able to add new items to database, so the POST method is working, but the view returns errors ..
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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=ISO-8859-1">
<title>Admin View</title>
<style type="text/css">
body{margin:0, padding:0}
#body{
text-align: center;
top: 3%;
}
.table2{
border-spacing: 5%;
}
.table1 {
border-collapse: collapse;
width: 80%;
}
.table1 tr:nth-child(odd) td{
background-color: #ffffff;
}
.table1 tr:nth-child(even) td{
background-color: #4da6ff;
}
.table1 td, th {
text-align: left;
border: 1px solid green;
}
.black_overlay{
display: none;
position: absolute;
top: 0%;
left: 0%;
width: 100%;
height: 100%;
background-color: black;
z-index:1001;
-moz-opacity: 0.8;
opacity:.80;
filter: alpha(opacity=80);
}
.white_content {
display: none;
position: absolute;
top: 25%;
left: 25%;
width: 50%;
height: 50%;
padding: 16px;
border: 16px solid orange;
background-color: white;
z-index:1002;
overflow: auto;
}
</style>
</head>
<body>
<div id="body">
<h3>This is the Administrator View</h3>
<p>From here, you can search for items in the database, view, add new items and delete items from database</p>
<table align="center">
<tr>
<td>
<form:form action="AdminView" method="POST" commandName="searchForm">
<form:input path="KeyWordSearch" size="40"/>
<input type="submit" name="search" value="Search Store"/>
</form:form>
</td>
<td><button onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">Add new item</button></td>
</tr>
</table>
<br>
<c:if test="${not empty itemList}">
<table class="table1" align="center">
<tr>
<th>Item Name</th>
<th>Date added</th>
<th>Item Description</th>
<th>View Details</th>
</tr>
<c:forEach var="item" items="${itemList}">
<tr>
<td>${item.itemName}</td>
<td>${item.itemAdded}</td>
<td>${item.itemDescription}</td>
<td>View</td>
</tr>
</c:forEach>
</table>
</c:if>
</div>
<div id="light" class="white_content">
<h2 align="center">Add new item to Store</h2>
<form:form action="AdminView" method="POST" commandName="addItemForm">
<table align="left">
<tr>
<th style="border:0">Item name</th>
<td><form:input path="ItemName"/></td>
</tr>
<tr>
<th style="border:0">Item location</th>
<td><form:input path="ItemLocation"/></td>
</tr>
<tr>
<th style="border:0">Item Description</th>
<td><form:textarea path="ItemDescription"/></td>
</tr>
<tr>
<td><input type="submit" name="add" value="Add Item"/></td>
</tr>
</table>
</form:form>
Close
</div>
<div id="fade" class="black_overlay"></div>
</body>
</html
This is the Controller:
package com.test.controller;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.test.forms.AddNewItemForm;
import com.test.forms.SearchForm;
import com.test.models.items.ItemIF;
import com.test.transaction.TransactionFactory;
/**
* Handles requests for Admin View page
* #author Trung
*
*/
#Controller
#RequestMapping (value = "/AdminView")
public class AdminViewController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView adminForm(Model model){
SearchForm searchForm = new SearchForm();
model.addAttribute("searchForm", searchForm);
AddNewItemForm addItemForm = new AddNewItemForm();
model.addAttribute("addItemForm", addItemForm);
return new ModelAndView("AdminView");
}
#RequestMapping (params = "search", method = RequestMethod.POST)
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, Model model){
List<ItemIF> relatedItems = null;
TransactionFactory transaction = new TransactionFactory();
relatedItems = transaction.retrieveItemByName(searchForm.getKeyWordSearch());
if (relatedItems.isEmpty()){
System.out.println("okay, there isn't any item that is matched your criteria");
} else {
model.addAttribute("itemList", relatedItems);
}
return "AdminView";
}
#RequestMapping(params = "add", method = RequestMethod.POST)
public ModelAndView addNewItemForm(#ModelAttribute("addItemForm") AddNewItemForm addItemForm){
TransactionFactory transaction = new TransactionFactory();
String itemName = addItemForm.getItemName();
String itemLocation = addItemForm.getItemLocation();
String itemDescription = addItemForm.getItemDescription();
transaction.insertItem(itemName, itemLocation, itemDescription);
return new ModelAndView("AdminView");
}
}
You need a BindingResult as parameter in both post methods after the #ModelAttribute parameter, like this:
public String processingSearchStore(#ModelAttribute("searchForm") SearchForm searchForm, BindingResult result, Model model){
Related
I do have some problems on how will I implement a pop-up on a link. I'm currently using Spring-boot with Thymeleaf
I'm planning to implement the pop up window upon pressing the "Edit" button. Currently it shows on a new tab.
Here's the HTML:
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:replace="template::header">
</head>
<body>
<div class="d-flex" id="wrapper">
<div th:insert="template::sidebar">
</div>
<div id="page-content-wrapper">
<nav th:insert="template::navbar">
</nav>
<div class="container-fluid">
<h1> Employee List </h1>
Add new Employee<br/><br/>
<table border="1" cellpadding="10">
<thead>
<tr>
<th> Employee Name </th>
<th> Designation </th>
<th> Credentials </th>
<th> Department </th>
<th> Image </th>
<th> Image filename </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr th:each="employee: ${employees}">
<td th:text="${employee.name}"></td>
<td th:text="${employee.designation}"></td>
<td th:text="${employee.credentials}"></td>
<td th:text="${employee.departmentName == null} ? 'Empty' : ${employee.departmentName}"></td>
<td><img th:src="#{'/uploads/' + ${employee.image_fn}}"/></td>
<td th:text="${employee.image_fn}"></td>
<td>
<a th:href="#{'/admin/employees/edit/' + ${employee.name}}" th:target="_blank"><button type="button" class="btn btn-primary">Edit</button></a> <!--Edit Button must launch a pop up window, but is currently launching only on new tab-->
<!-- -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#empDeleteConfirm">Delete</button>
<a th:href="#{'/admin/employees/imageUpload/' + ${employee.name}}">Upload Image</a>
</td>
<div class="modal fade" id="empDeleteConfirm" tabindex="-1" role="dialog" aria-labelledby="empDeleteConfirm" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="empDeleteConfirm">Are you sure?</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Do you want to delete this employee?
</div>
<div class="modal-footer">
<a th:href="#{'/admin/employees/delete/' + ${employee.name}}"><button type="button" class="btn btn-primary">Delete</button></a>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
</tr>
</tbody>
</table>
<!-- Modal -->
</div>
</div>
</div>
<script type="text/javascript" th:src="#{/js/jquery-3.4.1.min.js}"></script>
<script type="text/javascript" th:src="#{/js/bootstrap.js}"></script>
</body>
</html>
Here's the window to be shown on a pop up window:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head th:replace="template::header">
</head>
<body>
<div class="d-flex" id="wrapper">
<!-- <div th:insert="template::sidebar">
</div> -->
<div id="page-content-wrapper">
<!-- <nav th:insert="template::navbar">
</nav> -->
<div class="container-fluid" align="center">
<h1> Edit Employee </h1>
<form action="#" th:action="#{/admin/employees/update}" th:object="${employee}" method="post" th:fragment="empEdit">
<table border="0" cellpadding="10">
<td><input type="hidden" th:field="*{name}"/></td>
<td><input type="hidden" th:field="*{image_fn}"/></td>
<tr>
<td> Designation: </td>
<td><input type="text" th:field="*{designation}"/></td>
</tr>
<tr>
<td> Credentials: </td>
<td><input type="text" th:field="*{credentials}"/></td>
</tr>
<tr>
<select th:field="*{department}">
<option th:each="department: ${departments}" th:value="${department.name}" th:text="${department.description}"></option>
</select>
</tr>
<tr>
<td><button type="submit">Save</button></td>
</tr>
</table>
</form>
</div>
</div>
</div>
<script type="text/javascript" th:src="#{/js/jquery-3.4.1.min.js}"></script>
<script type="text/javascript" th:src="#{/js/bootstrap.js}"></script>
</body>
</html>
Using these controller:
import com.ppt.contentmanagementsystem.dao.DepartmentDAO;
import com.ppt.contentmanagementsystem.dao.EmployeeDAO;
import com.ppt.contentmanagementsystem.model.Department;
import com.ppt.contentmanagementsystem.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Optional;
#Controller
public class EmployeeVC {
#Autowired
EmployeeDAO employeeDAO;
#Autowired
DepartmentDAO departmentDAO;
#GetMapping("/admin/employees")
public String employeesHomePage(Model model){
List<Employee> employees = employeeDAO.getAllEmployees();
model.addAttribute("employees", employees);
model.addAttribute("title", "Employees");
return "employeeHome";
}
#GetMapping("/admin/employees/new")
public String newEmployeePage(Model model){
Employee employee = new Employee();
List<Department> departments = departmentDAO.getAllDepartments();
model.addAttribute("employee", employee);
model.addAttribute("departments", departments);
return "employeeNew";
}
#PostMapping("/admin/employees/new")
public String addEmployeePage(#ModelAttribute("employee") Employee employee){
employeeDAO.addEmployee(employee);
return "redirect:/admin/employees";
}
#GetMapping("/admin/employees/edit/{id}")
public String editEmployeePage(Model model, #PathVariable String id){
Optional<Employee> eopt = employeeDAO.getEmployee(id);
Employee employee = eopt.get();
List<Department> departments = departmentDAO.getAllDepartments();
model.addAttribute("employee", employee);
model.addAttribute("departments", departments);
model.addAttribute("title", "Employee Edit");
return "employeeEdit";
}
#GetMapping("/admin/employees/imageUpload/{id}")
public String uploadEmployeeImagePage(Model model, #PathVariable String id){
Optional<Employee> eopt = employeeDAO.getEmployee(id);
Employee employee = eopt.get();
model.addAttribute("employee", employee);
model.addAttribute("title", "Employee Image");
return "employeeImage";
}
#PostMapping("/admin/employees/imageUpload")
public String updateEmployeeImage(#ModelAttribute("employee") Employee employee, #RequestParam("imageFile") MultipartFile imageFile) throws IOException{
employeeDAO.saveEmployeeImage(employee, imageFile);
return "redirect:/admin/employees";
}
#PostMapping("/admin/employees/update")
public String updateEmployeePage(#ModelAttribute("employee") Employee employee){
employeeDAO.updateEmployee(employee);
return "redirect:/admin/employees";
}
#GetMapping("/admin/employees/delete/{id}")
public String deleteEmployeePage(#PathVariable String id){
employeeDAO.deleteEmployee(id);
return "redirect:/admin/employees";
}
}
For modal window you should add the JavaScript code to your template as described here
Thymeleaf documentation 13.4 Textual parser-level comment blocks: removing code
Simple implementation of the modal window in js is:
<!DOCTYPE html>
<html> <head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style> body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0; top: 0; width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0,0,0);
/* Fallback color */
background-color: rgba(0,0,0,0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover, .close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById("myModal");
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() { modal.style.display = "block"; }
// When the user clicks on <span> (x), close the modal
span.onclick = function() { modal.style.display = "none"; }
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
} }
</script>
</body> </html>
I've found a textual solution here: Spring MVC: Open link in new browser window in handler method
And a tutorial explaining Javascripts window.open function
https://www.youtube.com/watch?v=G83c-ZqZ7pk
Answering the question on how to open a new browser-window (popup) when clicked on an element or link.
I got this jsp for logging page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.error {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.msg {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
#login-box {
width: 300px;
padding: 20px;
margin: 100px auto;
background: #fff;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border: 1px solid #000;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>
<h1>Spring Security Custom Login Form (Annotation)</h1>
<div id="login-box">
<h2>Login with Username and Password</h2>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='user' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'>
<input name="submit" type="submit" value="submit" />
</td>
</tr>
</table>
<input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</div>
</body>
</html>
and in the controller:
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
#RequestParam(value = "error", required = false) String error,
#RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}
and security config:
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}123456").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/admin/**").access("hasRole('ROLE_USER')").and().formLogin()
.loginPage("/login").permitAll().failureUrl("/login?error").usernameParameter("username")
.passwordParameter("password").and().logout().logoutSuccessUrl("/login?logout").and().csrf();
}
}
After loggin I don't get valid url like: localhost/com.myproject.spring/login?error
or localhost/com.myproject.spring/admin
but I get always:
localhost/com.myproject.spring/j_spring_security_check and error message: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
What is wrong? I've just copied everything from this tutorial: https://www.mkyong.com/spring-security/spring-security-custom-login-form-annotation-example/
I want to retrieve the parameters sent through the form login.jsp in the controller..but I am getting the error-"Request parameter is not present". My code for login.jsp is as follows:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring Security</title>
</head>
<body>
<center>
<h1>Welcome to Spring Security Learning</h1>
<c:if test="${not empty SPRING_SECURITY_LAST_EXCEPTION}">
<font color="red">
Your login attempt was not successful due to <br/><br/>
<c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}"/>.
</font>
</c:if>
<div style="text-align: center; padding: 30px; border: 1px solid; width: 250px;">
<form method="post"
action='j_spring_security_check'>
<table>
<tr>
<td colspan="2" style="color: red">${message}</td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" name="j_username" id="uname"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="j_password" /></td>
</tr>
<tr>
<td colspan="1"><input type="submit" value="Login" /></td>
<td colspan="1"><input name="reset" type="reset" /></td>
</tr>
</table>
</form>
</div>
</center>
</body>
</html>
The code for controller is as follows:-
#RequestMapping("/search")
public ModelAndView search(HttpSession session2,#RequestParam("j_username") String name) {
session2.setAttribute("name", name);
Session session=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory().openSession();
String hql = "SELECT E.firstName FROM User E";
Query query = session.createQuery(hql);
List results = query.list();
//System.out.println(results.get(1).getClass().getFields());
HashMap model = new HashMap();
model.put("users", results);
return new ModelAndView("search", model);
}
Please help..thanx in advance..
From what I can see when the checkbox page passes of parameters to the Proto page, which puts it in the portfolio object which is then used to check the value of the data and display the portfolio name ,and when the proto page refreshes the parameters arent passed again from the checkbox page and the portfolio object has a null value stored in it which gives a null pointer exception.
so if I store the parameter values once they're already passed from the checkbox page would that solve the problem ? And if so how can I go about it ?
Here is the code for proto page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="oracle.jdbc.pool.OracleDataSource"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<head>
<title>Live Data Tracking</title>
<style type='text/css'>
.wrapper {
margin: 0px auto;
width: 1379px;
background-color: #cccccc
}
.header {
float: left;
width: 100%;
background-color: #356aa0
}
.left1 {
float: left;
margin-right: 10px;
width: 338px;
background-color: #ffffff
}
.left2 {
float: left;
margin-right: 10px;
width: 337px;
background-color: #ffffff
}
.left3 {
float: left;
margin-right: 10px;
width: 337px;
background-color: #ffffff
}
.right {
float: right;
width: 337px;
background-color: #ffffff
}
.footer {
float: left;
width: 100%;
background-color: #00457b
}
body {
padding: 0px;
margin: 0px;
font-size: 90%;
background-color: #e7e7de
}
</style>
</head>
<script type="text/javascript">
<%
ArrayList<ArrayList<String>> testList = new ArrayList();
portfolio = request.getParameterValues("portfolio");
try{
OracleDataSource ds= new OracleDataSource();
//javax.sql.DataSource ds = new javax.sql.DataSource();
ds.setDriverType("thin");
ds.setServerName("localhost");
ds.setPortNumber(1521);
ds.setDatabaseName("orcl");
ds.setUser("system");
ds.setPassword("amex1234");
Connection connection = ds.getConnection();
System.out.println("Connected Successfully");
Statement statement = connection.createStatement() ;
if (portfolio!=null)
{
for(int i=0;i<portfolio.length;i++)
testList.add(new ArrayList());
//System.out.println(testList);
for(int i=0; i<portfolio.length;i++)
{ String temp="";
ResultSet resultset = statement.executeQuery("select num FROM "+portfolio[i]+"_Test") ; //Put in SQl command and Table name here
while(resultset.next()){
temp = resultset.getString(1);
testList.get(i).add(temp);
}
//System.out.println(testList);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
%>
</script>
<body>
<%! String[] portfolio; %>
<div class="wrapper">
<div class="header">
<center>
<h4>Live Tracker</h4>
</center>
</div>
<div class="left1">
<h3>Portfolio</h3>
<%
if (portfolio != null)
{
for (int i = 0; i < portfolio.length; i++) //i=portfolio length proxy
{
out.println ("<b>"+portfolio[i]+"<b>"); %>
<br>
<% }
}
else out.println ("<b>none<b>");
%>
</div>
<div class="left2">
<h3>Pre-Stage</h3>
for (int j = 0; j < portfolio.length; j++)
{
response.setIntHeader("Refresh", 2);
//System.out.println(testList.get(j).size());
if (testList.get(j).size()!=0){ %>
Data is there <br>
<% } else { %>
No data <br>
<% }
}%>
</div>
<div class="left3">
<h3>Stage</h3>
</div>
<div class="right">
<h3>Mirror</h3>
</div>
<div class="footer">Something Funny and Witty Here</div>
</div>
</body>
</HTML>
This is the code for the checkbox page. Run via this page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<body>
<FORM method="POST" ACTION="Proto_1.jsp">
<center>
Select your portfolio(s): <br><br>
<table>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=X>
</td>
<td>
X
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=Y>
</td>
<td>
Y
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=W>
</td>
<td>
W
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=V>
</td>
<td>
V
</td>
</tr>
<tr>
<td>
<input TYPE=checkbox name=portfolio VALUE=S>
</td>
<td>
S
</td>
</tr>
</table>
<br> <INPUT TYPE=submit name=submit Value="Submit">
</center>
</FORM>
</BODY>
</HTML>
There are several options to resolve.
Option 1: Set the params into session. Instead of:
portfolio = request.getParameterValues("portfolio");
Try this:
String[] portfolio = null;
if(null == request.getParameter("submit")) { //page reload, true
portfolio = (String[])session.getAttribute("portfolio");
} else {
portfolio = request.getParameterValues("portfolio");
session.setAttribute("portfolio", portfolio);
}
Option 2: Separate the view and business logic i.e. split your page into two. First jsp to get the portfolio from request and make frequent call to get the updated records from the second jsp. This approach requires JavaScript.
View.jsp: Make call to the Records.jsp frequently using setInterval()
<script>
var getRecords = function() {
// to do here
};
setInterval(getRecords, 2 * 1000); (in miliseconds)[every 2 sec]
</script>
Records.jsp: Generate dynamic html along with records
You can save the checkbox data to the session via session.setAttribute("portfolio", portfolio).
You can retrieve this and set the value back to the page via document.getElementById(id).value or via value={$sessionVariable} in jsp
I want to implement easy validation with Spring MVC.
I added to pom.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
Here is my POJO:
import org.hibernate.validator.constraints.Range;
public class Goal {
#Range(min = 1, max = 120)
private int minutes;
// getters + setters
and Controller implementation:
import javax.validation.Valid;
#Controller
#SessionAttributes("goal")
public class GoalController {
#RequestMapping(value = "addGoal", method = RequestMethod.GET)
public String addGoal(Model model) {
Goal goal = new Goal();
goal.setMinutes(10);
model.addAttribute("goal", goal);
return "addGoal";
}
#RequestMapping(value = "addGoal", method = RequestMethod.POST)
public String updateGoal(#Valid #ModelAttribute(value = "goal") Goal goal, BindingResult result) {
System.out.printf("Result has errors: %s%n", result.hasErrors());
System.out.printf("Minutes updated: %d%n", goal.getMinutes());
if (result.hasErrors()) {
return "addGoal";
}
return "redirect:/addMinutes.html";
}
}
addGoal.jsp page:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html>
<head>
<title>Add Goal Here</title>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffeeee;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
</head>
<body>
Language: English | Ukrainian
<form:form commandName="goal">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td><spring:message code="goal.minutes"/></td>
<td><form:input path="minutes"/></td>
<td><form:errors path="minutes" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3">
<input type="submit" value="Enter Goal Minutes"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
And here is page view:
And appropriate result:
snippet from console:
Result has errors: false
Minutes updated: -5
It should display error message for negative input and stay at the same page instead second screen shot.
I couldn't figure out causing of this trouble.
Any suggestion?
Solution was cleaned - webapps folder at Tomcat.
I deleted old webapps which were deployed. And now it works fine.
It has some strange impact on my current application.