Data not loading on the first load changing perspective (Hybris) - widget

I've made a custom backoffice widget which I can access by clicking the new Order Cockpit item added in the option perspectives tree. This will show different graphs with data in it.
But for some reason the data doesn't load on the first load, but when refreshing the page it works perfect. Is there any way to configure to refresh or re-init the widget when clicking the Order Cockpit item in the option tree?
widgetdefinition.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
Copyright (c) 2020 SAP SE or an SAP affiliate company. All rights reserved
-->
<widget-definition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.hybris.com/schema/cockpitng/widget-definition.xsd"
id="org.training.widgets.customGraphWidget">
<name>customGraph Sample Widget</name>
<description>customGraph Sample Widget</description>
<defaultTitle>customGraph Sample Widget</defaultTitle>
<author>DucVan</author>
<version>1.0</version>
<view src="customGraphWidget.zul" />
<keywords>
<keyword>graphbackoffice</keyword>
</keywords>
<controller class="org.training.widgets.customGraphController" />
</widget-definition>
widgetController
package org.training.widgets;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hybris.cockpitng.core.model.WidgetModel;
import org.training.services.customGraphService;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import com.hybris.cockpitng.util.DefaultWidgetController;
import java.util.List;
public class customGraphController extends DefaultWidgetController {
private static final long serialVersionUID = 7954736389190109887L;
#WireVariable
private transient customGraphService customGraphService;
#Override
public void preInitialize(Component comp) {
super.preInitialize(comp);
WidgetModel model = getWidgetInstanceManager().getModel();
model.put("orders", convertAllOrderModelsToJSON());
}
private Object convertAllOrderModelsToJSON() {
//get all the models
List list = customGraphService.getAllOrdersModels();
//convert models to JSON
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(list);
return json;
}
}
zul page
<?xml version="1.0" encoding="UTF-8"?>
<widget xmlns="http://www.zkoss.org/2005/zul"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:w="http://www.zkoss.org/2005/zk/client"
xmlns:zk="http://www.zkoss.org/2005/zk"
xsi:schemaLocation="http://www.zkoss.org/2005/zul http://www.hybris.com/schema/cockpitng/zul/zul.xsd"
height="100%">
<html>
<h:head>
<h:script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.6.0/chart.js"
integrity="sha512-CWVDkca3f3uAWgDNVzW+W4XJbiC3CH84P2aWZXj+DqI6PNbTzXbl1dIzEHeNJpYSn4B6U8miSZb/hCws7FnUZA=="
crossorigin="anonymous" referrerpolicy="no-referrer" defer="true"/>
<h:script>const orders = [${widgetModel.orders}][0];</h:script>
<h:script defer="true" src="widgetClasspathResource/widgets/customGraphWidget/graphConfiguration.js?v=1"/>
</h:head>
<h:body>
<h:div style="height: 100%; width: 80%; margin: auto; overflow: hidden;">
<h:div style="background-color: white;height:35%;margin: 40px auto auto
;padding:20px;border: 2px solid #d7dee5">
<h:canvas id="lineChart1"></h:canvas>
</h:div>
<h:div style="background-color: white;width: 30%;height:35%;margin: 30px auto auto 0px
;padding:20px;border: 2px solid #d7dee5;float: left">
<h:canvas id="pieChart1"></h:canvas>
</h:div>
<h:div style="background-color: white;width: 60%;height:35%;margin: 30px 0px auto auto
;padding:20px;border: 2px solid #d7dee5">
<h:canvas id="barChart1"></h:canvas>
</h:div>
</h:div>
</h:body>
</html>
</widget>

Related

How to Update a record in spring boot and mysql

