SOLUTION: I've changed the server from tomcat to jetty and the charset is back to normal
I'm having some trouble with the enconding on a application. Everytime I save something to the database the encoding breaks, but for reading is ok (I tested by changing manually on the db).
As Ralph asked I've checked if the charset is broke before I save on the database, and it's. So I'm changing the question to reflect better the problem.
I'm using Spring MVC, Hibernate and MySQL. I've configurated spring to use UTF-8 in my configuration class:
public class ServletSpringMVC extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { AppWebConfiguration.class, JPAConfiguration.class, SecurityConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {};
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter encodingFilter = new CharacterEncodingFilter();
encodingFilter.setEncoding("UTF-8");
encodingFilter.setForceEncoding(true);
return new Filter[] {encodingFilter};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement(""));
}
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addListener(RequestContextListener.class);
servletContext.setInitParameter("spring.profiles.active", "dev");
}
}
My JSP is:
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%# taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<tags:template title="Jobs">
<jsp:attribute name="bodyArea">
<div class="container">
<c:if test="${not empty jobId}">
<c:url var="urlAction" value="${spring:mvcUrl('JC#updateJob').arg(0,jobId).build()}"/>
</c:if>
<c:if test="${empty jobId}">
<c:url var="urlAction" value="${spring:mvcUrl('JC#addJob').build()}"/>
</c:if>
<form:form action="${urlAction}" method="post" modelAttribute="jobDTO" id="form" acceptCharset="utf-8">
<input type="hidden" name="board" value="${boardId}">
<div class="form-group">
<label> <spring:message code="job.form.client"/> </label>
<form:input path="client" cssClass="form-control"/>
<form:errors path="client"/>
</div>
<div class="form-group">
<label> <spring:message code="job.form.priority"/> </label>
<form:select path="priority" cssClass="form-control">
<form:option value="" label=""/>
<form:options items="${priorities}"/>
</form:select>
<form:errors path="priority"/>
</div>
<div class="form-group">
<label> <spring:message code="job.form.status"/> </label>
<form:select path="status" cssClass="form-control">
<form:option value="" label=""/>
<form:options items="${statuses}"/>
</form:select>
<form:errors path="status"/>
</div>
<div class="form-group">
<label> <spring:message code="job.form.responsible"/> </label>
<form:select path="responsible" cssClass="form-control">
<form:option value="" label=""/>
<form:options items="${boardHelper.getBoardUsers(boardId)}"/>
</form:select>
<form:errors path="responsible"/>
</div>
<div class="form-group">
<label> <spring:message code="job.form.description"/> </label>
<form:textarea path="description" cssClass="form-control" rows="5"/>
<form:errors path="description"/>
</div>
</form:form>
<div class="container">
<div class="row">
<div class="col-lg-1">
<button type="submit" class="btn btn-success" form="form">
<span class="glyphicon glyphicon-floppy-disk"></span>
<spring:message code="Save"/>
</button>
</div>
<c:if test="${not empty jobId}">
<div class="col-lg-1">
<form action="${spring:mvcUrl('JC#deleteJob').arg(0,jobId).build()}" method="post">
<button type="submit" class="btn btn-danger">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<span class="glyphicon glyphicon-trash"></span>
<spring:message code="Delete"/>
</button>
</form>
</div>
</c:if>
</div>
</div>
</div>
</jsp:attribute>
</tags:template>
Related
I'm trying to set boxes' elements copied from medicineBox's values like below. Can anyone help me in this. I need to post medicineOrder model to the controller
<tr th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
<input type="text" th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" th:value="${medicineBox.box.number}" />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
I'm using two object here -
medicine and medicineOrder
------------------> Controller method to get the page
#GetMapping("/{medicineId}")
public String loadMedicineDetailPage(#PathVariable("medicineId") long medicineId, Model model) {
model.addAttribute("medicine", service.getMedicineById(medicineId));
model.addAttribute("medicineOrder", new MedicineOrder());
return WebPages.MEDICINE_DETAIL.toString();
}
------------------> thymeleaf html page
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Spring Boot Application</title>
</head>
<body>
<div class="container">
<br/>
<a class="btn btn-primary" th:href="#{/mvc/medicine/list}">Back</a>
<br/>
<br/>
<h3 class="text-center alert alert-success">Medicine Details</h3>
<form class="row g-3" action="#" th:action="#{/mvc/medicine/sell}" method="post" th:object="${medicineOrder}">
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="name" class="form-label">Name</label>
<input type="text" style="background-color:#95edea" disabled class="form-control" id="name" th:field="${medicine.name}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="company" class="form-label">Company</label>
<input type="text" disabled class="form-control" id="company" th:field="${medicine.companyStringName}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="price" class="form-label">Price</label>
<input type="text" disabled class="form-control" id="price" th:field="${medicine.price}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="count" class="form-label">Count</label>
<input type="text" class="form-control" id="count" th:field="${medicine.count}"/>
</div>-->
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="volume" class="form-label">ML</label>
<input type="text" disabled class="form-control" id="volume" th:field="${medicine.volume}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="purchaseDate" class="form-label">Date Purchased</label>
<input type="text" disabled class="form-control" id="purchaseDate" th:field="${medicine.purchaseDate}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="boxNo" class="form-label">Box Number</label>
<input type="text" class="form-control" id="boxNo" th:field="${medicine.boxNumber}"/>
</div>-->
**<input type="hidden" th:field="*{medicineId}" th:value="${medicine.medicineId}"/>**
<table class="table table-bordered">
<tr class="table-primary">
<td>Box Number</td>
<td>Medicine Count</td>
<td>Sell Count</td>
</tr>
<tr th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
**<input type="text" th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" th:value="${medicineBox.box.number}"** />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
</table>
<button class="btn btn-primary" type="submit">Sell</button>
</form>
</div>
</body>
</html>
---------------> Controller method to handle the post request
#PostMapping("/sell")
public String sellMedicine(#ModelAttribute MedicineOrder medicineOrder, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
// error handling
}
service.sellMedicine(medicineOrder);
return "redirect:/mvc/medicine/list";
}
----------------> Class MedicineOrder
package com.example.demo.dto;
import com.example.demo.model.Box;
import java.util.ArrayList;
import java.util.List;
public class MedicineOrder {
private long medicineId;
private List<OrderedBox> boxes = new ArrayList<>();
public long getMedicineId() {
return medicineId;
}
public void setMedicineId(long medicineId) {
this.medicineId = medicineId;
}
public List<OrderedBox> getBoxes() {
return boxes;
}
public void setBoxes(List<OrderedBox> boxes) {
this.boxes = boxes;
}
#Override
public String toString() {
return "MedicineOrder{" +
"medicineId=" + medicineId +
", boxes=" + boxes +
'}';
}
}
package com.example.demo.dto;
public class OrderedBox {
private String boxNumber;
private int medicineCount;
public String getBoxNumber() {
return boxNumber;
}
public void setBoxNumber(String boxNumber) {
this.boxNumber = boxNumber;
}
public int getMedicineCount() {
return medicineCount;
}
public void setMedicineCount(int medicineCount) {
this.medicineCount = medicineCount;
}
#Override
public String toString() {
return "OrderedBox{" +
"boxNumber='" + boxNumber + '\'' +
", medicineCount=" + medicineCount +
'}';
}
}
Not able to get the MedicineOrder.medicineId and medicineBorder.boxes[*].boxNumber from template to model object.
After lot of searching I didn't find any answer which is solving the issue only using thymeleaf.
To solve this issue I had to add two hidden input field for medicineId and boxNumber on medicineOrder object and populate those input field using javascript as below. Anyway if anyone find the solution by only using thymeleaf, please let me know.
Populated those fields using javascript
<script>
function function__02__number__assignment(_element){
var __element = _element.children[0];
var __tElement1 = __element.children[0];
var __tElement2 = __element.children[1];
// Copy value from 2 to 1
__tElement1.value = __tElement2.value;
}
function function__01__box_traverse(){
var rootElement = document.getElementsByClassName('box-stock-details');
for(var __i=0 ; __i < rootElement.length ; __i++) {
function__02__number__assignment(rootElement[__i]);
}
function_01_01_medicineId();
return true;
}
function function_01_01_medicineId(){
var _00_1_id_src = document.getElementById('00-1-id-src');
var _00_1_id_dest = document.getElementById('00-1-id-dest');
_00_1_id_dest.value = _00_1_id_src.value;
}
</script>
updated template file
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Spring Boot Application</title>
</head>
<body>
<div class="container">
<br/>
<a class="btn btn-primary" th:href="#{/mvc/medicine/list}">Back</a>
<br/>
<br/>
<h3 class="text-center alert alert-success">Medicine Details</h3>
<form class="row g-3" action="#" th:action="#{/mvc/medicine/sell}" method="post" th:object="${medicineOrder}">
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="name" class="form-label">Name</label>
<input type="text" style="background-color:#95edea" disabled class="form-control" id="name" th:field="${medicine.name}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="company" class="form-label">Company</label>
<input type="text" disabled class="form-control" id="company" th:field="${medicine.companyStringName}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="price" class="form-label">Price</label>
<input type="text" disabled class="form-control" id="price" th:field="${medicine.price}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="count" class="form-label">Count</label>
<input type="text" class="form-control" id="count" th:field="${medicine.count}"/>
</div>-->
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="volume" class="form-label">ML</label>
<input type="text" disabled class="form-control" id="volume" th:field="${medicine.volume}"/>
</div>
<div class="col-md-6 col-xs-12 col-sm-12">
<label for="purchaseDate" class="form-label">Date Purchased</label>
<input type="text" disabled class="form-control" id="purchaseDate" th:field="${medicine.purchaseDate}"/>
</div>
<!--<div class="col-md-6 col-xs-12 col-sm-12">
<label for="boxNo" class="form-label">Box Number</label>
<input type="text" class="form-control" id="boxNo" th:field="${medicine.boxNumber}"/>
</div>-->
<!-- Hidden input to get the value of medicineId from Medicine object -->
<input id="00-1-id-src" type="hidden" th:value="${medicine.medicineId}"/>
<!-- Hidden input to set the medicineId on MedicineOrder object -->
<input id="00-1-id-dest" type="hidden" th:field="*{medicineId}" />
<table class="table table-bordered">
<tr class="table-primary">
<td>Box Number</td>
<td>Medicine Count</td>
<td>Sell Count</td>
</tr>
<tr class="box-stock-details" th:each="medicineBox : ${medicine.medicineBoxes}">
<td class="text-center">
<input hidden th:field="*{boxes[__${medicineBoxStat.index}__].boxNumber}" />
<input disabled class="form-control" type="text" th:value="${medicineBox.box.number}" />
</td>
<td class="text-center" th:text="${medicineBox.medicineCount}"></td>
<td><input type="number" th:field="*{boxes[__${medicineBoxStat.index}__].medicineCount}" class="form-control" /></td>
</tr>
</table>
<button class="btn btn-primary" type="submit" onclick="return function__01__box_traverse()">Sell</button>
</form>
</div>
</body>
<script>
function function__02__number__assignment(_element){
var __element = _element.children[0];
var __tElement1 = __element.children[0];
var __tElement2 = __element.children[1];
// Copy value from 2 to 1
__tElement1.value = __tElement2.value;
}
function function__01__box_traverse(){
var rootElement = document.getElementsByClassName('box-stock-details');
for(var __i=0 ; __i < rootElement.length ; __i++) {
function__02__number__assignment(rootElement[__i]);
}
function_01_01_medicineId();
return true;
}
function function_01_01_medicineId(){
var _00_1_id_src = document.getElementById('00-1-id-src');
var _00_1_id_dest = document.getElementById('00-1-id-dest');
_00_1_id_dest.value = _00_1_id_src.value;
}
</script>
</html>
The main functioning of my project to give privileges to the user to modify the event he want to.
so first page is modify-event.jsp where he will get the list of events present in the system with modify button at the end column
modify-event.jsp
<%#page import="java.util.ArrayList"%>
<jsp:include page="includes/header.jsp" />
<div>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%
HttpSession session1 = request.getSession();
//String id = request.getParameter("userId");
String driverName = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String dbName = "technovision";
String userId = "root";
String password = "root";
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<h2 align="center"><font><strong>Retrieve data from database in jsp</strong></font></h2>
<table align="center" cellpadding="5" cellspacing="5" border="1">
<tr>
</tr>
<tr bgcolor="#A52A2A">
<td><b>Event name</b></td>
<td><b>Registration Amount</b></td>
<td><b>EventHead name</b></td>
<td><b>EventHead contact</b></td>
<td><b>Event Description</b></td>
<td><b>Action</b></td>
</tr>
<%
try{
connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);
statement=connection.createStatement();
String sql ="SELECT * FROM events";
resultSet = statement.executeQuery(sql);
while(resultSet.next()){
session1.setAttribute("eventid",resultSet.getString(1));
session1.setAttribute("eventname",resultSet.getString(2));
session1.setAttribute("registrationamount",resultSet.getString(3));
session1.setAttribute("eventheadname",resultSet.getString(4));
session1.setAttribute("eventheadcontact",resultSet.getString(5));
session1.setAttribute("eventdescription",resultSet.getString(6));
//ArrayList a = new ArrayList();
//a.add(resultSet.getString(1));
//a.add(resultSet.getString(2));
//a.add(resultSet.getString(3));
//a.add(resultSet.getString(4));
//a.add(resultSet.getString(5));
//a.add(resultSet.getString(6));
%>
<tr bgcolor="#DEB887">
<td><%=resultSet.getString("event_name") %></td>
<td><%=resultSet.getString("registration_amount") %></td>
<td><%=resultSet.getString("eventhead_name") %></td>
<td><%=resultSet.getString("eventhead_contact") %></td>
<td><%=resultSet.getString("event_description") %></td>
<td>Modify</td>
</tr>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</div>
<%# include file="includes/footer.jsp" %>
<%#include file="includes/scripts.jsp" %>
</body>
</html>
Now when user clicks on any of the modify button he should redirect to the page which will fetch the clicked event details so that he can edit the same, but the case here is its opening the last data from that table above in modify-event.jsp because i made use of httpsession but i guess in the wrong way.
so when user clicks on modify button i redirected him to page name modify-page.jsp
modify-page.jsp
<%#page import="java.util.ArrayList"%>
<jsp:include page="includes/header.jsp" />
<%--<%# page import="com.event"%>--%>
<style>
input.eventdescription{
padding-top : 20px;
padding-bottom : 100px;
}
</style>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.*"%>
<%#page import="java.sql.Connection"%>
<%
// ArrayList[] eventname = new ArrayList[10];
// ArrayList[] registrationamount = new ArrayList[10];
// ArrayList[] eventheadname = new ArrayList[10];
// ArrayList[] eventheadcontact = new ArrayList[10];
// ArrayList[] eventdescription = new ArrayList[10];
// ArrayList[] eventid = new ArrayList[10];
//
//HttpSession session1 = request.getSession();
// eventname = (ArrayList[])session1.getAttribute("eventname");
// registrationamount = (ArrayList[])session1.getAttribute("registrationamount");
// eventheadname = (ArrayList[])session1.getAttribute("eventheadname");
// eventheadcontact = (ArrayList[])session1.getAttribute("eventheadcontact");
// eventdescription = (ArrayList[])session1.getAttribute("eventdescription");
// eventid = (ArrayList[])session1.getAttribute("eventid");
%>
<div class="addevent-content" style="background-color:black">
<div class="pattern height-resize">
<div class="container">
<form class="form-horizontal" action="UpdateEvent" method="post"
id="addevent_form" >
<!-- Form Name -->
<center>
<h2 id="registerheading">
<b style="color: gold">Modify Event</b>
</h2>
</center>
<br>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Event
Name<abbr title="Required">*</abbr>
</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="event_name" id="form_fname" placeholder="Event Name"
value='${eventname}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Registration Amount<abbr title="Required">*</abbr>
</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="registration_amount" id="form_lname" placeholder="Registration Amount"
value='${registrationamount}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Event Image<abbr
title="Required">*</abbr></label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="event_image" placeholder="Event Image" class="form-control"
value='' type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">EventHead Name<abbr
title="Required">*</abbr></label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="eventhead_name" id="password1" placeholder="EventHead Name"
value='${eventheadname}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">EventHead Contact
<abbr title="Required">*</abbr>
</label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="eventhead_contact" id="password2" placeholder="(+91)"
value='${eventheadcontact}' class="form-control" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-5 control-label" style="color: #fff">Event Description<abbr
title="Required">*</abbr></label>
<div class="col-md-5 inputGroupContainer">
<div class="input-group">
<input name="event_description" id="email" placeholder=""
value='${eventdescription}' class="form-control eventdescription" type="text" required>
</div>
</div>
</div>
<!-- Select Basic -->
<input name="event_id"class="form-control"
value='${eventid}' type="hidden" >
<!-- Button -->
<div class="form-group">
<label class="col-md-5 control-label"></label>
<div class="col-md-5">
<br>
<button type="submit" class="btn btn-warning">SUBMIT</button>
</div>
</div>
</form>
</div>
<!-- /.container -->
</div>
<!-- pattern height resize-->
</div>
<%# include file="includes/footer.jsp" %>
<%#include file="includes/scripts.jsp" %>
</body>
</html>
So is there any way that when user clicks on modify button and it should retrieve that particular event details in modify-page.jsp from the database for modification and then user can click on submit to update the database .
below is the structure of the database table "Events"
Database structure
send unique id with url ,
Modify
Then get id in modify-page request.getParameter("id")
connect db again with PreparedStatement
using SELECT * FROM Events WHERE eventid= ? sql statement.
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();
});
});
I am trying to insert data's into database using Spring,Hibernate and MySql. I am getting the following error while inserting data into database
"Neither BindingResult nor plain target object for bean name 'owner' available as request attribute". I tried all possible solutions available but couldn't clear it.
This is my controller
#Controller
public class DataOwnerRegController {
#Autowired(required = true)
DataService dataService;
#RequestMapping(value="/DataOwnerReg",method = RequestMethod.POST)
public String getForm(#ModelAttribute("owner") Model model )
{
model.addAttribute("owner", new Owner());
return "DataOwnerReg";
}
#RequestMapping(value = "/DataOwnerReg")
public ModelAndView registeruser(#ModelAttribute("owner") Owner owner, BindingResult result){
ModelAndView modelAndView = new ModelAndView("DataOwnerReg");
dataService.insertRow(owner);
return modelAndView;
}
}
My View
<%# 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 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>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DATA OWNER REGISTRATION</title>
<link href="<c:url value="/resources/theme/css/bootstrap.css"/>" rel="stylesheet" >
<link href="<c:url value="/resources/theme/css/style.css"/>" rel="stylesheet">
<script src="<c:url value="/resources/theme/js/jquery-2.1.4.min.js"/>"> </script>
<script src="<c:url value="/resources/theme/js/bootstrap.mi.js"/>"></script>
<link href='https://fonts.googleapis.com/css?family=Raleway:300' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Bangers' rel='stylesheet' type='text/css'>
</head>
<body class="body-image">
<div>
<nav style="background-color:transparent;border:none" class="navbar navbar-default">
<div class="container">
<ul class="nav navbar-nav">
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/"/>">HOME</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">DATAOWNER</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">DATA CENTER</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">KEY DISTRIBUTION</a></li>
<li><a style="font-family: Raleway,sans-serif;color:white;font-size:15px;font-weight:600" href="<c:url value="/DataOwner"/>">ADMINISTRATOR</a> </li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="border">
<form:form modelAttribute="owner" method="Post" action="/DataOwnerReg">
<h3 style="text-align:center">Data Owner Registration</h3>
<h2 style="text-align:center">${message}</h2>
<hr style="width:25%"/>
<div class="formation">
<h4>Username:</h4>
<div class="input-group">
<form:input type="text" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="Enter the Username" required="" path="Username" /><div class="input-group-addon"><span class="glyphicon glyphicon-user" aria-hidden="true"></span></div>
</div>
<h4>Password:</h4>
<div class="input-group">
<form:input type="password" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="Enter the Password" required="" path="Password"/><div class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></div>
</div>
<h4>Confirm Password:</h4>
<div class="input-group">
<form:input type="password" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="Repeat Password" required="" path="CPassword" /><div class="input-group-addon"><span class="glyphicon glyphicon-lock" aria-hidden="true"></span></div>
</div>
<h4>Email Address:</h4>
<div class="input-group">
<form:input type="email" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="me#example.com" required="" path="Email" /><div class="input-group-addon"><span class="glyphicon glyphicon-envelope" aria-hidden="true"></span></div>
</div>
<h4>Mobile Number:</h4>
<div class="input-group">
<form:input type="text" class="form-control" style="font-family:Raleway,sans-serif;height:40px" placeholder="10 Digit Mobile Number" required="" path="Email" /><div class="input-group-addon"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></div>
</div>
<div>
<input type="submit" style="width:150px;height:45px;margin-top:30px;font-family:Raleway,sans-serif" class="btn btn-success" value="Register"/>
</div>
<br/>
</div>
</form:form>
</div>
</div>
</body>
</html>
Please Help in this.
Thanks in advance
There are a couple things wrong with your controller
First you have the #ModelAttribute on a method argument of the type Model which you shouldn't do. Next the method you expect to be invoked on a GET request is going to be invoked on a POST request so basically there will be no model. Finally in your method that should handle the POST request you are returning a ModelAndView but with an empty model, so at that point there is no model anymore and no Owner object.).
I would suggest to fix your controller in the following way
#Controller
#RequestMapping("/DataOwnerReg")
public class DataOwnerRegController {
private final DataService dataService;
#Autowired
public DataOwnerRegController(DataService DataService) {
this.dataService=dataService;
}
#ModelAttribute
public Owner owner() {
return new Owner();
}
#RequestMapping(method = RequestMethod.GET)
public String get() {
return "DataOwnerReg";
}
#RequestMapping(method = RequestMethod.POST)
public String registeruser(#ModelAttribute("owner") Owner owner, BindingResult result){
dataService.insertRow(owner);
return "DataOwnerReg";
}
}
I have a form with two ModelAttributes one is citizens and the other is punishment. The two objects are separated by jquery tabs. I am having problems in getting the items on the form to display properly some are being displayed and some are not. I mean the html elements.
I am not sure how the Controller would look when there is multiple ModleAttributes on the page. Under is a sample of the code:
Page
<title>Citizen Registration</title>
</head>
<body>
<div id="tabs">
<ul>
<li>Citizen Registration</li>
<li>Punishment</li>
</ul>
<div id="tab1">
<form:form id="citizenRegistration" name ="citizenRegistration" method="post" modelAttribute="citizens" action="citizen_registration.htm">
<div id="divRight" class="mainDiv">
<div class="divGroup" id="divCharInfo">
<fieldset>
<legend>Characteristics Info</legend>
<ol>
<li><form:label for="photo" path="photo">Select Photo</form:label>
<form:input path="photo" type="file" id="photo" title="Upload a photo"/><form:errors path="photo" id="errors"/></li>
<li>
<label>Select Gender</label>
<form:select path="genderId" id="genderId" title="Select Your Gender">
<form:options items = "${gender.genderList}" itemValue="genderId" itemLabel="genderDesc" />
</form:select>
<form:errors path="genderId" class="errors"/>
</li>
<li><form:label for="weight" path="weight">Enter Weight <i>(lbs)</i></form:label>
<form:input path="weight" id="weight" title="Enter Weight"/><form:errors path="weight" id="errors"/>
</li>
<li><form:label for="height" path="height">Enter Height <i>(feet)</i></form:label>
<form:input path="height" id="height" title="Enter Height"/><form:errors path="height" id="errors"/>
</li>
.......................
<div id="tab2">
<form:form id="punishmentRegistration" name ="punishmentRegistration" method="post" modelAttribute="punishment" action="punishment_registration.htm">
<ol>
<li>
<form:label for ="punishmentId" path="punishmentId">Punishment Number</form:label>
<form:input path="punishmentId" id="punishmentId"/><form:errors path="punishmentId" id="errors"/>
</li>
<li>
<form:label for="crimeRecNo" path="crimeRecNo">Select Crime</form:label>
<form:select path="crimeRecNo" id="CrimeRecNo" title="Select Crime">
<form:options items = "${crime.crimeList}" itemValue="crimeRecNo" itemLabel="crimeRecNo" title="crimeDesc"/>
</form:select>
<form:errors path="crimeRecNo" id="errors"/>
</li>
<li>
<form:label for ="monitoringStDate" path="monitoringStDate"> Start Date </form:label>
<form:input path="monitoringStDate" id="monitoringStDate"/><form:errors path="monitoringStDate" id="errors"/>
</li>
<li>
<form:label for ="monitoringEnDate" path="monitoringEnDate"> End Date </form:label>
<form:input path="monitoringEnDate" id="monitoringEnDate"/><form:errors path="monitoringEnDate" id="errors"/>
</li>
</ol>
</form:form>
</div>
</div>
</body>
</html>
Controller
#RequestMapping(value="citizen_registration.htm", method = RequestMethod.GET)
public ModelAndView loadPage(HttpServletRequest request,
HttpServletResponse response,
#ModelAttribute Citizens citizens, #ModelAttribute Punishment punishment,
BindingResult result,
ModelMap m, Model model) throws Exception {
//code here
return new ModelAndView("citizen_registration");
This is my code however when i run it nothing in tab2 is displayed andnot all elements in tab1 is shown.
I don't think so if you can bind multiple models using the Spring form. In fact you should take a look in the spring binding form.
http://static.springsource.org/spring/docs/1.1.5/taglib/tag/BindTag.html
Take a look in the sample code. I have not tested the code. Let know in case of any issues.
Model
public class User{
private String username;
private String password;
..Setter and Getters
}
public class UserProfile{
private String firstName;
private String lastName;
setter and getter
}
Controller
#Controller
public class MyController{
#RequestMapping(....)
public String newAccountForm(ModelMap map){
User user = new User(); //Would recommend using spring container to create objects
UserProfile profile = new UserProfile();
map.addAttribute('user', user);
map.addAttribute('profile', profile);
return "form"
}
#RequestMapping(....)
public String newAccountForm(#ModelAttrbite('User')User user, BindingResult resultUser, #ModelAttribute('UserProfile')UserProfile userProfile, BindingResult resultProfile){
//Check the binding result for each model. If not valid return the form page again
//Further processing as required.
}
}
JSP
<%#taglib uri="http://www.springframework.org/tags" prefix="spring">
<form action="" method="post">
<spring:bind path="user.username">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="user.password">
<input type="password" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="profile.firstName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<spring:bind path="profile.lastName">
<input type="text" name="${status.expression}" value="${status.value}"><br />
</spring:bind>
<input type="submit" value="Create"/>
</form>
I already gave alternate approach in this link here
<form:form method="POST" modelAttribute="applicationGeneralInformation">
<div class="section2">
<h2>General Informaion</h2>
<form:input type="hidden" path="id" id="id"/>
<label for="app_version">Version</label>: <form:input type="text" id="app_version" path="version"/><br/>
<label for="app_func_desc">Description</label>: <form:input type="text" id="app_func_desc"
path="functionalDescription"/><br/>
<label for="app_sec_func">Functions</label>: <form:input type="text" id="app_sec_func"
path="securityFunctions"/><br/>
</div>
<div class="section2">
<h2>Application Content</h2>
<form:form method="POST" modelAttribute="applicationContent">
<div>
<h3>CIA Rating</h3>
<label for="CIARating">CIA Rating</label>: <form:select type="text" id="CIARating" path="CIARating">
<form:option value="1">1</form:option>
<form:option value="2">2</form:option>
<form:option value="3">3</form:option>
<form:option value="4">4</form:option>
</form:select><br/><br/>
</div>
<div>
<h3>Business Continuity and Disaster Recovery</h3>
<div>
<h4>RTO</h4>
<label for="RTO">RTO</label>: <form:select type="text" id="RTO" path="RTO">
<form:option value="1">< 2<sub>Hrs</sub></form:option>
<form:option value="2">2<sub>Hrs</sub>-4<sub>Hrs</sub> </form:option>
<form:option value="3">4<sub>Hrs</sub>-48<sub>Hrs</sub></form:option>
<form:option value="4">> 48<sub>Hrs</sub></form:option>
</form:select><br/>
</div>
<div>
<h4>RPO</h4>
<label for="RPO">RPO</label>: <form:input type="text" id="RPO" path="RPO"/><br/>
</div>
</div>
</form:form>
<input type="submit" value="Submit">
</div>
</form:form>
<script type="text/javascript">
$(document).ready(
function() {
$("#userAttendance").submit(
function(e) {
e.preventDefault();
jQuery.ajaxSetup({
async : false
});
var a = "${pageContext.request.contextPath}";
alert(a);
$.post($(this).attr("action"), $(this).serialize(),
function(response) {
$("#showTableByDate").html(response);
jQuery.ajaxSetup({
async : true
});
});
});
//Date picker
$('#datepicker').datepicker({
autoclose : true
});
});