org.springframework.web.util.NestedServletException Netbeans - spring

I am using Spring Framework to develop a web app.
The problem is when i tried to add an article in my database It shows a NestedServlet exception. Can any one help me ?
This is my controler class :
#Controller
public class Controler {
ArticleFacadeLocal articleModel;
CategorieFacadeLocal categorieModel;
ConnexionFacadeLocal connexionModel;
public Controler(){
articleModel = new ArticleModel();
categorieModel = new CategorieModel();
connexionModel = new ConnexionModel();
}
#RequestMapping("/home.do")
public String home(HttpServletRequest request){
if(isConnected(request))
return addPage(request);
else return "page:login";
}
#RequestMapping("login.do")
public String login(HttpServletRequest request){
String login=request.getParameter("login");
String password=request.getParameter("password");
if(ConnexionModel.connect(login, password)){
request.getSession().setAttribute("login",login);
ServletContext application=request.getServletContext();
application.setAttribute("categories", categorieModel.findAll());
return addPage(request);}
else
request.setAttribute("error",true);
return "forward:/home.do";
}
#RequestMapping("logout.do")
public String logout(HttpServletRequest request) {
request.getSession(false).invalidate();
return "forward:/home.do";
}
#RequestMapping("articles.do")
public String list(HttpServletRequest request){
request.setAttribute("articles",articleModel.findAll());
return "page:articles";
}
#RequestMapping("addPage.do")
public String addPage(HttpServletRequest request){
request.setAttribute("categories", categorieModel.findAll());
return "page:add";
}
#RequestMapping("add.do")
public String add(HttpServletRequest request){
try{
Article a=getArticleFromView(request);
articleModel.create(a);
request.setAttribute("error", false);
}catch(Exception e){request.setAttribute("error", true);}
return "forward:/addPage.do";
}
#RequestMapping("modifyPage.do")
public String modiyPage(HttpServletRequest request){
int idArticle=Integer.parseInt(request.getParameter("idArticle"));
request.setAttribute("categories", categorieModel.findAll());
Article article = articleModel.find(idArticle);
request.setAttribute("article", article);
return "page:modify";
}
#RequestMapping("modify.do")
public String modify(HttpServletRequest request){
try{
Article a=getArticleFromView(request);
articleModel.edit(a);
return "forward:/articles.do";
}catch(Exception e){
request.setAttribute("error", true);
return "forward:/modifyPage.do";
}
}
#RequestMapping("searchPage.do")
public String searchPage(HttpServletRequest request){
return "page:search";
}
#RequestMapping("search.do")
public String search(HttpServletRequest request){
String libelle=request.getParameter("libelle");
request.setAttribute("article",articleModel.find(libelle));
return "page:search";
}
public boolean isConnected(HttpServletRequest request){
HttpSession session = request.getSession(false);//recupere une session sans la creer
return (session!=null && session.getAttribute("login")!=null);
}
public Article getArticleFromView(HttpServletRequest request){
Article a = new Article();
String libelle = request.getParameter("libelle");
String description = request.getParameter("description");
String prix = request.getParameter("prix");
String qte = request.getParameter("qte");
String categorie = request.getParameter("categorie");
a.setLibelle(libelle);
a.setDescription(description);
a.setPrix(Double.parseDouble(prix));
a.setQte(Integer.parseInt(qte));
a.setCategorie(new Categorie(categorie));
return a;
}
}
And this is my jsp file
<%#include file="include.jsp" %>
<form action="add.do" method="post">
<table align="center">
<tr >
<td>Libelle :
<td><input type="text" required="required" name="libelle"/>
</tr>
<tr >
<td>Description :
<td><input type="text" required="required" name="description">
</tr>
<tr>
<td>Prix :
<td><input type="text" required="required" name="prix">
</tr>
<tr>
<td>Quantité :
<td><input type="text" required="required" name="qte">
</tr>
<tr >
<td> Catégorie :
<td>
<select name="categorie" >
<c:forEach items="${categories}" var="c">
<option value="${c.idCategorie}"> ${c.libelleCategorie} </option>
</c:forEach>
</select>
</tr>
<tr align="center" >
<td colspan="2"><button type="submit" id="btn">Ajouter</button></td>
</tr>
</table>
</form>
<c:if test="${not empty error && error}"> <p style="color: red;"> Echec d'ajout de l'article </p></c:if>
<c:if test="${not empty error && not error}"> <p style="color: green;">Article ajouté avec succes </p></c:if>
This is error exception :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.AssertionFailure: null id in model.beans.Article entry (don't flush the Session after an exception occurs)
cause première
org.hibernate.AssertionFailure: null id in model.beans.Article entry (don't flush the Session after an exception occurs)
I am not using Maven.

Related

ASP.NET Routes config not following tutorial

I'm trying to follow a basic tutorial to get forms working:
https://www.completecsharptutorial.com/asp-net-mvc5/4-ways-to-create-form-in-asp-net-mvc.php
After running the first example my code trying to render localhost:5001/form1 instead of the example's localhost:5001/Home/form1
I'm assuming the issue is my Starup.cs routes needs to be tweaked. It currently looks like:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Controller code:
namespace test_ops.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location =
ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId =
Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
[HttpPost]
public ActionResult form1(int txtId, string txtName, string chkAddon)
{
ViewBag.Id = txtId;
ViewBag.Name = txtName;
if (chkAddon != null)
ViewBag.Addon = "Selected";
else
ViewBag.Addon = "Not Selected";
return View("Index");
}
}
}
Model code:
namespace test_ops.Models
{
public class TestModel
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Addon { get; set; }
}
}
View code in Home/index.cshtml:
<h4 style="color:purple">
<b>ID:</b> #ViewBag.ID <br />
<b>Name:</b> #ViewBag.Name <br />
<b>Addon:</b> #ViewBag.Addon
</h4>
<hr />
<h3><b>Forms: Weakly Typed</b></h3>
<form action="form1" method="post">
<table>
<tr>
<td>Enter ID: </td>
<td><input type="text" name="txtId" /></td>
</tr>
<tr>
<td>Enter Name: </td>
<td><input type="text" name="txtName" /></td>
</tr>
<tr>
<td>Addon: </td>
<td><input type="checkbox" name="chkAddon" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
</table>
</form>
After submitting the form the page comes back with the a 404:
"This localhost page can’t be foundNo webpage was found for the web address: https://localhost:5001/form1
HTTP ERROR 404"
Can someone please let me know what needs to be changed to get this working?
try to add controller to your form
<form action="#Url.Action("form1", "home")" method="post">
...
but is much better to use this syntax instead of form
#using (Html.BeginForm("form1", "Home", FormMethod.Post))
{
<table>
<tr>
//...
<tr>
<td colspan="2"><input type="submit" value="Submit Form" /></td>
</tr>
}
and check a file _ViewImports.cshtml in a View folder. It should have
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