I am a newbie to spring boot.I have created a crud operation and the insert operation is working properly. I have a challenge on the update operation , the program is giving an error on the web page
Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.Wed Jul 22 20:39:03 CAT 2020 There was an unexpected error (type=Bad Request, status=400)
and the following error from the console
Resolved [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'long'; nested exception is java.lang.NumberFormatException: For input string: "saveEmployee"]
how can I solve the problem?
my code is below
Controller Class
```
package com.zimprogrammer.springboot.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.zimprogrammer.springboot.model.Employee;
import com.zimprogrammer.springboot.service.EmployeeService;
#Controller
public class EmployeeController {
#Autowired
private EmployeeService employeeService;
#GetMapping("/")
public String vieHomePage(Model model) {
// this shows a list of employees
model.addAttribute("listEmployees", employeeService.getAllEmployees());
return "index";
}
#GetMapping("/showEmployeeForm")
public String showEmployeeForm(Model model){
//request for the form to enter the data
Employee employee =new Employee();
model.addAttribute("employee", employee);
return "new_employee";
}
#PostMapping("/saveEmployee")
public String saveEmployee(#ModelAttribute("employee") Employee employee) {
//save data to the database
employeeService.saveEmployee(employee);
return "redirect:/";
}
#GetMapping("/showFormForUpdate/{id}")
public String showFormForUpdate(#PathVariable( value="id") long id, Model model) {
//get the employee from the service
Employee employee =employeeService.getEmployeeById(id);
// set the employee to pre-populate the form
model.addAttribute("employee", employee);
return "update_employee";
}
}```
Employee Service Interface
```package com.zimprogrammer.springboot.service;
import java.util.List;
import com.zimprogrammer.springboot.model.Employee;
public interface EmployeeService {
List<Employee> getAllEmployees();
void saveEmployee(Employee employee);
Employee getEmployeeById(long id);
}
```
Employee Service Class
```
package com.zimprogrammer.springboot.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zimprogrammer.springboot.model.Employee;
import com.zimprogrammer.springboot.repository.EmployeeRepository;
#Service
public class EmployeeServiceImpl implements EmployeeService{
#Autowired
private EmployeeRepository employeeRepository;
#Override
public List<Employee> getAllEmployees() {
return employeeRepository.findAll();
}
#Override
public void saveEmployee(Employee employee) {
this.employeeRepository.save(employee);
}
#Override
public Employee getEmployeeById(long id) {
Optional<Employee> optional=employeeRepository.findById(id);
Employee employee=null;
if(optional.isPresent()) {
employee=optional.get();
}else {
throw new RuntimeException("User not found for id::" + id);
}
return employee;
}
}
```
Employee Repository Interface
```
package com.zimprogrammer.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.zimprogrammer.springboot.model.Employee;
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}
```
Update Form : Thymeleaf and bootstrap
```
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>Employee Management System</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<div class="container" style="width:40%; height:40%;">
<h1>Employee Management system</h1>
<hr>
<h2>Update Employee</h2>
<form action="#" th:action="#{saveEmployee}" th:object="${employee}"
method="POST">
<input type="hidden" th:field="*{id}" />
<input type="text" th:field="*{firstName}"
class="form-control mb-4 col-4">
<input type="text" th:field="*{lastName}"
class="form-control mb-4 col-4">
<input type="text" th:field="*{email}"
class="form-control mb-4 col-4">
<button type="submit" class="btn btn-info col-2">Update
Employee</button>
</form>
<hr>
<a th:href = "#{/}"> Back to Employee List</a>
</div>
</body>
</html>
```
Can you also post you entity class?
From the error it is telling that the required type is long but it is getting it as string? It may be possible that you have mentioned your id as string instead of long.
Also try to add th:action="#{/saveEmployee}" to be exact as that of your /saveEmployee endpoint
Add "/" in form th:action, like so -> th:action="#{/saveEmployee}"
Also check your crud repository, insted of long use Long.
I solved the problem
I added a / to make th:action="#{/saveEmployee}" and changed long to Long in my controller Class in the following request
#GetMapping("/showFormForUpdate/{id}")
public String showFormForUpdate(#PathVariable( value="id") Long id, Model model) {
//get the employee from the service
Employee employee =employeeService.getEmployeeById(id);
// set the employee to pre-populate the form
model.addAttribute("employee", employee);
return "update_employee";
}
and this solved the problem

