Download CSV file from database using Spring MVC and Hibernate - java

I need to download data from two database tables (factory and factoryType) using the form below but it isn't working. I managed to get data only out of one table... Can somebody take a look?
Factory table:factoryId,factoryname
FactoryType table: factoryType,factoryTypeId
FactoryConf table: factoryID,factoryTypeId
We are using Hibernate for the database operations.
Form
<form:form id="FactoryUploadForm" method="post" modelAttribute="FactoryUploadForm" action="/submitUploadFactoryForm" enctype="multipart/form-data">
<table class="ui-widget" width="100%>
<tr>
<td valign="top" colspan=3 height="40px">
<div class="column span-15 highlight">
</div>
</td>
<td>
<h>Click here to download file</h>
</td>
</tr>
<tr>
<td>
<div class="column span-2_5"><label for="filedata">Select CSV File:</label><span style="color: red">*</span></div>
</td>
<td align="left">
<div class="column span-4"><input class="span-5 ui-input" type="file" id="fileData" name="fileData" size="45" /></div>
</td>
</tr>
<tr>
<td>
<div class="column span-2_5"><label for="uploadComment">Comment/Description:</label></div>
</td>
<td align="left">
<div class="column span-4"><input class="span-5 ui-input" type="text" maxlength="100" id="uploadComment" name="uploadComment" size="50" /></div>
</td>
</tr>
<tr>
<td valign="top"> </td>
<td colspan=2>
<div class="column " style="margin-top: 15px;">
<input type="submit" value="Upload File" "/>
</div>
<div class="column" style="margin-top: 15px;">
<input type="button" value="Reset" onclick="javascript:resetUploadFactoryForm();"/>
</div>
</td>
</tr>
</table>
</form:form>
Controller:
#Controller
public class NewFactoryUploadDownloadController {
private static final Log logger = LogFactory.getLog(NewFactoryUploadDownloadController.class);
#Resource
IInteropService interopService;
#Resource
FactoryUploadRepository repository;
#RequestMapping(value="/download.do")
public String downloadFactory(FactoryUploadForm form, Model model,HttpServletRequest request, HttpServletResponse response) throws IOException {
PrintWriter pw = null;
try{
logger.debug("+++++++++++++++++++++++++++++++++++++++");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename="+ "Backup" +".csv");
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-csheck=0, pre-check=0");
response.setHeader("Pragma", "public");
pw = response.getWriter();
// Get, Write and flush the data.
pw.println("Factory Id,FactoryLegalName,FactoryShortName,FactoryType");
List<Factory> factoryFromDB = Collections.emptyList();
factoryFromDB = Service.getfactories();
logger.info("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
for(Factory factory : factoryFromDB)
{
pw.println(String.format("%s,%s,%s",
factory.getId(),
formatString(factory.getName()),
factory.getShortName()));
}
pw.flush();
}catch (Exception ex){
logger.error("Error while downloading companies", ex);
model.addAttribute("failureMsg", "Error while downloading companies");
}
return null;
}
private String formatString(String str){
if (str.contains(",")){
return "\""+str + "\"";
}
return "\""+str + "\"";
}
}
Model:
#Entity
#Table(name = "FactoryConf", uniqueConstraints = {
#UniqueConstraint(columnNames = { "factoryId" } )
})
public class FactoryConf {
#Id
long factoryId;
#OneToOne
#JoinColumn(name = "factoryId", insertable = false, updatable = false)
Factory factory;
#ManyToOne(optional = false)
#JoinColumn(name = "factoryTypeId")
FactoryType factoryType;
public FactoryConf() {
super();
}
public FactoryConf(long factoryId, FactoryType factoryType) {
super();
this.factoryType = factoryType;
this.factoryId = factoryId;
}
public Factory getFactory() {
return factory;
}
public void setFactory(Factory factory) {
this.factory = factory;
}
public FactoryType getFactoryType() {
return factoryType;
}
public void setFactoryType(FactoryType factoryType) {
this.factoryType = factoryType;
}
public long getFactoryId() {
return factoryId;
}
public void setFactoryId(long factoryId) {
this.factoryId = factoryId;
}
public FactoryType getFactoryTypeByFactoryID(long factoryId){
return factoryType;
}
}

