Spring MVC Page - java

I have a question, I didn't understand why this part of the code(where is registration) Spring doesn't find even if I wrote an url. But the same code in another part, for example, add a new book or add the new author of the book is working correctly it added everything into the database and send me into another page. But if I register the person and click submit it always shows me 400 - bad request error. Please help me. What I wrote wrong?
This is my controller(doesn't work registration part with register book (not redirect to registerbook and doesn't add data into DB)):
#Controller
public class HelloController {
private static final Logger logger = Logger.getLogger(HelloController.class.getName());
#Autowired
#Qualifier("author")
private AuthorzDAO authorzDAO;
#Autowired
#Qualifier("book")
private BooksDAO booksDAO;
#Autowired
#Qualifier("borrow")
private BorrowsDAO borrowsDAO;
#Autowired
#Qualifier("person")
private PersonDAO personDAO;
#RequestMapping(value = "/",method = RequestMethod.GET)
public ModelAndView printHello() {
return new ModelAndView("hello", "command", new LoginPerson());
}
#RequestMapping(value = "/",method = RequestMethod.POST)
public String login(#ModelAttribute("SpringWeb")LoginPerson person, ModelMap model, HttpServletRequest request) {
model.addAttribute("info", personDAO.getInfromStudent(person.getEmail(), person.getPassword()));
model.addAttribute("takenbook", person.getEmail());
if (person.getEmail().equals("admin#admin.com") && person.getPassword().equals("admin")) {
logger.warning("AAAAA");
logger.warning(person.getEmail());
return "admin";
} else if(personDAO.checkPerson(person.getEmail(), person.getPassword()) == true){
logger.warning(personDAO.checkPerson(person.getEmail(), person.getPassword()).toString());
logger.warning("BBBBB");
logger.warning(person.getPassword());
return "personinfo";
} else {
return new ResponseStatusException().error();
}
}
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public ModelAndView registration() {
return new ModelAndView("registration", "person", new Person());
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String register(#ModelAttribute("person") Person person) {
logger.warning("Hello");
logger.warning(person.toString());
personDAO.connectPerson(person);
return "redirect:/registerbook";
}
#RequestMapping(value = "/registerbook", method = RequestMethod.GET)
public ModelAndView registerbook() {
//model.addAttribute("newborrow", new Borrows());
return new ModelAndView("registerbook", "newborrow", new Borrows());
}
#RequestMapping(value = "/registerbook", method = RequestMethod.POST)
public String regbook(#ModelAttribute("newborrow") Borrows borrows, ModelMap model) {
logger.warning(String.valueOf(borrows.getId()));
model.addAttribute("borrowid", borrows.getId());
model.addAttribute("personid", borrows.getStudentid());
model.addAttribute("bookid", borrows.getBookid());
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Timestamp todays30 = Timestamp.valueOf(dateFormat.format(today30));
Timestamp todayy = Timestamp.valueOf(dateFormat.format(today));
borrows.setTakendate(todayy);
borrows.setBroughtdate(todays30);
borrowsDAO.insertBorrow(borrows);
return "hello";
}
#RequestMapping(value = "/addauth", method = RequestMethod.GET)
public ModelAndView addauth() {
return new ModelAndView("addauthbooks", "adding", new Authorz());
}
#RequestMapping(value = "/example", method = RequestMethod.POST)
public String addingauthor(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id_author", authorz.getAuthorid());
model.addAttribute("fname_author", authorz.getName());
model.addAttribute("lname_author", authorz.getSurname());
logger.warning(String.valueOf(authorz.getAuthorid()));
logger.warning(authorz.getName());
logger.warning(authorz.getSurname());
authorzDAO.insertAuthorz(authorz);
return "example";
}
#RequestMapping(value = "/addbooks", method = RequestMethod.GET)
public ModelAndView addbook() {
return new ModelAndView("addbook", "addingbook", new Books());
}
#RequestMapping(value = "/admin", method = RequestMethod.POST)
public String addingbook(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authorid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
model.addAttribute("fragment", books.getFragment());
logger.warning(String.valueOf(books.getId()));
logger.warning(books.getName());
logger.warning(String.valueOf(books.getPagecount()));
booksDAO.insertBook(books);
return "admin";
}
#RequestMapping(value = "/deleteauth", method = RequestMethod.GET)
public ModelAndView deleteauthbooks() {
return new ModelAndView("deleteauthbooks", "deletingauthor", new Authorz());
}
#RequestMapping(value = "/admins", method = RequestMethod.POST)
public String deleteresult(#ModelAttribute Authorz authorz, ModelMap model) {
model.addAttribute("id", authorz.getAuthorid());
model.addAttribute("name", authorz.getName());
model.addAttribute("surname", authorz.getSurname());
authorzDAO.delete_book(authorz.getSurname());
return "admin";
}
#RequestMapping(value = "/deletebooks", method = RequestMethod.GET)
public ModelAndView deletebook() {
return new ModelAndView("deletebooks", "deletingbook", new Books());
}
#RequestMapping(value = "/nadmin", method = RequestMethod.POST)
public String deletebookresult(#ModelAttribute Books books, ModelMap model) {
model.addAttribute("id", books.getId());
model.addAttribute("name", books.getName());
model.addAttribute("pagecount", books.getPagecount());
model.addAttribute("point", books.getPoint());
model.addAttribute("authid", books.getAuthorid());
model.addAttribute("typeid", books.getTypeid());
booksDAO.delete_book(books.getName());
return "admin";
}
#RequestMapping(value = "/borrow", method = RequestMethod.GET)
public ModelAndView borrows() {
return new ModelAndView("borrow", "borrowing", new LoginPerson());
}
#RequestMapping(value = "/res", method = RequestMethod.POST)
public String borrow(#ModelAttribute LoginPerson borrows, ModelMap model) {
logger.warning(borrows.getEmail());
List list_borrows = personDAO.searchStudent(borrows.getEmail());
logger.warning(list_borrows.toString());
model.addAttribute("borrow", list_borrows);
return "result";
}
#RequestMapping(value = "/changebook", method = RequestMethod.GET)
public ModelAndView change() {
return new ModelAndView("changebook", "changing", new Person());
}
#RequestMapping(value = "/changebook", method = RequestMethod.POST)
public String changebook(#ModelAttribute("changebook") Person point, ModelMap model, HttpServletRequest request) {
model.addAttribute("point", point.getPoint());
model.addAttribute("email", point.getEmail());
logger.warning("Upper");
logger.warning(String.valueOf(point.getPoint()));
logger.warning(point.getEmail());
logger.warning(request.getParameter("email"));
if(point.getPoint() != null && request.getParameter("email") != null) {
logger.warning("It works!!!");
personDAO.changeBook(point.getPoint(), request.getParameter("email"));
}
logger.warning("Down");
return "changebook";
}
}
This is my jsp of registration:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-05-19
Time: 17:48
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Registration</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center><h2>Person Information</h2></center>
<%--<form:form method = "post" action = "/springlab_war_exploded/admin" modelAttribute="person">--%>
<form:form method ="post" modelAttribute="person">
<fieldset>
<center>
<div id="legend">
<legend class="">Registration</legend>
</div>
</center>
<center>
<div class="control-group">
<!-- id -->
<label class="control-label" for="id">Id:</label>
<div class="controls">
<input type="number" id="id" name="id" placeholder="" class="input-xlarge">
<p class="help-block">Id can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<label class="control-label" for="name">First name:</label>
<div class="controls">
<input type="text" id="name" name="name" placeholder="" class="input-xlarge">
<p class="help-block">First name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<label class="control-label" for="surname">Last name:</label>
<div class="controls">
<input type="text" id="surname" name="surname" placeholder="" class="input-xlarge">
<p class="help-block">Last name can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- E-mail -->
<label class="control-label" for="email">Email:</label>
<div class="controls">
<input type="email" id="email" name="email" placeholder="" class="input-xlarge">
<p class="help-block">Please provide your Email</p>
</div>
</div>
<div class="control-group">
<!-- Password-->
<label class="control-label" for="pass">Password:</label>
<div class="controls">
<input type="password" id="pass" name="pass" placeholder="" class="input-xlarge">
<p class="help-block">Password should be at least 4 characters</p>
</div>
</div>
<div class="control-group">
<!-- Date -->
<label class="control-label" for="birthdate">Date:</label>
<div class="controls">
<input type="datetime" id="birthdate" name="birthdate" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your birthdate</p>
</div>
</div>
<div class="control-group">
<!-- Sex -->
<label class="control-label" for="gender">Sex:</label>
<div class="controls">
<input type="text" id="gender" name="gender" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your gender only M or F</p>
</div>
</div>
<div class="control-group">
<!-- Class -->
<label class="control-label" for="job">Job:</label>
<div class="controls">
<input type="text" id="job" name="job" placeholder="" class="input-xlarge">
<p class="help-block">Job can contain any letters or numbers, without spaces</p>
</div>
</div>
<div class="control-group">
<!-- Point -->
<label class="control-label" for="point">Point:</label>
<div class="controls">
<input type="number" id="point" name="point" placeholder="" class="input-xlarge">
<p class="help-block">Point can contain only numbers</p>
</div>
</div>
<div class="control-group">
<!-- Phone number -->
<label class="control-label" for="phonenumber">Phone number:</label>
<div class="controls">
<input type="tel" id="phonenumber" name="phonenumber" placeholder="" class="input-xlarge">
<p class="help-block">Please enter your phone number</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Next</button>
</div>
</div>
</center>
</fieldset>
</form:form>
</body>
</html>
And my jsp register book
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: lado
Date: 2019-06-02
Time: 12:51
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Register Book</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<%--<form:form class="form-horizontal" action='/springlab_war_exploded/login' method="post">--%>
<form:form class="form-horizontal" action="/springlab_war_exploded/login" method="post" modelAttribute="newborrow">
<fieldset>
<div id="legend">
<legend class="">Register Book</legend>
</div>
<div class="control-group">
<!-- id -->
<%--<label class="control-label" for="borrowid">Borrow Id:</label>--%>
<div class="controls">
<form:label path="id">Borrow Id:</form:label>
<form:input path="id"/>
<%--<input type="number" id="borrowid" name="borrowid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter borrow id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- name -->
<%--<label class="control-label" for="personid">Person Id:</label>--%>
<div class="controls">
<form:label path="studentid">Person Id:</form:label>
<form:input path="studentid"/>
<%--<input type="number" id="personid" name="personid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Eneter person id(it is your id)</p>
</div>
</div>
<div class="control-group">
<!-- surname -->
<%--<label class="control-label" for="bookid">Book Id:</label>--%>
<div class="controls">
<form:label path="bookid">Book Id:</form:label>
<form:input path="bookid"/>
<%--<input type="number" id="bookid" name="bookid" placeholder="" class="input-xlarge">--%>
<p class="help-block">Enter book id</p>
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success" name="submit" value="submit">Submit</button>
</div>
</div>
</fieldset>
</form:form>
</body>
</html>

Don't need "/" while redirecting or forwarding a request.
Can you try "redirect:registerbook";

Related

Spring MVC Login Form

I have created a simple login form that will redirect to the next page after submitting the form credentials. But it's not working fine.
here is my code:
Controller class:
#RequestMapping("/home")
public String showForm() {
return "home";
}
#RequestMapping(path = "/handleForm", method = RequestMethod.POST)
public String handleForm(HttpServletRequest request) {
String name = request.getParameter("username");
String pass = request.getParameter("password");
if (name != null && pass != null) {
if (name.equals("Twinkle") && pass.equals("twinkle123")) {
return "student-list";
} else {
return "home";
}
} else {
return "error";
}
}
home jsp file:
<div class="container mt-5">
<h3 class="text-center">Welcome, Login Here</h3>
<form action="handleForm" method="POST">
<div class="form-group">
<label for="username">User Name</label>
<input type="text" class="form-control"
id="username"
placeholder="Enter here"
name="username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" minlength="4"
maxlength="8" placeholder="Enter here" name="password">
</div>
<div class="container mt-5 text-center">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
</div>
How to fix it?

How to display different title depends on action?

I have got two methods that redirect to the same .html file.
First method is method responsible for saving, the second method is for updating.
It has got the same view so I just wanted to move user to the same view.
I have <h1>..</h1> in .html I would like to have title "New Mapping" for adding new mapping and "Update mapping" when we want to update mapping.
These are methods that do all the stuff (redirecting to the .html file)
#RequestMapping(path = "/.../update", method = RequestMethod.GET)
public String updatePage(#RequestParam("...") String ..., Model model) {
String[] tokens = ....split("_");
Template template= class.method(...);
model.addAttribute("template", template);
return "save";
}
#RequestMapping(path = "/.../save")
public String newMappingPage(Model model) {
Template template = new Template();
template.setCostIndex("10");
model.addAttribute("template", template);
return "save";
}
#RequestMapping(path = "/.../save", method = RequestMethod.POST)
public String saveMapping(#ModelAttribute Template template) {
class.method(template);
return "redirect:/main-page";
}
save.hml file
<html>
<head>
<title>Engine</title>
<link rel="stylesheet" th:href="#{/css/file.css}"/>
</head>
<body>
<h1>New/Update mapping</h1>
<form action="save" method="post" th:object="${template}">
<fieldset>
<label for="...">....[min]</label>
<input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
<label for="...">...</label>
<input type="number" id="...." th:field="*{...}" required="true"/>
<label for="...">....</label>
<input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
<br/>
<br/>
<label for="response">Response</label>
<br/>
<textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
<br/>
<input id="submit" type="submit" class="primary" value="Submit"/>
</fieldset>
</form>
</body>
</html>
You do not need to create two separate methods for add and update as you are storing data into DB from JSP page. use only one /save API.
#PostMapping(path = "/.../{}/save")
public String newMappingPage(Model model) {
Template template = new Template();
template.setCostIndex("10");
model = new Model();
if (model.getId() > 0) {
model = findById(model.getId());
model.addAttribute("heading", "Update Mapping");
} else {
model.addAttribute("heading", "New Mapping");
}
//Call method to store data from jsp file
return "save";
}
In JSP :
<html>
<head>
<title>Engine</title>
<link rel="stylesheet" th:href="#{/css/file.css}"/>
</head>
<body>
<h1>${heading}</h1>
<form action="save" method="post" th:object="${template}">
<fieldset>
<label for="...">....[min]</label>
<input type="number" id="..." th:field="*{...}" step="0.1" min="0"/>
<label for="...">...</label>
<input type="number" id="...." th:field="*{...}" required="true"/>
<label for="...">....</label>
<input type="text" id="..." th:field="*{...}" maxlength="1024" size="50"/>
<br/>
<br/>
<label for="response">Response</label>
<br/>
<textarea id="response" rows="20" cols="150" th:field="*{...}" required="true"/>
<br/>
<input id="submit" type="submit" class="primary" value="Submit"/>
</fieldset>
</form>
</body>
</html>
Update your method like this:
#PostMapping(path = "/.../{}/save")
public ModelAndView save(Model model) {
ModelAndView obj = new ModelAndView("save");
model = new Model();
if (model.getId() > 0) {
model = findById(model.getId());
obj .addAttribute("heading", "Update Mapping");
} else {
obj .addAttribute("heading", "New Mapping");
}
//Call method to store data from jsp file
return obj;
}

Why I am not able to insert and update?

<%#include file="../header.jsp" %>
<h1>Add Room</h1>
<form action="save" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Room Type</label>
<input type="text" name="roomType" placeholder="Enter Room Type" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Description</label>
<input type="text" name="roomDescription" placeholder="Enter Room Description" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Number</label>
<input type="number" name="roomNumber" placeholder="Enter Room Number" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="file" name="file" placeholder="Select Room Image" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="hidden" name="ro_id" value="${Room.ro_id}" placeholder="Select Room Image" required="required" class="form-control"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" value="submit">Save</button>
</div>
</form>
<%#include file="../footer.jsp" %>
Here is my edit jsp from where I update my database
Edit Room Jsp for updating for database using Room controller and I get
"Column Image"cannot be null
<%#include file="../header.jsp" %>
<h1>Edit Room</h1>
<form action="${SITE_URL}/admin/room/save" method="post" enctype="multipart/form-data">
<div class="form-group">
<label>Room Type</label>
<input type="text" name="roomType" value="${Room.room_type}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Description</label>
<input type="text" name="roomDescription" value="${Room.room_description}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Number</label>
<input type="number" name="roomNumber" value="${Room.room_number}" required="required" class="form-control"/>
</div>
<div class="form-group">
<label>Room Image</label>
<input type="file" name="file" link src="D:/Hotels/uploadedImage/${Room.image}" required="required" class="form-control" />
</div>
<form:hidden path="${Room.ro_id}" />
<input type="text" value="${Room.ro_id}" name="id"/>
<div class="form-group">
<button type="submit" class="btn btn-success" value="editroom/ro_id" >Save</button>
</div>
</form>
<%#include file="../footer.jsp" %>
When I try to update the page i get Column"image" cannot be null
and when I try to add it "Required int parameter #id is not present
/**
*
* #author
*/
#Controller
#RequestMapping(value = "/admin/room")
public class Roomcontroller {
#Autowired
private RoomService roomService;
#RequestMapping(method = RequestMethod.GET)
public String index(ModelMap map) throws SQLException {
map.addAttribute("Room", roomService.getAll());
return "admin/room/index";
}
#RequestMapping(value = "/addroom", method = RequestMethod.GET)
public String addRoom() throws SQLException {
return "admin/room/addroom";
}
#RequestMapping( value = "/editroom/{ro_id}", method = RequestMethod.GET )
public #ResponseBody ModelAndView edit(#PathVariable("ro_id") int ro_id) throws SQLException {
ModelAndView mv = new ModelAndView("admin/room/editroom");
mv.addObject("Room", roomService.getById(ro_id));
return mv;
}
#RequestMapping(value = "/deleteroom/{ro_id}", method = RequestMethod.GET)
public String delete(#PathVariable("ro_id") int ro_id) throws SQLException {
roomService.delete(ro_id);
return "redirect:/admin/room";
}
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestParam("roomType") String roomType,#RequestParam("id") int id,
#RequestParam("roomDescription") String roomDescription, #RequestParam("roomNumber") int roomNumber
,#RequestParam("file") MultipartFile multipartFile,HttpServletRequest req) throws SQLException, IOException {
Room attributes
Room room = new Room();
room.setRo_id(id);`
room.setRoom_type(roomType);
room.setRoom_description(roomDescription);
room.setRoom_number(roomNumber);
// TO DO : Save room, fetch the id of saved room and set it through
// setter in above object.
System.out.println(room.getRo_id());
if(room.getRo_id()==0){
System.out.println(room.getRo_id());
String serverRootPath = req.getServletContext().getRealPath("");
System.out.println(serverRootPath);
// You can change the directory.
File roomImageDirectory = new File("D:\\Hotels\\uploadedImages");
if (!roomImageDirectory.exists()) {
roomImageDirectory.mkdirs();
}
String[] fileNameToken = multipartFile.getOriginalFilename().split("\\.");
// You can change file name to be saved.
String newFileName = "room-" + room.getRoom_number() + "." + fileNameToken[fileNameToken.length - 1];
File roomImage = new File(roomImageDirectory, "/" + newFileName);
roomImage.createNewFile();
multipartFile.transferTo(roomImage);
room.setImage(newFileName);
roomService.insert(room);
}
else
{
roomService.update(room);
}
return "redirect:/admin/room";
}
}

Redirect to same tab on page upon Form submission - Spring MVC

I am using Spring MVC. I have a jsp page with multiple tabs. Each tab has a form. All these tabs are in a single jsp page called admin.jsp
I want to redirect the tab to itself upon POST to show errors or success message of transaction(Validation of input). What view should I return from the controller for each tab.
Controller:
#RequestMapping(value="/register", method = RequestMethod.POST)
public String registerDevice(#ModelAttribute("deviceMaster") #Validated DeviceMaster deviceMaster, BindingResult result, Model model, Locale locale) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/lock", method = RequestMethod.POST)
public #ResponseBody Status lockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request, #RequestParam #DateTimeFormat(pattern="yyyy-MM-dd") Date dueDate) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/unlock", method = RequestMethod.POST)
public #ResponseBody Status unlockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
admin.jsp
<div class="tabs" align="center">
<div class="list-center">
<ul class="tab-links">
<li class="active">Register</li>
<li>Lock</li>
<li>Unlock</li>
</ul>
</div>
<div class="tab-content">
<div id="tab1" class="tab active">
<div class="devices">
<form:form method="post" id="registerForm" modelAttribute="deviceMaster" action="/DeviceManager/admin/register">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" type="text" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Home Whse:</div>
<div class="plselect">
<form:select path="warehouseHome">
<form:option value="NONE" label="------- Select One -------"/>
<form:option value="TR" label="TRAINING"/>
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnRegister" class="abutton">Register</a></div>
<div class="plinput"><a id="btnCancel1" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab2" class="tab">
<div class="devices" >
<form:form method="post" id="lockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/lock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Reason Code:</div>
<div class="plselect">
<form:select path="reasonCodeForeignKey">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${reasonList}" itemValue="reasonCode" itemLabel="reasonDesc"/>
</form:select>
</div>
</div>
<div class="hidden" >
<div>
<div class="plLabelSearch">Away Whse:</div>
<div class="plselect">
<form:select path="awayWarehouse">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<div>
<div class="plLabelSearch">Due Date:</div>
<div class="plinput"><form:input id="datepicker" path="dueDate" placeholder="yyyy-mm-dd"/></div>
</div>
<div>
<div class="plLabelSearch">IT Ticket:</div>
<div class="plinput"><form:input path="itTicket" value="" size="29"/></div>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnLock" class="abutton">Lock</a></div>
<div class="plinput"><a id="btnCancel2" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab3" class="tab">
<div class="devices" >
<form:form method="post" id="unlockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/unlock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnUnlock" class="abutton">Unlock</a></div>
<div class="plinput"><a id="btnCancel3" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
Handled it using jQuery and kept selected tab active on refresh with Bootstrap 3
$(document).ready(function() {
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('.tab-links a[href="' + activeTab + '"]').tab('show');
}
$('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage.setItem('activeTab', currentAttrValue);
jQuery('.tabs ' + currentAttrValue).siblings().slideUp(400);
jQuery('.tabs ' + currentAttrValue).delay(400).slideDown(400);
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});

Spring MVC Not Displaying Form Errors

Here's my controller
#RequestMapping(value = "/save",method = RequestMethod.POST)
public ModelAndView saveUserAccount(#ModelAttribute("account") UserAccountForm userAccount, BindingResult result){
AddUserValidator userValidator = new AddUserValidator();
userValidator.validate(userAccount,result);
boolean hasErrors = result.hasErrors();
if(hasErrors){
return render(ADD_USER_VIEW)
.addAttr("ACCOUNT_ROLES", Arrays.asList(AccountRole.values()))
.addAttr("TENANTS",tenantInfoService.getAll())
.addAttr("errors",result)
.addAttr("account",userAccount).toMav();
}
return render(ADD_USER_VIEW)
.addAttr("ACCOUNT_ROLES", Arrays.asList(AccountRole.values()))
.addAttr("TENANTS",tenantInfoService.getAll())
.addAttr("account",new UserAccountForm())
.toMav();
}
Here's the render library That I have created.
public class RenderMavBuilder {
private final ModelAndView mav;
public static RenderMavBuilder render(String viewname){
RenderMavBuilder target = new RenderMavBuilder(viewname);
return target;
}
public RenderMavBuilder addAttr(String attrName, Object value){
mav.addObject(attrName, value);
return this;
}
public RenderMavBuilder addAttr(Object value){
mav.addObject(value);
return this;
}
public RenderMavBuilder addAttrs(Map<String , ?> attrs){
mav.addAllObjects(attrs);
return this;
}
private RenderMavBuilder(String viewName){
this.mav = new ModelAndView(viewName);
}
public ModelAndView toMav(){
return mav;
}
}
Here's my validator
Here's my form.
<div class="col-md-6 centered">
<form:errors path="*" />
<form:form commandName="account" method="post" action="${pageContext.request.contextPath}/user/save">
<!-- Username -->
<div class="col-xs-12 form-group">
<label class="control-label">Username</label>
<form:input path="username" type="text" class="form-control" />
</div>
<!-- Password -->
<div class="col-xs-12 form-group">
<label class="control-label">Password</label>
<form:password path="password" class="form-control"/>
</div>
<!-- Password -->
<div class="col-xs-12 form-group">
<label class="control-label">Password</label>
<form:password path="retypedPassword" class="form-control"/>
</div>
<!-- First Name -->
<div class="col-xs-12 form-group">
<label class="control-label">First Name</label>
<form:input path="firstName" type="text" class="form-control"/>
</div>
<!-- First Name -->
<div class="col-xs-12 form-group">
<label class="control-label">Last Name</label>
<form:input path="lastName" type="text" class="form-control"/>
</div>
<!-- User Role -->
<div class="col-xs-12 form-group">
<label class="control-label">User Role</label>
<form:select path="accountRole" class="form-control">
<form:options items="${ACCOUNT_ROLES}"/>
</form:select>
</div>
<!-- Branch Designation -->
<div class="col-xs-12 form-group">
<label class="control-label">Designated Branch</label>
<select path="tenantId" items="${TENANTS}" class="form-control">
<c:forEach var="branch" items="${TENANTS}">
<option value="${branch.id}">${branch.tenantDescription}</option>
</c:forEach>
</select>
</div>
<!-- Button -->
<div class="col-md-12 form-group">
<button class="form-control btn btn-primary submit-button" type="submit">Save New User <i class="fa fa-check-square-o"></i></button>
</div>
</form:form>
On my controler the binding result has errors. however, the error is not being displayed on the view, what am I missing?
The problem is the way you are constructing your ModelAndView, you should use the Errors object to construct it. Use Errors.getModel() to obtain the underlying Map that represents the model and use that, next to the view name, to construct the ModelAndView.
Next to that for your other model attributes you should simply add #ModelAttribute annotated methods to retrieve those. I would also suggest adding a GET based method which you redirect to after successful submit.
Your helper class seems also rather pointless as doing it simply inside your controller would simplify your code (imho).
Your controller could look something along these lines.
#RequestMapping(value = "/save",method = RequestMethod.POST)
public ModelAndView saveUserAccount(#ModelAttribute("account") UserAccountForm userAccount, BindingResult result){
AddUserValidator userValidator = new AddUserValidator();
userValidator.validate(userAccount,result);
boolean hasErrors = result.hasErrors();
return new ModelAndView(hasErrors ? ADD_USER_VIEW, "redirect:/add", errors.getModel());
}
#RequestMapping(value="/add")
public String addUserAccount(Model model) {
model.addObject("account", new UserAccountForm());
return ADD_USER_VIEW;
}
#ModelAttribute
public void referenceData(Model model) {
model.addObject("ACCOUNT_ROLES", Arrays.asList(AccountRole.values()));
model.addObject("TENANTS",tenantInfoService.getAll());
}

Categories