How to print values present in <nobr> tag using selenium webdriver

it would be really helpful if someone could point out to me in the right direction.
I am trying to print values which are present in nobr tag.
this is my code.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
public class appannieuserrating {
public static WebDriver driver;
#Test
public void f() throws Exception{
driver.findElement(By.id("login-button")).click();
driver.findElement(By.id("username")).sendKeys("sample.test#gmail.com");
driver.findElement(By.id("password")).sendKeys("password");
driver.findElement(By.id("login_submit_button")).click();
Thread.sleep(5000);
driver.navigate().to("https://www.appannie.com/apps/ios/app/storage-hunters-uk-the-game/reviews/?date=2015-07-06~2015-07-06");
Thread.sleep(5000);
String s1 = driver.findElement(By.cssSelector(".ngCellText.cell-inner.ng-scope")).findElement(By.tagName("img")).getAttribute("src");
System.out.println(s1);
}
#BeforeTest
public void beforeTest() {
driver = new FirefoxDriver();
driver.get("https://www.appannie.com/");
}
#AfterTest
public void afterTest() {
}
}
<div class="ngCanvas" ng-style="canvasStyle()" style="height: 467px;">
<div class="ng-scope ngRow even" ng-row="" ng-class="row.alternatingRowClass()" ng-click="row.toggleSelected($event)" ng-repeat="row in renderedRows" ng-style="rowStyle(row)" style="top: 0px; height: 58px;">
<div class="ngCell col0 colt0" ng-class="{'sorted': col.sortDirection}" ng-repeat="col in renderedColumns" style="height: 58px;">
<div class="ngVerticalBar ngVerticalBarVisible" ng-class="{ ngVerticalBarVisible: !$last }" ng-style="{height: rowHeight}" style="height: 58px;"> </div>
<div ng-cell="">
<div class="ngCellText cell-inner ng-scope">
<span stars="row.getProperty(col.field)" aa-stars="">
<nobr>
<img alt="*" src="/media/pictures/star-whole.png">
<img alt="*" src="/media/pictures/star-whole.png">
<img alt="*" src="/media/pictures/star-whole.png">
<img alt="*" src="/media/pictures/star-whole.png">
<img alt="*" src="/media/pictures/star-whole.png">
</nobr>
</span>
</div>
</div>
</div>
Here am trying to count the number of stars present in the "nobr" tag somehow its printing null value.
kindly point me in the right direction guys.
I would do smth like this:
List<WebElement> elements = driver.findElement(By.xpath("//span[#aa-stars]/nobr")).findElements(By.tagName("img"));
int counter = 0;
for(WebElement we: elements) {
if("*".equals(we.getAttribute("alt"))) {
counter++;
}
}
System.out.println(counter);
Unfortunately, your password is incorrect so I cannot try myself :D :D Tried locally with the same html - should work.
UPD:
I forgot to tell - in your attempt to find img element - you ignored the nobr. Yes. It is in DOM too. If you want to find ANY next img - do like this:
.findElement(By.xpath("//img"));
If you use by tagName - it is assumed that you search for direct child.
UPD 2
If you rely on src and believe that this img should be a star, consider this:
for(WebElement we: elements) {
String text = we.getAttribute("src");
if(text!=null) {
if(text.contains("star"){
counter++;
}
}
}
UPD 3
List<WebElement> elements = driver.findElement(By.xpath("//span[#aa-dtars]/nobr")).findElements(
By.tagName("‌​img"));
int counter = 0;
String starPicLink = "/media/pictures/star-whole.png";
for (WebElement we : elements) {
String text = we.getAttribute("src");
if (starPicLink.equals(text)) {
counter++;
}
}
System.out.println(counter + " Star");
UPD 4
pastie.org/10292596#34 - working version
I tried something link below to identify a input tag inside nobr tag:
xpath=//div[#id='div0_17']/span[#id='outer0_366']/nobr/input

Can I use a jsp:include to include an entire JSP page as tab content?

I'm trying to define JSP pages as content for my tabs using the "jsp:include" - like this (Note: "page0.jsp")...
<ul id="smTabs" class="nav nav-tabs" style="margin-bottom: 15px;">
<li class="active">
Page0
</li>
-
-
-
<div id="smTabContent" class="tab-content">
<div class="tab-pane fade active in" id="page0">
<jsp:include page="page0.jsp" />
</div>
The problem:
When the user clicks on a tab, the "included" (i.e., "jsp:include") JSP page form fields are empty because the controller has not been initialized.
QUESTION:
What "href=" value will succeed in both revealing the tab contents (e.g., page0.jsp) and, as well, initialize the controller so the page is displayed properly with data?
Thanks for any help.
Here's what the empty form for page0.jsp looks like...
Here is what it should look like...
BELOW IS EXTRA INFORMATION IF INTERESTED...
Here is the tabbedPage.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<br/><br/><br/>
<div class="page-header"><h1>Tabbed Page Management</h1></div>
<div class="bs-component">
<ul id="smTabs" class="nav nav-tabs" style="margin-bottom: 15px;">
<li class="active">
Page0
</li>
<li>
Page1
</li>
<li>
Page2
</li>
</ul>
<div id="smTabContent" class="tab-content">
<div class="tab-pane fade active in" id="page0">
<h4>${page0FormBean}</h4>
<jsp:include page="page0.jsp" />
</div>
<div class="tab-pane fade" id="page1">
<h4>${page1FormBean}</h4>
<jsp:include page="page1.jsp" />
</div>
<div class="tab-pane fade" id="page2">
<h4>${page2FormBean}</h4>
<jsp:include page="page2.jsp" />
</div>
</div>
</div>
here is the controller for "tabbedPage.jsp"...: TabbedPageController.java
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
#Scope("session")
public class TabbedPageController
{
private static final Logger LOG = Logger.getLogger("TabbedPageController");
#RequestMapping(value = {"/tabbedPage"}, method = RequestMethod.GET)
public String tabbedPage(ModelMap model, HttpSession session)
{
LOG.info("_________________________tabbedPage_________________________entering...");
return "tabbedPage";
}
}
Here is page0.jsp (one of the JSP pages included...i.e., via "jsp:include")
<%#taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<br/><br/><br/>
<div class='panel panel-primary'>
<div class='panel-heading'>
<h2 class='panel-title'>Page0</h2>
</div>
</div>
<form:form id="page0Form" modelAttribute="page0FormBean" method="post">
<div class="form-group row-fluid">
<label class='col-xs-6 control-label' for='formFieldA'>Page0's Form Field A</label>
<div class='col-xs-6'>
<input class='form-control' type='text' id='formFieldA' value='${page0FormBean.formFieldA}' />
</div>
</div>
<div class="form-group row-fluid">
<label class='col-xs-6 control-label' for='formFieldB'>Page0's Form Field B</label>
<div class='col-xs-6'>
<input class='form-control' type='text' id='formFieldB' value='${page0FormBean.formFieldB}' />
</div>
</div>
<div class="form-group row-fluid">
<label class='col-xs-6 control-label' for='formFieldC'>Page0's Form Field C</label>
<div class='col-xs-6'>
<input class='form-control' type='text' id='formFieldC' value='${page0FormBean.formFieldC}' />
</div>
</div>
</form:form>
here is the controller for "page0.jsp"...: Page0Controller.java
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.apache.log4j.Logger;
import java.io.Serializable;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
#Controller
#Scope("session")
public class Page0Controller implements Serializable
{
private static final Logger LOG = Logger.getLogger("Page0Controller");
private static final long serialVersionUID = 1602123387257827883L;
#RequestMapping(value = "/page0", method = RequestMethod.GET)
public ModelAndView page0(ModelMap model)
{
LOG.info("____________________page0___________________entering...");
Page0FormBean page0FormBean = new Page0FormBean("page0fieldavalue", "page0fieldbvalue", "page0fieldcvalue");
model.addAttribute("page0FormBean", page0FormBean);
return new ModelAndView("tabbedPage", "page0FormBean", page0FormBean);
}
}
here is the "form bean" used by "page0.jsp"...: Page0FormBean.java
public class Page0FormBean
{
private String formFieldA;
private String formFieldB;
private String formFieldC;
public Page0FormBean(String formFieldA, String formFieldB, String formFieldC)
{
this.formFieldA = formFieldA;
this.formFieldB = formFieldB;
this.formFieldC = formFieldC;
}
public String getFormFieldA()
{
return formFieldA;
}
public void setFormFieldA(String formFieldA)
{
this.formFieldA = formFieldA;
}
public String getFormFieldB()
{
return formFieldB;
}
public void setFormFieldB(String formFieldB)
{
this.formFieldB = formFieldB;
}
public String getFormFieldC()
{
return formFieldC;
}
public void setFormFieldC(String formFieldC)
{
this.formFieldC = formFieldC;
}
#Override
public String toString()
{
return "Page0FormBean{" + "formFieldA=" + formFieldA + ", formFieldB=" + formFieldB + ", formFieldC=" + formFieldC + '}';
}
}
I've arrived at a solution for now. - Hopefully, the Spring MVC mavens will chime in if they have a better approach
Essentially, I am using a session scope variable: "tabno". -I use "tabno" in the JSP page to control the active tab, etc. (Note: the use of a ternary expression in EL)
Instead of href=#page0, I am instead using href=page1 to invoke the page0.jsp's controller.
-Page0Controller then passes control to TabbedPageController, and page0.jsp is displayed as "tab content' in tabbedPage.jsp.
Works for now.
Thanks
The tab JSP code looks like this...
-
-
-
<div class="bs-component">
<ul id="smTabs" class="nav nav-tabs" style="margin-bottom: 15px;"> <%-- <%pageContext.forward("page1.jsp");%> --%>
<li class="${sessionScope.tabno==0?'active':''}" >
Page0
</li>
<li class="${sessionScope.tabno==1?'active':''}" >
Page1
</li>
<li class="${sessionScope.tabno==2?'active':''}" >
Page2
</li>
</ul>
<div id="smTabContent" class="tab-content">
<div class="${sessionScope.tabno==0?'tab-pane fade active in':'tab-pane fade'}" id="page0">
<jsp:include page="page0.jsp" />
</div>
<div class="${sessionScope.tabno==1?'tab-pane fade active in':'tab-pane fade'}" id="page1">
<jsp:include page="page1.jsp" />
</div>
<div class="${sessionScope.tabno==2?'tab-pane fade active in':'tab-pane fade'}" id="page2">
<jsp:include page="page2.jsp" />
</div>
</div>
</div>
-
-
-
Page0Controller.java (associated with page0.jsp) looks like this... (you can see where I set the "tabno" value in a session attribute)...
#Controller
#Scope("session")
public class Page0Controller implements Serializable
{
private static final Logger LOG = Logger.getLogger("Page0Controller");
private static final long serialVersionUID = 1602123387257827883L;
#RequestMapping(value = "/page0", method = RequestMethod.GET)
public ModelAndView page0(ModelMap model, HttpSession session)
{
Page0FormBean page0FormBean = new Page0FormBean("page0fieldavalue", "page0fieldbvalue", "page0fieldcvalue");
model.addAttribute("page0FormBean", page0FormBean); //<== setting the "modelAttribute" that's used in page.jsp...
session.setAttribute("tabno", "0"); //<== setting "tabno" value here...
return new ModelAndView("tabbedPage", "page0FormBean", page0FormBean);
}
}
TabbedPageController.java (associated with tabbedPage.jsp) looks like this...
#Controller
#Scope("session")
public class TabbedPageController implements Serializable
{
private static final Logger LOG = Logger.getLogger("TabbedPageController");
private static final long serialVersionUID = 6570072463879652843L;
#RequestMapping(value = {"/tabbedPage"}, method = RequestMethod.GET)
public String tabbedPage(ModelMap model, HttpSession session)
{
return "tabbedPage";
}
}

Why does the <c:if> statement doesn't execute in the jsp? [duplicate]

This question already has answers here:
Can not find the tag library descriptor for “http://java.sun.com/jsp/jstl/core” [duplicate]
(18 answers)
Closed 7 years ago.
This is a Spring Web MVC project where I do input validation in server side. If there are any errors, then I add it to the model before sending it to the view.
Controller
#Controller("resultController")
public class ResultController {
private final ResultService resultService;
#Autowired
public ResultController(ResultService resultService) {
this.resultService = resultService;
}
// #RequestMapping(value = "/search", method = RequestMethod.GET)
#RequestMapping(value ="/template", method = RequestMethod.GET)
public String getPersonList(ModelMap model) {
System.out.println("We are coming into this place");
return "header";
}
#RequestMapping(value = "/number", method = RequestMethod.POST, params = { "regNo" })
public String getStudentResult(#RequestParam(value = "regNo", required = true) String regNo, ModelMap model){
//Server side validation
if(regNo.equals(null) || regNo.isEmpty()){
model.addAttribute("nullValue", "Register Number field cannot be empty");
return "header";
}else if(regNo.length() != 12 ){
System.out.println("This Sys out is shown");
model.addAttribute("invalidLength", new String("invalid"));
return "header";
}else{
model.addAttribute("studentResult",resultService.getStudentResult(regNo));
return "numberResult";
}
}
}
header.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<head>
<script src="http://code.jquery.com/jquery.min.js"></script>
<style>
#mycontainer, h1, h3 {
text-align:center;
}
form {
display:inline-block;
}
/* #regNoErrorMsgNumber {
display: none;
background: brown;
color: white;
} */
</style>
</head>
<body>
<div id="mycontainer">
<form method="post" action="number" id="number">
<!-- <div id="regNoErrorMsgNumber">Only numbers are allowed</div> -->
<div style="text-align: center;" >
<!-- //TODO: Only number, no spaces, no special symbol and 12 digit check-->
<input width="20" type="text" data-validation="numbers" id="regNo" name="regNo" size="30" maxLength="50" placeholder="Enter Register Number"> <b>OR</b>
<div>
<c:if test="${not empty nullValue}">
<c:out value="${nullValue}"/>
</c:if>
<c:if test="${not empty invalidLength}">
<c:out value="Register Number should be 12 digits"/>
</c:if>
</div>
</div>
</form>
<form method="post" action="name" id="name">
<input type="text" id="studentName" name="studentName" size="30" maxLength="50" placeholder="Enter Student Name"></input>
</form>
</div>
<div style="text-align: center;">
<input id="inputFields" type="button" value="Search" />
</div>
<!-- </form> -->
<script>
$(document).ready(function(){
$('#inputFields').click(function(event){
if (document.getElementById('regNo').value !=""){
$("#number").submit();
}else if(document.getElementById('studentName').value !=""){
$("#name").submit();
}
});
});
</script>
</body>
The following piece of jstl code in jsp doesn't work
<c:if test="${not empty invalidLength}">
<c:out value="Register Number should be 12 digits"/>
</c:if>
Also if I use the c:out statement without c:if tag, then it works. But it misaligns two input fields in UI. You can see the div mycontainer code in jsp. I want the error message to be shown below the regNo input field, but at the same time regNo and studetnName input field should be center aligned in a single line.
PS: I get Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core". Try increasing the version of the Dynamic Web Module project facet, as this method of reference may not be supported by the current JSP version (1.1)., but c:out tag with being wrapped with c:if works.
please try the following :
if you are using maven , add this to your dependencies and maven will add the jar for you :
<dependencies>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
if you are not using maven add the jstl library to your project (jstl-1.2.jar)
make sure you set a Targeted Runtime for your project , Tomcat , Glassfish , etc ...
and please refer to this question here .
for the errors part , use the <form:errors> from spring form tags :
- first add the following to your page :
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
then use the form:errors like the following :
<form:errors path="userName" cssClass="error" element="div" />
please refer to the following tutorials , here and here .
Hope that helps
I created a new class called ProjectErrors and I changed the code as follows
if(regNo.equals(null) || regNo.isEmpty()){
univErrors.setHasError(true);
model.addAttribute("isNull", univErrors );
}else if(Pattern.matches("[a-zA-Z]+", regNo)){
univErrors.setHasError(true);
model.addAttribute("onlyNumbers", univErrors );
}else if(regNo.length() != 12 ){
univErrors.setHasError(true);
model.addAttribute("length", univErrors );
}
I changed the jsp like this
<c:if test="${length.hasError}">
<c:out value="Register Number should be 12 digits."/>
</c:if>
<c:if test="${onlyNumbers.hasError}">
<c:out value="Register number can contain only digits."/>
</c:if>
And my error class looks like this
public class ProjectErrors {
public Boolean hasError;
public ProjectErrors(boolean b) {
// TODO Auto-generated constructor stub
hasError = b;
}
public Boolean getHasError() {
return hasError;
}
public void setHasError(Boolean hasError) {
this.hasError = hasError;
}
}
Now I see c:if tag working.
But, still get the warning in jsp "Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core". Try increasing the version of the Dynamic Web Module project facet, as this method of reference may not be supported by the current JSP version (1.1).",

