JSP and Spring Validation - java

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.

Related

Spring MVC - fill model on the form

I want to fill the form according to the related book when I click the view or update the link on the page. I know, there is a solution with opening another page but I want to do it on the same page. As you can see on the picture below I can properly get the list on the left table. I have tried a post method below but did not work. So what would you recommend to do it?
Controller class:
#PostMapping(path = "/listbooks")
public String getBook(#ModelAttribute BookConfig bookConfig, Model model)
throws IOException {
model.addAttribute("book", bookConfig);
return "list";
}
#GetMapping(path = "/listbooks")
public String showAllBooks(Model model) throws IOException {
model.addAttribute("books", bookService.getBookConfigList());
return "list";
}
HTML file:
<div class="table-responsive" th:if="${not #lists.isEmpty(books)}">
<table class="table table-hover" style="height:50px;">
<thead class="thead-inverse">
<tr>
<th>Name</th>
<th>View</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tr th:each="book : ${books}">
<td th:text="${book.name}">Book Name</td>
<td>View</td>
<td>Update</td>
<td>Delete</td>
</tr>
</table>
</div>
This is what I am trying to do on the HTML file:
<form th:if="${book != null}" th:object="${book}" th:action="#{/book/}"
method="post">
<div class="panel-heading">
<h4 class="panel-title"
">Edit
Book Configuration</h4>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 form-group"
>
<label>Book name</label>
<input type="text" class="form-control" th:field="*{name}"/>
</div>
...
I have solved using JavaScript, Firstly, I have adjusted the getBook method below
#PostMapping("/books")
public String getBook(#RequestBody String bookName) throws IOException {
return "list";
}
and then I have add these two JS functions:
$(document).ready(function () {
$(".view").click(function () {
var $row = $(this).closest("tr"); // Find the row
var $text = $row.find(".bookname").text(); // get the text on the view link using its the class name
$.post("http://localhost:8081/books",
{
bookName: $text
},
function (data, status) {
assignDataToTable(data);
});
});
});
function assignDataToTable(data) {
alert("hey" + data);
document.getElementById("booknameinput").value = data;
}

Spring MVC: Multiple Row Form Submit

I had a requirement where using Spring MVC we had to take inputs multiple rows of data from user. The form had many rows which user can edit and submit My code look like this.When I tried to display the area list it is null What will be the reason
My view is
<form data-th-action="#{/qprmonitorlottery}" method="POST" >
<section>
<div class="panel panel-default" style="margin-top: 15px;">
<!-- Default panel contents -->
<div class="panel-heading">エリア間補完の有無</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="13%" style="background: #FFFFFF; border-top: 1px solid #ffffff; border-left: 1px solid #ffffff;" > </th>
<th colspan="3" style="text-align: center">都市規模</th>
</tr>
<tr>
<th>エリア </th>
<th width="28%">大都市 </th>
<th width="29%">中都市</th>
<th width="30%">郊外 </th>
</tr>
<tr data-th-each="qprLottery,stat : ${qprLottery}">
<td data-th-text = "${qprLottery.areaName}">北海道 </td>
<td> <span style="display: inline-block; width: 80%">
<input type="number" data-th-value = "${qprLottery.rate1}" class="form-control" data-th-name="firstRate +${stat.index}" required >
<span class="help-block with-errors"></span>
</span> <span style="position: relative; top:-10px;" >%</span> </td>
<td> <span style="display: inline-block; width: 80%">
<input type="number" data-th-value = "${qprLottery.rate2}" class="form-control" data-th-name="secondRate +${stat.index}" required >
</span> <span style="position: relative; top:-10px;" >%</span> </td>
<td> <span style="display: inline-block; width: 80%">
<input type="number" data-th-value = "${qprLottery.rate3}" class="form-control" data-th-name="thirdRate +${stat.index}" required >
</span> <span style="position: relative; top:-10px;" >%</span> </td>
</tr>
</table>
</div>
</div>
</div>
</section>
<div class="row">
<div align="center" style="padding: 30 0px;">
<button type="submit" class="btn btn-primary" value="実行">実行
</button>
</div>
</div>
</form>
Controller is
#RequestMapping(value = "/qprmonitorlottery", method = RequestMethod.POST)
public String setQprMonitorLottery(#Valid #ModelAttribute() MasterCitySizeAreaForm form, BindingResult result) {
CitySizeByAreaView a = new CitySizeByAreaView();
System.out.println("Area list" + a.getRate1());
System.out.println("Area list-------------" + form.getAreaList());
if (result.hasErrors()) {
return "new-monitor-lottery";
}
return "new-monitor-lottery";
}
form classes are
public class MasterCitySizeAreaForm {
private ArrayList<CitySizeAreaForm> areaList;
public ArrayList<CitySizeAreaForm> getAreaList() {
return areaList;
}
public void setAreaList(ArrayList<CitySizeAreaForm> areaList) {
this.areaList = areaList;
}
}
form class 2
public class CitySizeAreaForm {
private int areaId;
private Integer area;
private Integer citySize;
private String areaName;
private String citySizeName;
private Float rate1;
private Float rate2;
private Float rate3;
public CitySizeAreaForm() {
}
public CitySizeAreaForm(Integer area, String areaName, Float rate1, Float rate2, Float rate3) {
this.area = area;
this.areaName = areaName;
this.rate1 = rate1;
this.rate2 = rate2;
this.rate3 = rate3;
}
}
replace:
<tr data-th-each="qprLottery,stat : ${qprLottery}">
with
<tr data-th-each="qprLottery,stat : ${qprLottery.areaList}">
This link helped me!!!Do try it!!
http://jsltech.blogspot.com/2013/12/how-add-multiple-objects-into-database.html
can use this format for displaying:-
<c:forEach items="${contactForm.contacts}" var="contact" varStatus="status">
<tr>
<td>${contact.firstname}</td>
<td>${contact.lastname}</td>
<td>${contact.email}</td>
<td>${contact.phone}</td>
</tr>
</c:forEach>

JSP how to link between 2 java classes to add items to arraylist and display them in JSP

Heyy I'm new to JSP and would like to know how to solve a small problem. I'm not sure how to do the link between the Client.java and Item.java to be able to add new items into the ArrayList and display it on the jsp page.
This is my Client.java code:
package javaCode;
import java.util.ArrayList;
public class Client {
private String name;
private String email;
private int phone;
private String address;
private String country;
private String city;
public ArrayList<Item> list;
private String shipping;
private int fee;
private double discount;
private Item item;
public Client() {
list = new ArrayList<Item>();
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setPhone(int phone) {
this.phone = phone;
}
public int getPhone() {
return phone;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return address;
}
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return country;
}
public void setCity(String city) {
this.city = city;
}
public String getCity() {
return city;
}
public void setShipping(String shipping) {
this.shipping = shipping;
}
public String getShipping() {
return shipping;
}
public void setFee() {
if(this.shipping == "") {
this.fee = 0;
}
if(this.shipping == "USPS Express Mail") {
this.fee = 200;
}
if(this.shipping == "USPS Priority Mail") {
this.fee = 300;
}
if(this.shipping == "DHL") {
this.fee = 400;
}
if(this.shipping == "FedEx") {
this.fee = 50;
}
}
public int getFee() {
return fee;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public double getDiscount() {
return discount;
}
public void setItem(Item item) {
list.add(this.item);
}
public ArrayList<Item> getList() {
return list;
}
}
This is my Item code:
package javaCode;
public class Item {
private String item;
private int quantity;
private double price;
public Item() {
}
public void setItem(String item) {
this.item = item;
}
public String getItem() {
return item;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
//Client.list.add(this);
}
public int getQuantity() {
return quantity;
}
public void setPrice(double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public double getTotal() {
return (quantity*price);
}
}
This is the clientdetails.jsp file:
<jsp:useBean id="iteminfo" class="javaCode.Item"/>
<jsp:setProperty property="*" name="iteminfo"/>
<jsp:useBean id="userinfo" class="javaCode.Client" scope="request"/>
<jsp:setProperty property="*" name="userinfo"/>
<h2>Personal Information</h2>
<table border="1">
<tr>
<td>Name</td>
<td><jsp:getProperty property="name" name="userinfo"/></td>
</tr>
<tr>
<td>E-mail</td>
<td><jsp:getProperty property="email" name="userinfo"/></td>
</tr>
<tr>
<td>Phone</td>
<td><jsp:getProperty property="phone" name="userinfo"/></td>
</tr>
<tr>
<td>Address</td>
<td><jsp:getProperty property="address" name="userinfo"/></td>
</tr>
<tr>
<td>Country</td>
<td><jsp:getProperty property="country" name="userinfo"/></td>
</tr>
<tr>
<td>City</td>
<td><jsp:getProperty property="city" name="userinfo" /></td>
</tr>
<tr>
<td>Shipping Method</td>
<td><jsp:getProperty property="shipping" name="userinfo"/></td>
</tr>
<tr>
<td>Shipping Amount</td>
<td><jsp:getProperty property="fee" name="userinfo"/></td>
</tr>
<tr>
<td>Discount</td>
<td><jsp:getProperty property="discount" name="userinfo"/></td>
</tr>
<tr>
<td>List</td>
<td><jsp:getProperty property="list" name="userinfo"/></td>
</tr>
</table>
<br><br>
<table border="1">
<tr>
<td>Name</td>
<td>Item1</td>
</tr>
<tr>
<td>Quantity</td>
<td><jsp:getProperty property="quantity" name="iteminfo"/></td>
</tr>
<tr>
<td>Unit Price</td>
<td><jsp:getProperty property="price" name="iteminfo"/></td>
</tr>
<tr>
<td>Total</td>
<td><jsp:getProperty property="total" name="iteminfo"/></td>
</tr>
</table>
This is the form.jsp file (containing html form):
<html>
<head>
<title>Order Form</title>
<link rel="stylesheet" type="text/css" href="formstyle4.css">
<script type="text/javascript"></script>
</head>
<body>
<form name="order" id="orderForm" action="clientdetails.jsp" method="post">
<p id="date"><script type="text/javascript"></script></p>
<h2>Personal Information</h2>
<label id="fname">* Name</label><input type="text" name="name" id="name" onkeypress="return !isNumber(event)" required>
<label id="labemail">E-mail</label><input type ="text" name="email" id="email" onblur="validateEmail(this)" required><br/><br/>
<label for="address" id="labaddr">* Address</label>
<textarea rows="4" cols="25" id="address" name="address" required></textarea>
<label id="labcountry">Country</label>
<select id="country" name="country">
<option value=""></option>
<option value="Lebanon">Lebanon</option>
<option value="UAE">UAE</option>
<option value="United States">United States</option>
<option value="France">France</option>
<option value="Italy">Italy</option>
</select><br/><br/>
<label id="labphone">* Phone</label><input type="text" name="phone" id="phone" onkeypress="return isNumber(event)" onblur="validPhone()" required>
<label id="labcity">City</label><input type="text" name="city" id="city" onkeypress="return !isNumber(event)" required><br><br>
<br><br>
<table id="orderTable">
<th colspan="4">Order Details</th>
<tr id="first">
<td>Item</td>
<td>Quantity</td>
<td>Unit Price</td>
<td>Total</td>
</tr>
<tr>
<td id="item">Item1</td>
<td><input onblur="findTotal(1)" class="item" type="text" name="quantity" id="quantity" onkeypress="return isNumber(event)"/></td>
<td><input onblur="findTotal(1)" class="item" type="number" min="0" step="0.01" name="price" id="price" onkeypress="return isNumber(event)"/></td>
<td><input onblur="totals()" class="item" type="text" name="total" id="total" readonly></td>
</tr>
<!--
<tr>
<td id="item">Item2</td>
<td><input onblur="findTotal(2)" type="text" name="quantity" id="quantity" onkeypress="return isNumber(event)"/></td>
<td><input onblur="findTotal(2)" type="text" name="price" id="price" onkeypress="return isNumber(event)"/></td>
<td><input onblur="totals()" type="text" name="total" id="total" readonly></td>
</tr>
<tr>
<td id="item3">Item3</td>
<td><input onblur="findTotal(3)" type="text" name="val3" id="qt3" onkeypress="return isNumber(event)"/></td>
<td><input onblur="findTotal(3)" type="text" name="val3" id="price3" onkeypress="return isNumber(event)"/></td>
<td><input onblur ="totals()" type="text" name="total" id="total3" readonly></td>
</tr> -->
<tr>
<td id="colshipping">Shipping Method</td>
<td colspan="2">
<select id="shipping" name="shipping">
<option value="empty"></option>
<option value="USPS Express Mail">USPS Express Mail</option>
<option value="USPS Priority Mail">USPS Priority Mail</option>
<option value="DHL">DHL</option>
<option value="FedEx">FedEx</option>
</select>
</td>
<td><input type="text" id="fee" onblur="totals()" readonly></td>
</tr>
<tr>
<td id="coldis">Discount</td>
<td colspan="2"><input onchange="totals()" type="text" name="discount" id="discount" onkeypress="return isNumber(event)" required> %</td>
<td><input type="text" onchange="totals()" id="amount" name="amount" readonly></td>
</tr>
<tr>
<td id="coltotal" colspan="3">Total</td>
<td><input type="text" name="totalPrice" id="totprice" readonly></td>
</tr>
</table>
<br>
<input type="submit" id="sub" value="Submit">
</form>
</body>
</html>
My problem is whenever I fill-in the information in "form.jsp", "clientdetails.jsp" opens and shows me the details I entered except the list element, it keeps showing as empty. I'm not sure how to be able to connect between the item class and client class to be able to display the Item1 instance in list. They told me that maybe I should do some modifications in setItem(Item item) method by how?
Please any hint or advice might help me a lot! Thank you!
In below method,
public void setItem(Item item) {
list.add(this.item);
}
Why are you doing list.add(this.item); ? shouldn't it be list.add(item);?
Change it to list.add(item); .

Download CSV file from database using Spring MVC and Hibernate

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;
}
}

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>

Categories

Resources