How to upload,display,download and delete files using spring mvc

Hi am trying to do operations like uploading a file,displaying a file,downloading a file and deleting a file using spring mvc i got success in uploading file and deleting file all operations working fine but then whats happening is when i do uploading the uploaded file or image displaying or downloading twice and getting
java.lang.IllegalStateException: getOutputStream() has already been called for this response
<form method="post" action="doUpload" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Pick file #1:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td>Pick file #2:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
<table border="1" bgcolor="black" width="600px">
<tr style="background-color: teal; color: white; text-align: center;"
height="40px">
<td>File Name</td>
<td>Image</td>
<td>Download</td>
<td>Delete</td>
</tr>
<c:forEach items="${employeeList}" var="user">
<tr style="background-color: white; color: black; text-align: center;"
height="30px">
<td><c:out value="${user.fileName}" /></td>
<td><img src="show?id=${user.id}" /></td>
<td>Download</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
#Controller
#RequestMapping("/")
public class RegistrationController {
#Autowired
private IRegistrationService registerService;
#RequestMapping(value = "/saveParentAndStudentFromAdmin", method = RequestMethod.POST)
public ModelAndView saveParentAndStudentByAdmin(
#ModelAttribute Student student,
#RequestParam CommonsMultipartFile[] fileUpload) {
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload) {
System.out.println("Saving file: "
+ aFile.getOriginalFilename());
student.setFileName(aFile.getOriginalFilename());
student.setFileType(aFile.getContentType());
student.setData(aFile.getBytes());
registerService.saveParentAndStudentByAdmin(student);
}
}
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
#RequestMapping("delete")
public ModelAndView deleteUser(#RequestParam int id) {
registerService.deleteRow(id);
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
#RequestMapping("show")
public ModelAndView displayImage(#RequestParam int id,
HttpServletResponse response, HttpServletRequest request) {
System.out.println("Id to display image: " + id);
Student item = registerService.get(id);
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
try {
response.getOutputStream().write(item.getData());
} catch (IOException e) {
e.printStackTrace();
}
try {
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
return new ModelAndView("StudentEnrollmentFromAdmin");
}
#RequestMapping("downalod")
public ModelAndView downloadFile(#RequestParam int id,
HttpServletResponse response, HttpServletRequest request) {
System.out.println("Id to download: " + id);
Student student = registerService.get(id);
response.setContentType(student.getFileType());
response.setContentLength(student.getData().length);
response.setHeader("Content-Disposition", "attachment; filename=\""
+ student.getFileName() + "\"");
try {
FileCopyUtils.copy(student.getData(), response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
java.util.List<Student> uploadedFiles = registerService.findAllFiles();
return new ModelAndView("StudentEnrollmentFromAdmin", "employeeList",
uploadedFiles);
}
}
If I correctly understood your question you may do something like this:
public ResponseEntity<InputStreamResource> getFile(#PathVariable("idForm") String idForm)
{
try
{
Student item = registerService.get(id);
HttpHeaders respHeaders = new HttpHeaders();
//Change it with your real content type
MediaType mediaType = new MediaType("img","jpg");
respHeaders.setContentType(mediaType);
respHeaders.setContentLength(file.length());
//I suppose you have a method "getFileName"
//By using attachment you download the file; by using inline you should see the image in the browser
respHeaders.setContentDispositionFormData("attachment", item.getFileName());
InputStreamResource isr = new InputStreamResource(new ByteArrayOutputStream(item.getData()));
return new ResponseEntity<InputStreamResource>(isr, respHeaders, HttpStatus.OK);
}
catch (Exception e)
{
String message = "Error; "+e.getMessage();
logger.error(message, e);
return new ResponseEntity<InputStreamResource>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Angelo

AJAX Call, it returns NOT Acceptable using SPRING MVC Hibernate

I'm using Spring MVC Hibernate, I'm retrieving districts and blocks from the database. District is successfully displayed but when it comes to Blocks i'm not able to display them, what can be the problem?? please help
$(document).ready(function()
{
$('#districtcode').change(function()
{
$.ajax({
type: "POST",
url: "./districtenrollment.htm",
data: "categoryCode="+ this.value,
success : function (data){
$('#blockcode').empty();
$('#blockcode').append($("<option>").val("-1").text("Select"));
for (var i = 0; i < data.length; i++) {
$('#blockcode').append($("<option>").val(data[i][1]).text(data[i][0]));
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error:" + textStatus + " - exception:" + errorThrown);
}
});
});
});
<form:form method="POST" modelAttribute="disblo" autocomplete="off" >
<h3 id="heading"><u>Please Select</u></h3>
<table id="tab">
<tr>
<td>
User Id:
</td>
<td>
<form:input path="myid"/>
</td>
</tr>
<tr>
<td>
User name:
</td>
<td>
<form:input path="username"/>
</td>
</tr>
<tr>
<td>Select District</td>
<td>
<form:select path="mDistricts.districtcode" id="districtcode">
<form:option value="-1">Select </form:option>
<c:forEach var="c" items="${districtlist}">
<form:option value="${c.districtcode}" >${c.districtname}
</form:option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td>Select Block</td>
<td>
<form:select path="mBlocks.blockcode" id="blockcode">
<form:option value="-1">Select </form:option>
<c:forEach var="c" items="${blocklist}">
<form:option value="${c.blockcode}" >${c.blockname}
</form:option>
</c:forEach>
</form:select>
</td>
</tr>
</table>
</form:form>
`
This is my controller
#Autowired
private D_BDAO d_bdao;
#RequestMapping(value="Dist_Block.htm", method = RequestMethod.GET)
public ModelAndView getmodel(#ModelAttribute("disblo") usertestDisBlock db, HttpSession session) {
List<MDistricts> districtlist = d_bdao.getAllCategory();
org.springframework.web.servlet.ModelAndView model = new org.springframework.web.servlet.ModelAndView("Dist_Block");
model.addObject("districtlist", districtlist);
System.out.println("after model");
return model;
}
#RequestMapping(value = "/districtenrollment.htm", method = RequestMethod.POST)
public #ResponseBody
List<MBlocks> getmodel1(#RequestParam("categoryCode") Integer categoryCode) {
System.out.println("categoryCode="+categoryCode);
List<MBlocks> blocklist;
System.out.println("i'm here in ajax controller ");
blocklist = d_bdao.getAllBlocks(categoryCode);
System.out.println("i'm here after b_dao ");
System.out.println("c " + blocklist);
return blocklist;
}
This is my DAO Implementation
#Override
public List<MDistricts> getAllCategory() {
org.hibernate.Session session = sessionFactory.openSession();
session.beginTransaction();
String hql = "from MDistricts";
Query query = session.createQuery(hql);
List<MDistricts> districtlist = query.list();
session.close();
return districtlist;
}
#Override
public List<MBlocks> getAllBlocks(Integer districtcode) {
org.hibernate.Session session = sessionFactory.openSession();
session.beginTransaction();
SQLQuery q = session.createSQLQuery("select blockname, blockcode from test_schema.m_blocks where districtcode=:districtcode ORDER BY blockname");
q.setParameter("districtcode", districtcode);
List<MBlocks> blocklist = q.list();
session.close();
System.out.println("blocklist" + blocklist);
return blocklist;
}
I am not a telepath. But I can make an assumption (cause you don't provide enough information: stacktrace of the error, entity classes).
This code is incorrect
SQLQuery q = session.createSQLQuery("select blockname, blockcode from test_schema.m_blocks where districtcode=:districtcode ORDER BY blockname");
q.setParameter("districtcode", districtcode);
List<MBlocks> blocklist = q.list();
session.createSQLQuery() doesn't return List<MBlocks>, but List<Object[]>. Try this code with HQL:
Query q = session.createQuery(
"from MBlocks where districtcode = :districtcode order by blockname");
q.setParameter("districtcode", districtcode);
List<MBlocks> blocklist = q.list();
And try to log errors.

Data not populating on page after processing post request

it shows data when get request is send properly but when i save data with post requset then again the page is rendered data is not coming on page
This is my controller code
#RequestMapping(value = "/incident", method = RequestMethod.GET)
public String add_incident(Model model,HttpSession session) {
try{
List<AddIncident> fetchincident = incService.fetchIncident();
String user_id = ""+session.getAttribute("session");
List<AddIncident> fetchuserincident = incService.fetchuserincident(user_id);
//group work
User user = new User();
model.addAttribute("user", user);
List<User> fetchListByUsername = userService.findListByUserName(user_id);
String department = fetchListByUsername.get(0).getDepartment();
List<AddIncident> fetchgroupincident = incService.fetchgroupincident(department);
System.out.println(fetchgroupincident.get(0).getAssignTo());
System.out.println(fetchgroupincident.get(0).getSeverity());
model.addAttribute("fetchincident", fetchincident);
model.addAttribute("fetchgroupincident", fetchgroupincident);
model.addAttribute("fetchuserincident", fetchuserincident);
}catch(Exception e){
e.printStackTrace(); }
AddIncident incident = new AddIncident();
model.addAttribute("incident", incident);
return "incident";
}
#RequestMapping(value = "/incident", method = RequestMethod.POST)
public String add_incident(
#Valid #ModelAttribute("incident") AddIncident incident,
BindingResult result, Model model,HttpSession session) {
if (result.hasErrors()) {
return "incident";
} else {
User user=new User();
System.out.println(""+session.getAttribute("session"));
String user_id = ""+session.getAttribute("session");
System.out.println(user_id);
List<User> fetchListByUsername = userService.findListByUserName(user_id);
String department = fetchListByUsername.get(0).getDepartment();
System.out.println(department);
try{
List<User> fetchgroupuser = userService.findListByGroup(department);
ArrayList<String> email=new ArrayList<String>();
System.out.println(email);
for(User use:fetchgroupuser){
email.add(use.getEmail());
}
String[] to = new String[email.size()];
to = email.toArray(to);
System.out.println(to);
/*new String[]{"irasoftwares6#gmail.com","bluemagictest#gmail.com"};*/
String from = "Anurag.yv19#gmail.com";
String sub= "Incident Management System";
String msgBody="New Incident created";
incService.save(incident);
emailService.sendEmail(to , from, sub, msgBody);
}catch(ArrayIndexOutOfBoundsException e){e.printStackTrace();}
incident_logger.log(INCIDENT, incident.getRef_id()+" \n Assigned to :"+session.getAttribute("session"));
model.addAttribute("message", "Saved incident details");
return "incident";
}
}
my jsp code
<div class="table-responsive" id="inc-table" style="min-height: 280px;">
<form action="" method="get">
<div class="input-group">
<!-- USE TWITTER TYPEAHEAD JSON WITH API TO SEARCH -->
<input class="form-control" id="system-search" name="q" placeholder="Search for" required>
<span class="input-group-btn">
<button type="submit" class="btn btn-default"><i class="glyphicon glyphicon-search"></i></button>
</span>
</div>
</form>
<table class="table table-list-search table-bordered table-stripped table-hover">
<thead>
<tr>
<th>Ref. No.</th>
<th>Created</th>
<th>Severity</th>
<th>State</th>
<th>Assigned</th>
<th>Est</th>
<th>Description</th>
<th>Location</th>
<th>Config-item</th>
<th>Symptom Code</th>
<th>Closure Code</th>
<th>Submitted BY</th>
</tr>
</thead>
<tbody>
<c:forEach var="fetchuserincident" items="${fetchuserincident}">
<tr>
<td id="1" class="click" ><a href=""/>${fetchuserincident.ref_id}</td>
<td>${fetchuserincident.created}</td>
<td>${fetchuserincident.severity}</td>
<td>${fetchuserincident.state}</td>
<td>${fetchuserincident.assignTo}</td>
<td>${fetchuserincident.escalation}</td>
<td>${fetchuserincident.description}</td>
<td>${fetchuserincident.location}</td>
<td>${fetchuserincident.config_Item}</td>
<td>${fetchuserincident.symptom_code}</td>
<td>${fetchuserincident.closure_code}</td>
<td>${fetchuserincident.submittedby}</td>
<td> <button id="editbtn" class="fa fa-pencil">Edit</button></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<hr>
<br>
My Group Work
Ref. No.
Created
Severity
State
Assigned
Est
Description
Location
Config-item
Symptom Code
Closure Code
Submitted BY
${fetchgroupincident.ref_id}
${fetchgroupincident.created}
${fetchgroupincident.severity}
${fetchgroupincident.state}
${fetchgroupincident.assignTo}
${fetchgroupincident.escalation}
${fetchgroupincident.description}
${fetchgroupincident.location}
${fetchgroupincident.config_Item}
${fetchgroupincident.symptom_code}
${fetchgroupincident.closure_code}
${fetchgroupincident.submittedby}
Edit

spring form controller with html checkbox

I am trying to bind the input type checkbox using spring form controller,But i failed .
Here i am posting Controller,bean and jsp example,One more thing is i can't use
.
Below is the code:
Controller:
package com.test.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;
#SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {
private UserService userService;
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
user.setCommunity(user.getCommunity());
userService.add(user);
return new ModelAndView("userForm","user",user);
}
}
jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<script>
function submitForm(){
document.testForm.submit();
}
</script>
</head>
<body>
<form:form method="POST" commandName="user" name="testForm" action="./userRegistration.htm">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="1" label="India" />
<form:option value="2" label="USA" />
<form:option value="3" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><input type="checkbox" name="community" value="Hibernate"/>Hibernate</br>
<input type="checkbox" name="community" value="test"/>test</br>
<input type="checkbox" name="community" value="test1"/>test1</br>
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" onclick="submitForm();"></td>
</tr>
</table>
</form:form>
</body>
</html>
Java beans:
package com.test.domain;
public class User {
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
I tried different ways,but no luck.Any hints please.
the browser will not send the field in the request if the checkbox isn't checked. the value will either be "true" or not sent. you will never get a "false" value.
add a hidden field with _name for every checkbox
EX:
<input type="checkbox" name="community" value="Hibernate"/>
<input type="hidden" name="_community" value="on"/>
Then, spring will take care of it.
If you do not use the form tag it will not automaticly bind your checkboxes. If you use plain html you have to bind the your self.
You can solve this by adding a list of community objects and then use form:checkboxes.
For example:
<form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
I would also recomend you to use a HashMap when using ModelAndView like this:
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
model.put("communityList", communityList);
return new ModelAndView("userFormat", model);
Manually bind using 'ServletRequestUtils'... http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/ServletRequestUtils.html
Example
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
Long subscriptionOwnerId = ServletRequestUtils.getLongParameter(request, "id");
return new ModelAndView('test'); }`

Resources