Select tag always returns null

I am trying to create a search module to search shop details from database based on the criteria in select that user chooses
index.scala.html
#import helper._
#import helper.twitterBootstrap._
#main(Html("Home")) {
<!-- Main component for a primary marketing message or call to action -->
<div class="jumbotron">
<h1>Shop Directory</h1>
<p>Lets you search a nearby Shop and get to know their location</p>
<p>Search Shop by Product or Shop name</p>
<form class="form-inline" action="#routes.SearchController.search()" method="post">
<input type="text" class="form-inline input-lg" placeholder="Product/Shop name" name="keyword" required="keyword required">
<select class="form-inline input-lg" id="Select1" name="criteria">
<option value="">-:Select Criteria:- </option>
<option value="shop">Shop</option>
<option value="product">Product</option>
</select>
<button class="btn btn-lg btn-primary" role="button">Search</button>
</form>
</div>
}
Search.java
package viewmodels;
public class Search {
public String keyword;
public String criteria;
}
SearchResult.java
package viewmodels;
import models.Shop;
import play.mvc.Controller;
import java.util.ArrayList;
import java.util.List;
public class SearchResult extends Controller {
public String criteria;
public String keyword;
public List<Shop> shops;
public SearchResult() {
shops = new ArrayList();
}
}
SearchController.java
package controllers;
import models.Product;
import models.Shop;
import play.data.DynamicForm;
import play.data.Form;
import play.mvc.Controller;
import viewmodels.Search;
import viewmodels.SearchResult;
import java.util.List;
import play.mvc.Result;
import static play.data.Form.*;
public class SearchController extends Controller {
public static Result search() {
Form<Search> requestData = form(Search.class).bindFromRequest();
Search datatosearch = requestData.get();
// String criteria="shop";
String criteria = datatosearch.criteria;
SearchResult result = new SearchResult();
result.criteria = criteria;
result.keyword = datatosearch.keyword;
if (criteria == "shop") {
List<Shop> shops = Shop.findByShopName(datatosearch.keyword);
result.shops.addAll(shops);
}
else if (criteria == "product") {
List<Shop> shops = Product.findByShopName(datatosearch.keyword);
result.shops.addAll(shops);
}
return ok(views.html.search.results.render(result));
}
}
if I do String criteria="shop" or String criteria="product" in my SearchController.java then it works fine, meaning my model query is correct, but if I execute the above code with String criteria = datatosearch.criteria it shows a blank screen.
I am using play framework, I am really stuck at this and any help would be appreciated.
You are comparing strings with the == operator which is a no-no. Change your string comparisons to use String.equals so you are actually comparing the values instead of object references.
if (criteria.equals("shop") {
...
}
else if (criteria.equals("product") {
...
}
You probably also want to add some validation to check that criteria isn't NULL.