I 'm a beginer with spring framework. I insert an image to postgresql database and i want to display it.
the model class is:
#Data
#Entity
#Table(name="Item")
public class Item {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private byte[] imageTo_display;
private Long price;
#ManyToOne
private Cart cart;
}
I think the problem is at image tag but i don't know how to solve it .
and the html is:
<th:block th:each="item:${listItems}">
<tr>
<td>[[${item.id}]]</td>
<td>[[${item.name}]]</td>
<td>[[${item.price}]]</td>
<td> <img class="s-ava-alone-img" width="150" height="150" th:src="#{${item.imageTo_display}}"></td>
</tr>
<td>
<a class="h4 mr-3" th:href="#{'/users/edit/'+${item.id}}">Edit</a>
<a class="h4 mr-3" th:href="#{'/users/delete/' +${item.id}}">Delete</a>
</td>
</th:block>
The way you should do this is:
Create a controller that just returns the byte[] array of the image:
#GetMapping(value = "/image/{id}")
public void view(HttpServletResponse response, #PathVariable(name="id") int id) throws Exception {
response.setHeader("content-type", "image/jpg");
Item item = ...; // Get the item based on id;
OutputStream o = response.getOutputStream();
o.write(item.imageTo_display);
o.close();
}
Link to your image on the page:
<th:block th:each="item: ${listItems}">
<tr>
<td th:text="${item.id}" />
<td th:text="${item.name}" />
<td th:text="${item.price}" />
<td><img class="s-ava-alone-img" width="150" height="150" th:src="#{/image/{id}(id=${item.id})}"></td>
</tr>
<td>
<a class="h4 mr-3" th:href="#{/users/edit/{id}(id=${item.id})}">Edit</a>
<a class="h4 mr-3" th:href="#{/users/delete/{id}(id=${item.id})}">Delete</a>
</td>
</th:block>
Related
What I want to do is a parametrized report, i would love to use SSRS or other fancy tools for this but it's sort of dangerous at this point because i don't really want to mess around with the company server and I dont have much time; Also If it's a tool it should be a free and light tool and i didn't find one by now.
So, my idea is making a simple controller with Index that will return a List to View according to parameters and the View will use that ViewModel as Model then the users can export that list to CSV or PDF, the problem is: MVC is asking for a real db model to complete the scaffolding, how can this be done then?
Controller (I call an stored proc here)
public class ReporteEntregasPresentacionController : Controller
{
private EntregaMedicamentosEntities db = new EntregaMedicamentosEntities();
public ActionResult Index(DateTime DateFrom, DateTime DateTo)
{
ReporteEntregasPresentacionViewModel rep = new ReporteEntregasPresentacionViewModel();
string sqlQuery = "[dbo].[spEntregasPorPresentacion] ({0},{1})";
Object[] parameters = { DateFrom, DateTo };
rep.LstEntregasPresentacionViewModel = db.Database.SqlQuery<ItemEntregasPresentacionViewModel>(sqlQuery, parameters).ToList();
return View(rep);
}
}
ViewModel:
public class ReporteEntregasPresentacionViewModel
{
public int index;
public List<ItemEntregasPresentacionViewModel> LstEntregasPresentacionViewModel;
}
public class ItemEntregasPresentacionViewModel {
public string idProducto { get; set; }
public string Descripcion { get; set; }
public string EntregasTotales { get; set; }
}
I don't have a View now but i should be something like this:
#model EntregaMedicamentos.Models.ReporteEntregasPresentacionViewModel
<link href="~/Content/css/styles.css" rel="stylesheet" />
#{
ViewBag.Title = "ReporteEntregasPresentacion";
}
<h2>ReporteEntregasPresentacion</h2>
#using (Html.BeginForm("Index", "Entrega", FormMethod.Post))
{
<div class="card text-white bg-secondary">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<div class="input-group">
#Html.TextBox("DateFrom", ViewBag.currentFilter1 as DateTime?, new { #class = "form-control", placeholder = "Desde fecha", #readonly = "true", type = "datetime" })
#Html.TextBox("DateTo", ViewBag.currentFilter2 as DateTime?, new { #class = "form-control", placeholder = "Hasta fecha", #readonly = "true", type = "datetime" })
<button id="Submit4" type="submit" style='font-size:22px ;color:blue'><i class='fas fa-search'></i></button>
</div>
</div>
</div>
</div>
</div>
}
<br>
<table class="table table-striped ">
<tr class="table-primary">
<th>
Código
</th>
<th>
Producto
</th>
<th>
Entregas Totales
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.idProducto)
</td>
<td>
#Html.DisplayFor(modelItem => item.Descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Valor)
</td>
</tr>
}
</table>
I ended up creating a real table/model and then it worked fine with the viewmodel. Thanks.
I have some very strange problem with displaying of error messages after redirect. I use RedirectAttributes to pass BindingResult object with error messages to a view, but this solution doesn't work.
When I return just a view name withou redirect, everything works fine.
Can someone give an advice, but without session usage?
#Controller
public class UserRegistrationController {
#Autowired
private UserService userService;
#RequestMapping(value="/registration", method=RequestMethod.GET)
public ModelAndView registrationPage() {
ModelAndView modelAndView = new ModelAndView("user-registration/registration-form");
modelAndView.addObject("user", new User());
return modelAndView;
}
#RequestMapping(value="/registration", method=RequestMethod.POST)
public ModelAndView registerUser(#ModelAttribute #Valid User user,
BindingResult result,
final RedirectAttributes redirectAttributes) {
ModelAndView modelAndView = new ModelAndView("redirect:registration.html");
User tempUser = userService.get(user.getEmail());
Map<String, String> messages = new HashMap<String, String>();
if (tempUser == null && ! result.hasErrors()) {
userService.save(user);
messages.put("success", "message.user.success.register");
} else {
messages.put("error", "message.user.invalid.register");
redirectAttributes.addFlashAttribute("user", user);
redirectAttributes.addFlashAttribute("errors", result);
}
redirectAttributes.addFlashAttribute("messages", messages);
return modelAndView;
}
}
And the view code:
<p>
<c:forEach var="message" items="${messages}">
<span class="${message.key}"><spring:message code="${message.value}" /></span><br />
</c:forEach>
</p>
<form:form method="POST" commandName="user" action="${pageContext.request.contextPath}/registration.html">
<table>
<tbody>
<tr>
<td><spring:message code="user.registration.email" /></td>
<td><form:input path="email" /></td>
<td><form:errors cssClass="error" path="email" /></td>
</tr>
<tr>
<td><spring:message code="user.registration.password" /></td>
<td><form:password path="password" /></td>
<td><form:errors cssClass="error" path="password" /></td>
</tr>
<tr>
<td><input type="submit" /></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
Might want to look at this:
https://jira.springsource.org/browse/SPR-8968
And try returning a String rather than a ModelAndView
There should really be no reason to redirect while there are errors remain on the same page and only on success redirect. The reason for redirecting has to do with ensuring the browser does not attempt to repeat the same form submission when the back button is used, but while input is invalid the simplest thing to do is remain on the same page.
In my scenario, i'm developing nested select on a JSP, binded to a bean:
Bean
public class WizardPanelp1Bean {
private Integer id;
private Stringofpanels stringofpanels;
private Paneltype paneltype;
private Integer number;
private String paneltypestring;
//and getters/setters... [Omitted]
Now i have the Paneltype object, another simple bean
Paneltype
private Integer id;
private double peakpower;
private double weight;
private String name;
private double dimension;
private double conversion;
private Set functions = new HashSet(0);
private Set sensors = new HashSet(0);
private Set panels = new HashSet(0);
//[Getters/setters omitted as usual]
So, i prepare the view, with a bean named wb
a simple arraylist of panels
public class PanelsBean {
private ArrayList<WizardPanelp1Bean> panels =new ArrayList<WizardPanelp1Bean>();
and finally i go to the jsp (please note this is in a )
<tbody>
<c:forEach items="${wb.panels}" varStatus="loop" var="item">
<tr>
<td>${item.id}</td>
<td>
<form:select path="panels[${loop.index}].paneltype" >
<c:forEach var="type" items="${types}">
<c:choose>
<c:when test="${item.paneltype.id==type.id}">
<form:option selected="selected" value="${type.id}" label="${type.name}" />
</c:when>
<c:otherwise>
<form:option value="${type.id}" label="${type.name}" />
</c:otherwise>
</c:choose>
</c:forEach>
</form:select>
</td>
<td><form:input style="width:180px" path="panels[${loop.index}].number" /></td>
<td>
<div>
<form:input style="visibility: hidden ; width:0px" path="panels[${loop.index}].id" disabled="disabled" />
<a href="javascript:remove(${item.id},${stringofpanels.id})" class="wb.panels.remove" >Rimuovi</a>
</div>
</td>
</tr>
</c:forEach>
</tbody>
every time i get a null reference to paneltype. I obviously used a #InitBinder on the controller:
Initbinder
#InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Paneltype.class, "paneltype", new PropertyEditorSupport() {
#Override
public void setAsText(String text) {
int i=0;
PaneltypeDAO pDAO=new PaneltypeDAO();
setValue(pDAO.findById(Integer.parseInt(text)));
}
});
}
but the code never reach this. It's like the jsp is sure that the value is null.
Suggestions? Thanks
I think your problem persists when you try to submit this form and not getting the binded values in the model.
Try to initialize your list using LazyList. Please replace your panels declaration in PanelsBean class as below.
private List<WizardPanelp1Bean> panels = LazyList.decorate(new ArrayList<WizardPanelp1Bean>(),FactoryUtils.instantiateFactory(WizardPanelp1Bean.class));
Hope this helps you. Cheers.
I have an issue binding the AutoPupulating List in a form to update the data. I was able to save the data using Autopopulating list though.
Here is the form backing model.
public class AddUpdateShot {
private Integer shootId;
private char shotSelect;
private String shotNotes;
private Integer numOfItems;
private AutoPopulatingList itemNumColors;
private Integer totalNumOfItems;
private String shotName;
----------
public void setItemNumColors(AutoPopulatingList itemNumColors){
this.itemNumColors = itemNumColors;
}
public AutoPopulatingList getItemNumColors(){
return this.itemNumColors;
}
--------
}
Where itemNumClors is a simple model
public class ItemNumColor {
private Integer id;
private Integer itemNum;
private String itemName;
private String colorCode;
private String colorName;
------get and set methods
}
When I first saved the data, depending on how many ItemColors the user wanted,using jquery I added the input fields dynamically as shown in the following code.
<form:form id="createShootForm" method="POST"
commandName="createShoot">
<tr>
<td align="left"><label for="shootName">*Shoot Name:</label></td>
<td><form:input id="shootName" class="required" path="shootName" /></td>
</tr>
------- other input fields in form backing obj----
<c:forEach var="i" begin="${start}" end="${end-1}" step="1" varStatus="status">
<tr>
<td align="left"><label for="itemNumber${i}">Item
Number${i+1}:</label></td>
<td><form:input id="itemNumber${i}"
path="createShoot.itemNumColors[${i}].itemNum" /></td>
<td><form:select id="color${i}"
path="createShoot.itemNumColors[${i}].colorCode">
<form:option value="" label="Color" />
</form:select>
</td>
</tr>
</c:forEach>
<tr id="submitRow">
<td></td>
<td></td>
<td align="right"><input name="submit" type="submit" value="Next" /></td>
</tr>
</table>
</form:form>
The above code worked perfectly fine when I initially saved the data. But now when the user want to update the earlier saved data, I am unable to bind the Autopopulating list to the JSP. Here is how am doing it.
<form:form id="updateShotForm" method="POST"
commandName="shotToUpdate">
----other input fields of form backing object---
<c:forEach var="i" begin="0" end="${totalNumOfItems-1}" step="1"
varStatus="status">
<tr><td align="left"><label for="itemNumber${i}">ItemNumber${i+1}:</label></td>
<td><form:input id="itemNumber${i}"path="shotToUpdate.itemNumColors[${i}].itemNum" /></td>
</tr>
</c:forEach>
<tr id="submitRow">
<td></td>
<td></td>
<td align="right"><input name="submit" type="submit"
value="Next" />
</td>
</table>
</form:form>
When I open the edit JSP, I get the following run time exception
Sep 7, 2011 10:38:00 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jalapeno] in context with path [/OnLocation] threw exception [An exception occurred processing JSP page /WEB-INF/views/app/updateShot.jsp at line 256
253: <tr>
254: <td align="left"><label for="itemNumber${i}">Item
255: Number${i+1}:</label></td>
256: <td><form:input id="itemNumber${i}"
257: path="shotToUpdate.itemNumColors[${i}].itemNum" /></td>
258: <td><form:select id="color${i}"
259: path="shotToUpdate.itemNumColors[${i}].colorCode">
Stacktrace:] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'shotToUpdate' of bean class [com.jcrew.jalapeno.app.model.AddUpdateShot]: Bean property 'shotToUpdate' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707)
at org.springframework.beans.BeanWrapperImpl.getNestedBeanWrapper(BeanWrapperImpl.java:555)
at org.springframework.beans.BeanWrapperImpl.getBeanWrapperForPropertyPath(BeanWrapperImpl.java:532)
at org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:697)
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:98)
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:224)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:120)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:160)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:123)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:408)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:140)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)
I am not sure why I am not able to bind the object this way to the form since my form backing object does have an Autopopulating List which I initialised in the controller before loading this form
AutoPopulatingList itemNumColors = new AutoPopulatingList(ItemNumColor.class);
for( OnLocShotItemNumber onLocItemNumColor : itemNumColorsList){
ItemNumColor itemColor = new ItemNumColor();
itemColor.setId(onLocItemNumColor.getId());
itemColor.setColorCode(onLocItemNumColor.getItemColorCode());
itemColor.setItemNum(onLocItemNumColor.getItemNumber());
itemNumColors.add(itemColor);
}
shotToUpdate.setItemNumColors(itemNumColors);
model.put("shotToUpdate", shotToUpdate);
model.put("totalNumOfItems", itemNumColorsList.size());
Any help is greatly appreciated.
Thanks,
Shravanthi
Remove the 'shotToUpdate.' keyword from the PATH attribute. You have already specified the command object name so the PATH attributes should be relative to the command object.
my code is
<% using (Html.BeginForm())
{%>
<table>
<tr>
<th>
LabelID_FK
</th>
<th>
LabelName
</th>
<th>
LabelIsDocument
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td>
<%: item.LabelID_FK %>
</td>
<td>
<%: item.LabelName %>
</td>
<td>
<%-- <input type="checkbox" value="df" id="chk" onclick="check()" />--%>
<%=Html.CheckBox("chk_"+ item.LabelID_FK)%>
</td>
</tr>
<% } %>
</table>
<p>
<input type="button" value="submit" id="btn" />
</p>
which show checkbox list for document label which user can select it .
i want pass data list which user select checkbox it use jquery post
what i do?
i use this code when user click on button and work very good
[HttpPost]
public ActionResult DocumentLabel(FormCollection model)
{
for (int i = 0; i < model.Count; i++)
{
AriaCRMEntities aria = new AriaCRMEntities();
DocumentLabel label = new DocumentLabel();
string lbl = model[i].ToString();
string[] check = lbl.Split(',');
bool chk = Convert.ToBoolean(check[0]);
string name = model.Keys[i].ToString();
string[] n = name.Split('_');
string lblid = n[1];
if (chk)
{
label.LabelID_FK = Int32.Parse(lblid);
Guid id = Guid.NewGuid();
label.DocumentID_FK = id;
aria.DocumentLabels.AddObject(label);
aria.SaveChanges();
}
}
return Content("0ok");
}
but i want jquery post i need array check box whit select it to pass it to controller?