Related

Java SpringBoot Postgres remove rows

Help me please to remove the row in Postgres by clicking the Del button.
Maybe to link id in DB and id on the HTML page, but how?
Maybe I need to parse the HTML page and pass String id?
Any ideas will help me.
here is my database schema:
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<th><form action="/remove" method="post">
<input type="submit" value="Del"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
</form>
</th>
</tr>
{{/messages}}
</tbody>
#Entity
#Table(name = "message")
public class Message {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
private String text;
private String sn;
private String owner;
public Message() {
}
public Message(String text, String sn, String owner) {
this.text = text;
this.sn = sn;
this.owner = owner;
}
Rows are forming in database by:
#PostMapping("/main")
public String add (
#RequestParam String owner,
#RequestParam String text,
#RequestParam String sn, Map<String, Object> model) {
Message message = new Message (text, sn, owner);
if (text != null && !text.isEmpty() & sn != null && !sn.isEmpty() & owner != null &&
!owner.isEmpty()) {
if (!text.matches("^[0-9].*$")) {
messageRepo2.save(message);
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else
model.put("error", "ТМЦ не должно начинаться с цифры");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
} else {
model.put("error", "Заполните все поля!");
Iterable<Message> messages = messageRepo2.findAll();
model.put("messages", messages);
}
return "main";
}
There are two issues with your html code:
it would be to let the form element outside the table
need to use <input type="hidden" name="xxx" value="{{xxx}}" /> in order to let it can pass parameter to your controller method
<form action="/remove" method="post">
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<table class="tmc">
<thead>
<tr>
<th>ID</th><th>TMC</th><th>SN</th><th>Owner</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}} <input type="hidden" name="id" value="{{id}}" /></td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i> <input type="hidden" name="sn" value="{{sn}}" /></td>
<td><i>{{owner}}</i> <input type="hidden" name="owner" value="{{owner}}" /></td>
<td><input type="submit" value="Del"/></td>
</th>
</tr>
{{/messages}}
</tbody>
</table>
</form>
<thead>
<tr>
<th>ID ТМЦ</th><th>Наименование ТМЦ</th><th>Серийный номер ТМЦ</th><th>За кем числится</th>
</tr>
</thead>
<tbody>
{{#messages}}
<tr>
<td>{{id}}</td>
<td><span>{{text}}</span></td>
<td><i>{{sn}}</i></td>
<td><i>{{owner}}</i></td>
<td>
<form action="/remove" method="post" name="remove">
<input type="submit" value="Удалить"/>
<input type="hidden" name="_csrf" value="{{_csrf.token}}" />
<input type="hidden" name="sn" value="{{sn}}"/>
</form>
</td>
</tr>
{{/messages}}
</tbody>
import com.example.webapp.domain.Message;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Transactional
public interface MessageDel extends CrudRepository<Message, Long>{
List<Message> deleteBySn (String sn);
}
#PostMapping("/remove")
public String remove (#RequestParam String sn, Map<String, Object> model) {
Message messagedel = new Message (sn);
messageDel.deleteBySn(sn);
model.put("messages", messagedel);
return "redirect:/main";
}

Request Sent by the Client was syntactically incorrect with spring mvc - hunch is on photo upload method

im doing a web and upon testing it i encountered this , Request Sent by the Client was syntactically incorrect. i dont know which is the one giving the error, but to say, i have a model class that is artist.java. My jsp pages are artist,jsp and artistview.jsp. and it is being controlled by the artistcontroller.java. I am getting this error when i edit a an artist from my artistview.jsp. it is then directed to the edit portion of artist.jsp. after editing the details filling all details again, and i press edit artist, i get the error. i have a hunch that it is coming from the uploadprofilepic method, but cant figure it out. hope you could help me on this. thanks in advance.
here are my codes.
artist.java (my model class)
package com.artistlabprod.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
#Entity
#Table(name="ARTIST")
public class Artist {
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="ARTISTNAME")
private String artistName;
#Column(name="SURNAME")
private String surname;
#Column(name="TALENT")
private String talent;
#Column(name="AGE")
private int age;
#Column(name="HEIGHT")
private String height;
#Column(name="WEIGHT")
private String weight;
#Column(name="HAIRCOLOR")
private String hairColor;
#Column(name="EYECOLOR")
private String eyeColor;
#Column(name="ETHNICITY")
private String ethnicity;
#Column(name="EXPERIENCE")
private String experience;
#Column(name="PHOTO")
private String photo;
#Column(name="TWITTER")
private String twitter;
#Column(name="FACEBOOK")
private String facebook;
#Column(name="INSTAGRAM")
private String instagram;
public Artist() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getTalent() {
return talent;
}
public void setTalent(String talent) {
this.talent = talent;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getHairColor() {
return hairColor;
}
public void setHairColor(String hairColor) {
this.hairColor = hairColor;
}
public String getEyeColor() {
return eyeColor;
}
public void setEyeColor(String eyeColor) {
this.eyeColor = eyeColor;
}
public String getEthnicity() {
return ethnicity;
}
public void setEthnicity(String ethnicity) {
this.ethnicity = ethnicity;
}
public String getExperience() {
return experience;
}
public void setExperience(String experience) {
this.experience = experience;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getTwitter() {
return twitter;
}
public void setTwitter(String twitter) {
this.twitter = twitter;
}
public String getFacebook() {
return facebook;
}
public void setFacebook(String facebook) {
this.facebook = facebook;
}
public String getInstagram() {
return instagram;
}
public void setInstagram(String instagram) {
this.instagram = instagram;
}
}
artistcontroller.java
package com.artistlabprod.controller;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.artistlabprod.model.Artist;
import com.artistlabprod.service.ArtistService;
#Controller
public class ArtistController {
private ArtistService artistService;
public ArtistService getArtistService() {
return artistService;
}
#Autowired(required=true)
#Qualifier(value="artistService")
public void setArtistService(ArtistService ps){
this.artistService = ps;
}
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("listArtists", this.artistService.listArtists());
return "home";
}
#RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView getHome() {
ModelAndView modelandview = new ModelAndView ("index");
return modelandview;
}
#RequestMapping(value = "/aboutus", method = RequestMethod.GET)
public ModelAndView getAboutus() {
ModelAndView modelandview = new ModelAndView ("aboutus");
return modelandview;
}
#RequestMapping(value = "/contactus", method = RequestMethod.GET)
public ModelAndView getContactus() {
ModelAndView modelandview = new ModelAndView ("contactus");
return modelandview;
}
#RequestMapping(value = "/artists", method = RequestMethod.GET)
public String listArtists(Model model) {
model.addAttribute("artist", new Artist());
model.addAttribute("listArtists", this.artistService.listArtists());
return "artist";
}
#RequestMapping(value = "/artistview", method = RequestMethod.GET)
public String listofArtists(Model model) {
model.addAttribute("listArtists", this.artistService.listArtists());
return "artistview";
}
#RequestMapping(value= "/artist/add", method = RequestMethod.POST)
public String addArtist(){
return "redirect:/artistview";
}
#RequestMapping("/remove/{id}")
public String removeArtist(#PathVariable("id") int id){
this.artistService.removeArtist(id);
return "redirect:/artists";
}
#RequestMapping("/edit/{id}")
public String editArtist(#PathVariable("id") int id, Model model) {
model.addAttribute("artist", this.artistService.getArtistById(id));
model.addAttribute("listArtists", this.artistService.listArtists());
return "artist";
}
#RequestMapping(value = "/uploadProfilePic", method = RequestMethod.POST)
public String uploadBackground(#ModelAttribute("artist") Artist p, #RequestParam("file") MultipartFile file, Model model) {
String name="";
if(p.getId() == 0){
//add a new inventory item
this.artistService.addArtist(p);
p.setPhoto("photo-"+ p.getId() + ".jpg");
this.artistService.updateArtist(p);
name = p.getPhoto();
}else{
//update an existing inventory item
this.artistService.updateArtist(p);
}
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = "C:" + File.separator + "Users"
+ File.separator + "User Folder"
+ File.separator + "Documents"
+ File.separator + "appdevupitdc"
+ File.separator + "workspace"
+ File.separator + ".metadata"
+ File.separator + ".plugins"
+ File.separator + "org.eclipse.wst.server.core"
+ File.separator + "tmp1"
+ File.separator + "webapps"
+ File.separator + "img"
+ File.separator + "artistphotos";
File dir = new File(rootPath);
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + name);
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
//return listofArtists(model);
return addArtist();
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name
+ " because the file was empty.";
}
}
}
artist.jsp
<div class="container">
<div class="row">
<c:url var="addAction" value="/artist/add"></c:url>
<form:form action="uploadProfilePic" commandName="artist" enctype="multipart/form-data">
<table class="table table-hover table-responsive table-striped" >
<c:if test="${!empty artist.artistName}">
<tr>
<td><form:label path="id">
<spring:message text="ID" />
</form:label></td>
<td><form:input path="id" readonly="true" size="8"
disabled="true" /> <form:hidden path="id" /></td>
</tr>
</c:if>
<tr>
<td><form:label path="artistName">
<spring:message text="Name" />
</form:label></td>
<td><form:input size="35" path="artistName" /> </td>
</tr>
<tr>
<td><form:label path="surname">
<spring:message text="Surname" />
</form:label></td>
<td><form:input size="35" path="surname" /></td>
</tr>
<tr>
<td><form:label path="talent">
<spring:message text="Talent" />
</form:label></td>
<td><form:input size="35" path="talent" /></td>
</tr>
<tr>
<td><form:label path="age">
<spring:message text="Age" />
</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td><form:label path="height">
<spring:message text="Height" />
</form:label></td>
<td><form:input path="height" /></td>
</tr>
<tr>
<td><form:label path="weight">
<spring:message text="Weight" />
</form:label></td>
<td><form:input path="weight" /></td>
</tr>
<tr>
<td><form:label path="hairColor">
<spring:message text="Hair Color" />
</form:label></td>
<td><form:input size="35" path="hairColor" /></td>
</tr>
<tr>
<td><form:label path="eyeColor">
<spring:message text="Eye Color" />
</form:label></td>
<td><form:input size="35" path="eyeColor" /></td>
</tr>
<tr>
<td><form:label path="ethnicity">
<spring:message text="Ethnicity" />
</form:label></td>
<td><form:input size="35" path="ethnicity" /></td>
</tr>
<tr>
<td><form:label path="photo">
<spring:message text="Photo" />
</form:label></td>
<td><form:input type="file" name="file" path="" /></td>
</tr>
<tr>
<td><form:label path="experience">
<spring:message text="Experience" />
</form:label></td>
<td><form:textarea rows="10" cols="75" path="experience" /></td>
</tr>
<tr>
<td><form:label path="twitter">
<spring:message text="Twitter Link" />
</form:label></td>
<td><form:input size="35" path="twitter" /></td>
</tr>
<tr>
<td><form:label path="facebook">
<spring:message text="Facebook Link" />
</form:label></td>
<td><form:input size="35" path="facebook" /></td>
</tr>
<tr>
<td><form:label path="instagram">
<spring:message text="Instagram Link" />
</form:label></td>
<td><form:input size="35" path="instagram" /></td>
</tr>
<tr>
<td colspan="2"><c:if test="${!empty artist.artistName}">
<input type="submit" class="btn btn-success"value="<spring:message text="Edit Artist"/>" />
</c:if> <c:if test="${empty artist.artistName}">
<input type="submit" class="btn btn-primary" value="<spring:message text="Add Artist"/>" />
</c:if></td>
<td></td>
</tr>
<tr>
<td>
<a class="btn btn-info" href="<c:url value='/artistview' />"><i class="fa fa-list-ul fa-lg"></i> View List</a>
</td>
<td></td>
</tr>
<!-- for bottom line of table -->
<tr>
<td>
</td>
<td></td>
</tr>
</table>
</form:form>
</div>
artistview.jsp
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="section-heading">Artist List</h2>
<h3 class="section-subheading text-muted">Lorem ipsum dolor sit amet consectetur.</h3>
</div>
</div>
<c:if test="${!empty listArtists}">
<table class="table table-hover table-responsive table-striped">
<tr>
<th>Profile Picture</th>
<th>First Name</th>
<th>Last Name</th>
<th>Talent</th>
<th>Age</th>
<th>Height</th>
<th>Weight</th>
<th>Hair Color</th>
<th>Eye Color</th>
<th>Ethnicity</th>
<th>Experience</th>
<th>Twitter Link</th>
<th>Facebook Link</th>
<th>Instagram Link</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach items="${listArtists}" var="artist">
<tr>
<!-- <td><div style= "height: 200px; width: 200px"><img style="height: 100%; width:100%" src="photo?id=${artist.id}"/> </div>-->
<td> <img class="img-responsive" style="height: 100%; width:100%" src="/img/artistphotos/${artist.photo}" alt="" /> </td>
<td>${artist.artistName}</td>
<td>${artist.surname}</td>
<td>${artist.talent}</td>
<td>${artist.age}</td>
<td>${artist.height}</td>
<td>${artist.weight}</td>
<td>${artist.hairColor}</td>
<td>${artist.eyeColor}</td>
<td>${artist.ethnicity}</td>
<td>${artist.experience}</td>
<td>${artist.twitter}</td>
<td>${artist.facebook}</td>
<td>${artist.instagram}</td>
<td><a class="btn btn-success" href="<c:url value='/edit/${artist.id}' />"><i class="fa fa-pencil fa-lg"></i> Edit</a></td>
<td><a class="btn btn-danger" href="<c:url value='/remove/${artist.id}' />"><i class="fa fa-trash-o fa-lg"></i> Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
there is no error showing in the console of eclipse, but
here is the error im receiving from the browser:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Apache Tomcat/8.0.21
also the url on top displays this:
http://localhost:8080/artistweb/edit/uploadProfilePic
You are missing
(HttpServletResponse response, HttpServletRequest request)
in your method calls?
public String uploadBackground(#ModelAttribute("artist") Artist p, #RequestParam("file") MultipartFile file, Model model, HttpServletResponse response, HttpServletRequest request)
add in dispatcher-servlet.xml
<!-- setting maximum upload size -->
<beans:property name="maxUploadSize" value="10000000000000" />
</beans:bean>

jsp in another jsp struts 2

1st problem : i have a jsp in which there are two tabs ,for the second tab i have included the struts include tag. When i open the second tab and performs the action the second tab form values are not passing to the action.
2nd problem : in the select tag i have populate the list but it is coming as prepopulated means all the options are coming as selected="selected"
main jsp in which tabs are made
<!-- admin first tab starts here -->
<form action="saveRolesAndPermissions" method="post">
<table align="center">
<tr>
<td ><s:text name="FTID" ></s:text></td>
<td ><s:textfield id="FTID" name="ft_id">
</s:textfield></td>
<td><input type="button" value="validate" onclick="userPresent()"></td>
</tr>
</table>
<table>
<tr>
<td>First Name</td>
<td><input id="first_name" type="text" readonly onkeydown="return false"></td>
<td>Last Name</td>
<td><input id="last_name"
type="text" readonly onkeydown="return false"></td>
<td>Email-Id</td>
<td><input id="mail_id" type="text"
readonly onkeydown="return false"></td>
</tr>
</table>
<table align="center">
<tr>
<td><s:text name="ROLES"></s:text></td>
<td></td>
<td></td>
</tr>
<tr>
<td><s:text name="Available Roles"></s:text></td>
<td></td>
<td><s:text name="Assigned Roles"></s:text></td>
</tr>
<tr>
<td><s:select id="roles" name="availableRole"
multiple="true" list="availableRole"></s:select></td>
<td><input type="button" value="&gt" onclick="move_list_items('roles','assignedroles');"/><input
type="button" value="&lt" onclick="move_list_items('assignedroles','roles');"/></td>
<td><s:select id="assignedroles" name="assignedRole" multiple="true"
list="{}" >
</s:select></td>
</tr>
</table>
<br /> <br /> <br />
<table>
<tr>
<td><s:text name="Permissions"></s:text></td>
<td></td>
<td> </td>
</tr>
<tr>
<td><s:text
name="Available Permissions"></s:text></td>
<td></td>
<td><s:text name="Assigned Permissions"></s:text></td>
</tr>
<tr>
<td><s:select id="permissions" multiple="true"
name="availablePermission" list="availablePermission" headerValue=""></s:select></td>
<td><input
type="button" value="&gt" onclick="move_list_items('permissions','assignedpermissions');"/><br /> <input type="button"
value="&lt" onclick="move_list_items('assignedpermissions','permissions');" /></td>
<td><s:select id="assignedpermissions" multiple="true" name="assignedPermission"
list="{}" ></s:select></td>
</tr>
</table>
<br /> <br />
<table align="center" style="width: 25%;">
<tr>
<td><s:if test="hasActionMessages()">
<div class="welcome" style="list-style:none">
<s:actionmessage />
</div>
</s:if></td>
</tr>
</table>
<table>
<tr>
<td><s:submit
value="save"onclick="saveRole();return false;"></s:submit></td>
<td> <input type="button" name="close"
value="close" /></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</form>
<!-- second tab for modify roles -->
<div id="content02" class="content" >
<s:include value="../asp/aspAdminModify.jsp"></s:include>
</div>
<!-- /second tab ends here -->
included jsp
<form action="grantedRolesAndPermissions" method="post">
<table>
<tr>
<td><s:text name="FTID" ></s:text></td>
<td><s:textfield id="modify_FTID" name="modifyftid">
</s:textfield></td>
<td><s:submit
value="search" onclick="search();return false;"></s:submit>
</td>
</tr>
</table>
Bean for the first tab
private String ft_id;
private ArrayList<String> availableRole;
private ArrayList<String> availablePermission;
private ArrayList<String> assignedRole;
private ArrayList<String> assignedPermission;
//getters and setters
Action for the first tab
public class ASPadmin extends ActionSupport implements ServletRequestAware, ModelDriven<ASPAdminBean>{
/**
*
*/
private static final long serialVersionUID = 1L;
private AdminASPService aspService = new AdminASPService();
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
public CMTUser cmtuser;
private ASPAdminBean aspAdminBean = new ASPAdminBean();
//getters and setters
public String populateRolesAndPermissions() throws Exception
{
/*aspAdminBean=new ASPAdminBean();*/
aspAdminBean.setAvailableRole(aspService.getRolesList());
aspAdminBean.setAvailablePermission(aspService.getPermissionsList());
return SUCCESS;
}
public String saveRolesAndPermissions() throws Exception
{
User user = CMTUser.getUser(request);
String login = user.getUserId();
String[] temp = login.split("\\.");
String abcfinal = temp[0].substring(0, 1).toUpperCase()
+ temp[0].substring(1);
String deffinal = temp[1].substring(0, 1).toUpperCase()
+ temp[1].substring(1);
String name = abcfinal + " " + deffinal;
System.out.println("name ==============>" + name);
String id = aspService.saveRolesPermissions(aspAdminBean,name);
System.out.println("id=======>"+id);
if("Y".equals(id)){
addActionMessage("Record Inserted Successfully");
populateRolesAndPermissions();
return SUCCESS;
}
else{
return ERROR;
}
}
#Override
public String execute() throws Exception {
String url = request.getRequestURL().toString();
String[] actionArray = url.split("/");
String event = null;
String forward = SUCCESS;
for (int i = 0; i < actionArray.length; i++) {
event = actionArray[i];
}
System.err.println(event);
try {
if (event.equals("aspAdmin.action")) {
populateRolesAndPermissions();
}
}catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}
#Override
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
#Override
public ASPAdminBean getModel() {
// TODO Auto-generated method stub
return aspAdminBean;
}
}
bean for second tab
public class ASPAdminModifyBean {
private String modifyftid;
private String aspmodifyassignedRole;
private String aspmodifyassignedPermission;
private String createddate;
private String createdby;
private String updateddate;
private String updatedby;
private String username;
private ArrayList<String> modifyavailableRole;
private ArrayList<String> modifyavailablePermission;
private ArrayList<String> modifyassignedRole;
private ArrayList<String> modifyassignedPermission;
//getters and setters
action for the second tab
public class ASPadminModify extends ActionSupport implements ServletRequestAware, ModelDriven<ASPAdminModifyBean> {
private AdminASPService aspService = new AdminASPService();
private GetRolePermissionListInt[] roleVO;
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
private ASPAdminModifyBean modify = new ASPAdminModifyBean();
GetRolePermissionListInt role;
//getters and setters for the above
public String grantRolesPermissions(){
System.out.println("enter the grant roles and permissions");
String tab2="modify";
boolean id;
HttpServletRequest request=getRequest();
HttpSession session=request.getSession();
session.setAttribute("tabs",tab2 );
role=aspService.getGrantedRolesAndPermissions(modify);
System.out.println("assigned roles===================>"+role.getAssignedRoles());
modify.setAspmodifyassignedRole(role.getAssignedRoles());
modify.setAspmodifyassignedPermission(role.getAssignedPermissions());
modify.setCreatedby(role.getCreatedBy());
modify.setCreateddate(role.getCreatedDate());
modify.setUpdatedby(role.getUpdatedBy());
modify.setUpdateddate(role.getUpdatedDate());
modify.setUsername(role.getUserName());
modify.setModifyftid(role.getFtid());
System.out.println("assigned permissions==============>"+role.getAssignedPermissions());
System.out.println("updated by=================>"+role.getUpdatedBy());
System.out.println("update date=================>"+role.getUpdatedDate());
System.out.println("created by===================>"+role.getCreatedBy());
System.out.println("created date=====================>"+role.getCreatedDate());
System.out.println("ftid=============================>"+role.getFtid());
System.out.println("user name===========================>"+role.getUserName());
System.out.println("ftid=============>"+role.getFtid());
if(role!=null){
return SUCCESS;
}else{
return ERROR;
}
}
#Override
public void setServletRequest(HttpServletRequest arg0) {
// TODO Auto-generated method stub
}
#Override
public ASPAdminModifyBean getModel() {
// TODO Auto-generated method stub
return modify;
}
}
Well, the code is grown again :)
Start by :
changing your ArrayList declarations to List (in both beans, and regenerate getters and setters);
changing the way you get the Request, the Response and the Session, by using Struts2 Aware s interfaces (and their setters, with code inside)
Then if it still doesn't work, describe a little better what do you mean by "values are not passing to Action", and consider posting your interceptor stack config.
Hope that helps...

JSP and Spring Validation

This is my BackupForm:
public class BackupForm {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is validator:
#Component
public class BackupFormValidator implements Validator {
public boolean supports(Class<?> clazz) {
return BackupForm.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
BackupForm backupForm = (BackupForm) target;
if (backupForm.getName().length() == 0) {
System.out.println("Empty");
errors.rejectValue("name", "name.empty", "Name field is empty.");
} else {
File file = new File(Configures.getDirectory() + "\\"
+ backupForm.getName() + ".sql");
if (file.exists()) {
System.out.println("Exists");
errors.rejectValue("name", "name.exist",
"File." + backupForm.getName() + ".sql already exists.");
}
}
}
}
This is how I do in controller:
#RequestMapping(value = "/backup", method = RequestMethod.POST)
public String backupProcess(
#ModelAttribute("backup") BackupForm backupForm,
BindingResult result, Map<String, Object> map) {
backupFormValidator.validate(backupForm, result);
if (result.hasErrors()) {
// Если обнаружилась ошибка, то добавим в карту идентификатор об
// ошибке и вернем логическое представление поиска
map.put("error", true);
map.put("backup", new BackupForm());
map.put("search", new SearchForm());
return "backup";
} else {
return "redirect:/";
}
}
It's works, but tag errors is not working:
<form:form method="POST" commandName="backup">
<c:if test="${!empty error}">
<div class="alert alert-danger">
<b>Can not execute command!</b>
<form:errors path="name" />
</div>
</c:if>
<div class="panel panel-default">
<div class="panel-heading">New backup</div>
<div class="panel-body">
<table style="width: 100%; border-collapse: collapse;">
<tbody>
<tr>
<td
style="vertical-align: top; width: 250px; letter-spacing: 0px; word-spacing: 0px;"><form:input
path="name" class="form-control input-sm" type="text"
placeholder="Enter backup name..." value="${name}" /></td>
<td
style="text-align: left; vertical-align: top; letter-spacing: 0px; word-spacing: 0px;">
<input class="btn btn-success btn-sm"
type="submit" value="Backup" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</form:form>
What's wrong? Validation works properly, but <form:errors path="name" /> doesn't return anything.
You should remove the following line:
map.put("backup", new BackupForm());
This line is resetting the modelAttribute to a new one and thus the errors don't appear.

from json it is not returning the result

This is jsp code what is happening is when i submit the code it will call url of ajax function and executing that function also but when returning it will call to other url
If i'm calling ajax from jsp that is going to that particular url and executing it after that it entering to the other url without returning the result
<form name="frm" action="createnewcatgoryBean.jsp" onsubmit="return validatenewcat()" method="post">
<table style="padding: 5px 0px 0px 8px;">
<tr>
<th colspan="2">
<div style="width: width:271px; color:red;" id="validate"></div>
</th>
</tr>
<tr>
<th>Category Name<span>:</span>
</th>
<td>
<input id="cat" onblur="return validatenewcat()" type="text" name="category">
</td>
</tr>
<tr>
<th>Quotations form<span>:</span>
</th>
<td>
<input type="checkbox" name="quotations">
</td>
</tr>
<tr>
<th>Agreement form<span>:</span>
</th>
<td>
<input type="checkbox" name="agreement">
</td>
</tr>
<tr>
<th>Payment form<span>:</span>
</th>
<td>
<input type="checkbox" name="payment">
</td>
</tr>
<tr>
<th>ETI<span>:</span>
</th>
<td>
<input type="checkbox" name="eti">
</td>
</tr>
<tr>
<td colspan="2" style="float:right; padding-top:15px">
<input type="submit" value="Submit" style="width: 60px;">
</td>
</tr>
</table>
</form>
This is the JavaScript code that includes the AJAX request:
function validatenewcat() {
var category = document.getElementById("cat").value;
if (category == "") {
setTimeout(document.getElementById("validate").innerHTML = "!PLz Enter The Category Name", 2000);
return false;
} else {
var url = "catnamecheck.do?id=" + category;
xmlhttp.open("post", url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var temp = xmlhttp.responceText;
obj = JSON.parse(temp);
alert(obj);
if (temp != "") {
document.getElementById("validate").innerHTML = "!PLz Enter The Unique Category Name";
document.getElementById("cat").focus();
return false;
}
}
}
}
}
}
this my java code
public Map<String, String> catuniqecheck(String id) {
Connection c = null;
PreparedStatement ps1 = null;
ResultSet rs1 = null;
String sql=null;
try{
c = JDBCHelper.getConnection();
if(c!=null)
{
Map<String, String> map = new HashMap<String, String>();
sql="select * from catgory where catgoryname=?";
ps1=c.prepareStatement(sql);
ps1.setString(1, id);
ps1.execute();
rs1=ps1.getResultSet();
if(rs1.next())
{
System.out.println("insdide of the catuniqecheck");
map.put("catgoryname",rs1.getString("catgoryname"));
}
return map;
}
else
{
System.out.println("DB connection Established");
return null ;
}
}
catch (Exception e) {
// TODO: handle exception
return null ;
}
finally{
JDBCHelper.close(rs1);
JDBCHelper.close(ps1);
JDBCHelper.close(c);
}
}
this my servlet code
Map<String, String> result =p1.catuniqecheck(id);
if(result!=null)
{
System.out.println("inside success");
JSONObject json = new JSONObject();
json.accumulateAll(result);
System.out.println("inside json"+json.toString());
response.setContentType("application/json");
response.getWriter().write(json.toString());
}
try with
obj = JSON.parse("["+temp+"]")
And then first response length
alert(obj[0].length);
alert(obj[0]);
bcoz sometime response itself inside Square brackets like [{...}]

Categories

Resources