JSF forms strange behavior - forms

I have no idea why my forms behave in such way.
This is my JSF page:
<h:body>
<h:form>
<h:form>
<h:selectOneMenu value="#{productBean.product}" converter="#{productConverter}" validator="com.jsf.ProductAvailableValidator">
<f:selectItems value="#{productBean.pizza}" var="pizza" itemValue="#{pizza}" itemLabel="#{pizza.name}" />
<h:commandButton value="Dodaj" action="#{productBean.addToOrder(productBean.product.name)}" /></h:selectOneMenu>
</h:form>
<h:form>
<h:selectOneMenu value="#{productBean.product}" converter="#{productConverter}" validator="com.jsf.ProductAvailableValidator">
<f:selectItems value="#{productBean.drink}" var="drink" itemValue="#{drink}" itemLabel="#{drink.name}" />
<h:commandButton value="Dodaj" action="#{productBean.addToOrder(productBean.product.name)}" /></h:selectOneMenu>
</h:form>
<h:form>
<h:selectOneMenu value="#{productBean.product}" converter="#{productConverter}" validator="com.jsf.ProductAvailableValidator">
<f:selectItems value="#{productBean.other}" var="other" itemValue="#{other}" itemLabel="#{other.name}" />
<h:commandButton value="Dodaj" action="#{productBean.addToOrder(productBean.product.name)}" /></h:selectOneMenu>
</h:form>
<messages />
<h:outputText value="#{productBean.order}" />
<h:commandButton value="Wyczyść" action="#{ProductBean.clearOrder()}" /></h:form>
</h:body>
And this is my ProductBean:
#ManagedBean
#SessionScoped
public class ProductBean extends Connector
{
private List<Product> products;
private List<Product> pizza;
private List<Product> drink;
private List<Product> other;
boolean first = true;
private StringBuilder order = new StringBuilder();
public String getOrder() {
return order.toString();
}
private Product product;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public void addToOrder(String prod)
{
System.out.println("dodaje");
if(first)
{
first = false;
this.order.append(prod);
}
else
this.order.append(" + ").append(prod);
}
public void clearOrder()
{
this.order = null;
first = true;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public ProductBean() throws SQLException
{
resultSet = statement.executeQuery("SELECT * FROM dbo.products");
products = new ArrayList<Product>();
while(resultSet.next())
{
product = new Product();
product.setId_product(resultSet.getInt("id_product"));
product.setName(resultSet.getString("name"));
product.setCategory(resultSet.getInt("category_id"));
product.setIs_available(resultSet.getInt("is_available"));
products.add(product);
}
}
public Product getProductById(int id)
{
Iterator<Product> it = products.iterator();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getId_product() == id)
return prod;
}
return null;
}
public List<Product> getPizza() throws SQLException
{
Iterator<Product> it = products.iterator();
pizza = new ArrayList<Product>();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getCategory() == 1)
pizza.add(prod);
}
return pizza;
}
public List<Product> getDrink() throws SQLException
{
Iterator<Product> it = products.iterator();
drink = new ArrayList<Product>();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getCategory() == 2)
drink.add(prod);
}
return drink;
}
public List<Product> getOther() throws SQLException
{
Iterator<Product> it = products.iterator();
other = new ArrayList<Product>();
while(it.hasNext())
{
Product prod = it.next();
if(prod.getCategory() == 3)
other.add(prod);
}
return other;
}
public List<Product> getProducts() {
return products;
}
}
I also send a screenshot here to make code easier and faster to analize:
What happens here is that only the first button "Dodaj" (which means "add") works and add the String in outputlabel correctly. The rest of them do nothing. When I change the order, again only the first one works. Why?

You have multiple nested/cascaded <h:form>'s, that is not allowed in HTML! Either make one <h:form> and put all elements in that form, or make multiple <h:form>'s, but don't nest/cascade them!

Related

How can I pass object while navigating? [duplicate]

This question already has an answer here:
How pass parameter when navigate to another page (Shell)
(1 answer)
Closed 4 months ago.
I have main page on which I have collection view. I want to navigate to next page after I click submit button .I am able to navigate to the next page but I also want total list of items which I have in my collection how can I achieve that?
I don't know the detail of your code, but you can try to pass the total list of items as the parameter of the next page.(suppose it's name is SecondPage)
You can refer to the following code:
MainPage.cs
public partial class MainPage : ContentPage
{
MyViewModel myViewModel;
public MainPage()
      {
            InitializeComponent();
myViewModel = new MyViewModel();
BindingContext = myViewModel;
}
      private void mCollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)
      {
string previous = (e.PreviousSelection.FirstOrDefault() as MyModel)?.Name;
string current = (e.CurrentSelection.FirstOrDefault() as MyModel)?.Name;
}
private async void Button_Clicked(object sender, EventArgs e)
{
// here we can pass the data we need.
var secondPage = new SecondPage(myViewModel.Data);
await Navigation.PushAsync(secondPage);
}
}
MainPage.xaml.cs
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiCollectionApp.MainPage"
xmlns:local="clr-namespace:MauiCollectionApp"
x:Name="myPage"
>
<VerticalStackLayout>
<CollectionView ItemsSource="{ Binding Data}" x:Name="mCollectionView"
SelectionChanged="mCollectionView_SelectionChanged"
SelectionMode="Single"
>
<CollectionView.ItemTemplate>
<DataTemplate>
<HorizontalStackLayout Margin="3" >
<Label Text="{Binding Name}" BackgroundColor="Gray"/>
<Label Text="{Binding Car.Make}" Margin="5,0,5,0" />
<Button Text="delete" Margin="10,0,0,0"
BackgroundColor="Red"
Command="{Binding Path= BindingContext.RemoveEquipmentCommand,Source={Reference mCollectionView }}" CommandParameter="{Binding .}"
/>
</HorizontalStackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button Text="submit" Clicked="Button_Clicked" Margin="10"/>
</VerticalStackLayout>
</ContentPage>
MyViewModel.cs
public class MyViewModel: INotifyPropertyChanged
{
public ObservableCollection<MyModel> Data { get; set; }
public ICommand RemoveEquipmentCommand => new Command<MyModel>(ReMoveItem);
private void ReMoveItem(MyModel obj)
{
System.Diagnostics.Debug.WriteLine(" the selected item's name is: " + obj.Name );
Data.Remove(obj);
}
public MyViewModel() {
Data = new ObservableCollection<MyModel>();
Data.Add(new MyModel { Name ="model_1", Car= new Vehicle {Make="Make1" } });
Data.Add(new MyModel { Name = "model_2", Car = new Vehicle { Make = "Make2" } });
Data.Add(new MyModel { Name = "model_3", Car = new Vehicle { Make = "Make3" } });
Data.Add(new MyModel { Name = "model_4", Car = new Vehicle { Make = "Make4" } });
}
bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Object.Equals(storage, value))
return false;
storage = value;
OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
SecondPage.cs
public partial class SecondPage : ContentPage
{
public ObservableCollection<MyModel> Items { get; set; }
public SecondPage(ObservableCollection<MyModel> data )
      { // we can get the passed data here
            InitializeComponent();
            this.Items = data;
      }
}

Zxing.Net.Mobile Forms and MVVM Xaml Not Scanning

New to Xamarin development! Using Visual Studio 2017 and all the latest installs and updates for my dev environment.
I have my app "shell" working in that it will run, navigate, crud to local db, and sync to rest services. So, the base of my app is sound. I am trying to integrate the ZXing barcode scanner into my app. Most of what help I can find relates to raw forms or code behind xaml. I am using views and view models and I don't know how to translate the information I am finding to this model.
I currently have the xaml view showing the "camera viewer" when a button is clicked so I can see a barcode using the camera. However, there is no "red line" in the camera view and subsequently, there are no events being fired to let me know what is going on. I really am confused as I am so new to Xamarin. I don't know where to start.
XAML View page
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
xmlns:fe="clr-namespace:FreshEssentials;assembly=FreshEssentials"
xmlns:forms="clr-namespace:ZXing.Net.Mobile.Forms;assembly=ZXing.Net.Mobile.Forms"
prism:ViewModelLocator.AutowireViewModel="True"
x:Class="Views.InventoryPage1"
Title="Inventory Page">
<StackLayout Spacing="5" Padding="10,10,10,0">
<!--<fe:BindablePicker ItemsSource="{Binding Areas}" SelectedItem="{Binding SelectedArea}" DisplayProperty="AreaName" Title="Select Your Area" />
<fe:BindablePicker ItemsSource="{Binding Reasons}" SelectedItem="{Binding SelectedReason}"
DisplayProperty="Description" Title="Select a Reason" />
<Label Text="Scan"/>
<Entry Text="{Binding Barcode}"/>
<Label Text="Quantity"/>
<Entry Text="{Binding Quantity}"/>
<Button Text="Save" Style="{StaticResource Button_Primary}" Command="{Binding SaveCommand}" />-->
<forms:ZXingScannerView WidthRequest="100" HeightRequest="100" IsScanning="{Binding IsScanning}" IsAnalyzing="{Binding IsAnalyzing}" Result="{Binding Result, Mode=TwoWay}" ScanResultCommand="{Binding QRScanResultCommand}" ></forms:ZXingScannerView>
</StackLayout>
</ContentPage>
ViewModel
public class InventoryPage1ViewModel : BindableBase, INavigationAware
{
private readonly IPageDialogService _pageDialogService;
private bool _isAnalyzing = true;
private bool _isScanning = true;
public ZXing.Result Result { get; set; }
public List<Area> Areas { get; private set; }
public Area SelectedArea { get; set; }
public List<Reason> Reasons { get; private set; }
public Reason SelectedReason { get; set; }
public int Quantity { get; set; }
public string Barcode { get; set; }
public DelegateCommand SaveCommand => new DelegateCommand(PerformSave);
public DelegateCommand QRScanResultCommand => new DelegateCommand(QRCommand);
private readonly IAreaService _areaService;
private readonly IScanService _scanService;
private readonly IReasonService _reasonService;
public InventoryPage1ViewModel(IAreaService areaService, IScanService scanService, IReasonService reasonService, IPageDialogService pageDialogService)
{
_pageDialogService = pageDialogService;
_reasonService = reasonService;
_scanService = scanService;
_areaService = areaService;
Areas = _areaService.GetAll();
Reasons = _reasonService.GetAll();
}
public bool IsScanning
{
get
{
return _isScanning;
}
set
{
_isScanning = value;
RaisePropertyChanged();
}
}
public bool IsAnalyzing
{
get
{
return _isAnalyzing;
}
set
{
_isAnalyzing = value;
RaisePropertyChanged();
}
}
private void QRCommand()
{
int x = 1;
}
private async void PerformSave()
{
var scan = new Scan()
{
AreaId = SelectedArea.Id,
InsertDateTime = DateTime.Now,
ReasonId = SelectedReason.Id,
ScanItem = Barcode,
ScanQty = Quantity,
IsUploaded = false
};
// Save it to the DB here.
var retVal = _scanService.Insert(scan);
if (retVal)
{
await _pageDialogService.DisplayAlertAsync("Saved", "Scan saved successfully.", "OK");
}
else
{
// TODO: Inform the user something went wrong.
}
}
int _index;
public int SelectIndex
{
get
{
return _index;
}
set
{
_index = value;
RaisePropertyChanged("SelectIndex");
}
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
}
public void OnNavigatingTo(NavigationParameters parameters)
{
}
}
MainActivity
public class MainActivity :
global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.tabs;
ToolbarResource = Resource.Layout.toolbar;
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
ZXing.Net.Mobile.Forms.Android.Platform.Init();
LoadApplication(new App(new AndroidInitializer()));
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IConnectionFactory, ConnectionFactory>();
}
}
UPDATE
I have a working view model now thanks to #Krzysztof over at Xamarin.Forms.
New ViewModel
public class InventoryPage1ViewModel : BindableBase, INavigationAware
{
private readonly IPageDialogService _pageDialogService;
public List<Area> Areas { get; private set; }
public Area SelectedArea { get; set; }
public List<Reason> Reasons { get; private set; }
public Reason SelectedReason { get; set; }
public int Quantity { get; set; }
public DelegateCommand SaveCommand => new DelegateCommand(PerformSave);
private readonly IAreaService _areaService;
private readonly IScanService _scanService;
private readonly IReasonService _reasonService;
public InventoryPage1ViewModel(IAreaService areaService, IScanService scanService, IReasonService reasonService, IPageDialogService pageDialogService)
{
_pageDialogService = pageDialogService;
_reasonService = reasonService;
_scanService = scanService;
_areaService = areaService;
Areas = _areaService.GetAll();
Reasons = _reasonService.GetAll();
}
public ZXing.Result Result { get; set; }
private string barcode = string.Empty;
public string Barcode
{
get
{
return barcode;
}
set
{
barcode = value;
RaisePropertyChanged();
}
}
private bool isAnalyzing = true;
public bool IsAnalyzing
{
get { return this.isAnalyzing; }
set
{
if (!bool.Equals(this.isAnalyzing, value))
{
this.isAnalyzing = value;
RaisePropertyChanged(nameof(IsAnalyzing));
}
}
}
private bool isScanning = true;
public bool IsScanning
{
get { return this.isScanning; }
set
{
if (!bool.Equals(this.isScanning, value))
{
this.isScanning = value;
RaisePropertyChanged(nameof(IsScanning));
}
}
}
public Command QRScanResultCommand
{
get
{
return new Command(() =>
{
IsAnalyzing = false;
IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
Barcode = Result.Text;
await _pageDialogService.DisplayAlertAsync("Scanned Item", Result.Text, "Ok");
});
IsAnalyzing = true;
IsScanning = true;
});
}
}
private async void PerformSave()
{
var scan = new Scan()
{
AreaId = SelectedArea.Id,
InsertDateTime = DateTime.Now,
ReasonId = SelectedReason.Id,
ScanItem = Barcode,
ScanQty = Quantity,
IsUploaded = false
};
// Save it to the DB here.
var retVal = _scanService.Insert(scan);
if (retVal)
{
await _pageDialogService.DisplayAlertAsync("Saved", "Scan saved successfully.", "OK");
}
else
{
// TODO: Inform the user something went wrong.
}
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
}
public void OnNavigatingTo(NavigationParameters parameters)
{
}
}

Wicket SELECT doesn't update it's model

i've wicket panel with list of ProductViews (as SELECT)
after you choose your ProductView from SELECT, its load Product from database by id of ProductView into details form. You can modify Product entity and you can save it when you finish.
After save i try to refresh SELECT list to update its data, but it doesn't work(i mean, for example, SELECT contains an old name of product after rename it, but when i select the same ProductView, it reload an entity into details form again, and of course the new data appears from database) i don't want to reload product list again, i want to solve it from memory. Here is my source:
ProductView:
#Entity
#Table(name = "product")
#XmlRootElement
public class ProductView implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Enumerated(EnumType.ORDINAL)
#Column(name = "category")
private Category category;
public ProductView() {
}
public ProductView(Long id) {
this.id = id;
}
public ProductView(Product product) {
this.id = product.getId();
this.name = product.getName();
this.category = product.getCategory();
}
// + getters & setters
}
Product:
#Entity
#Table(name = "product")
#XmlRootElement
public class Product implements Serializable {
// same as ProductView but more data, objects, connections, etc
}
And wicket panel with comments
private Product product;
private ProductView productView;
private List<ProductView> productViews;
private Form productForm;
private Select categorySelectComponent;
private WebMarkupContainer contentContainer;
public ProductPanel(String id) {
super(id);
setOutputMarkupId(true);
add(contentContainer = new WebMarkupContainer("contentContainer")); // container DIV
contentContainer.setOutputMarkupId(true); // refreshable
contentContainer.add(productForm = new Form("productForm")); // details FORM
contentContainer.add(categorySelectComponent = new Select("categorySelectComponent", new PropertyModel<ProductView>(this, "productView"))); // item SELECT
categorySelectComponent.add( new SelectOptions<ProductView>( // first category
"oneCategory",
new PropertyModel<List<ProductView>>(this, "oneProducts"), // see getOneProducts(); list of productviews
new IOptionRenderer<ProductView>() {
#Override
public String getDisplayValue(ProductView p) {
return p.getName();
}
#Override
public IModel<ProductView> getModel(ProductView p) {
return new Model<ProductView>(p);
}
}));
categorySelectComponent.add( new SelectOptions<ProductView>( // second category
"twoCategory",
new PropertyModel<List<ProductView>>(this, "twoProducts"), // see getTwoProducts();
new IOptionRenderer<ProductView>() {
#Override
public String getDisplayValue(ProductView p) {
return p.getName();
}
#Override
public IModel<ProductView> getModel(ProductView p) {
return new Model<ProductView>(p);
}
}));
categorySelectComponent.add( new SelectOptions<ProductView>( // third category
"threeCategory",
new PropertyModel<List<ProductView>>(this, "threeProducts"), // see getThreeProducts();
new IOptionRenderer<ProductView>() {
#Override
public String getDisplayValue(ProductView p) {
return p.getName();
}
#Override
public IModel<ProductView> getModel(ProductView p) {
return new Model<ProductView>(p);
}
}));
categorySelectComponent.add(new OnChangeAjaxBehavior() { // update form after choose entity
#Override
protected void onUpdate(final AjaxRequestTarget art) {
product = getProductFacade().find( productView.getId() );
updatePanel(art);
}
});
productForm.add(
// some details component (textfields, radios, links, etc) to edit Product
);
productForm.add(new AjaxSubmitLink("formSubmitLink") { // save entity
#Override
protected void onSubmit(AjaxRequestTarget art, Form<?> form) {
super.onSubmit(art, form); // i don't know it is necessary at all
getProductFacade().edit( product );
updateProductViewInCategoryMap(art); // important method
//art.add(contentContainer); //it is in update method
}
});
}
more methods inside panel
private Map<Category, List<ProductView>> categoryMap; // all product by categories
public void initCategoryMap() {
categoryMap = new EnumMap<Category, List<ProductView>>(ProductView.class);
categoryMap.put( Category.ONE, new ArrayList<ProductView>() );
categoryMap.put( Category.TWO, new ArrayList<ProductView>() );
categoryMap.put( Category.THREE, new ArrayList<ProductView>() );
for (ProductView view : getProductViews()) {
categoryMap.get(view.getCategory()).add(view);
}
}
//***** Get Products By Categories *******
final public List<ProductView> getOneProducts(){
if (categoryMap == null){
initCategoryMap();
}
return categoryMap.get( Category.ONE );
}
final public List<ProductView> getTwoCategory(){
if (categoryMap == null){
initCategoryMap();
}
return categoryMap.get( Category.TWO );
}
final public List<ProductView> getThreeProducts(){
if (categoryMap == null){
initCategoryMap();
}
return categoryMap.get( Category.THREE );
}
// **************************************
public List<ProductView> getProductViews() { // Get All Product
if (productViews == null) {
productViews = getProductFacade().findAllProductAsView();
}
return productViews;
}
private void updatePanel(AjaxRequestTarget art) { // refresh panel
art.add(ProductPanel.this);
}
private void updateProductViewInCategoryMap(AjaxRequestTarget art) { // change Product in map after save (call from onSubmit method of AjaxSubmitLink)
for(Map.Entry<Category, List<ProductView>> entry : categoryMap.entrySet()){ // search category contains entity
if (entry.getValue().contains( productView )){
entry.getValue().remove( productView ); // remove entity from category
break;
}
}
productView = new ProductView( product ); // new productview by modified product
categoryMap.get( productView.getCategory() ).add( productView ); // add entity to it's category's list
art.add(contentContainer);
}
and HTML:
<select class="categorySelect" wicket:id="categorySelectComponent">
<optgroup label="Category One">
<wicket:container wicket:id="oneCategory">
<option wicket:id="option"></option>
</wicket:container>
</optgroup>
<optgroup label="Category Two">
<wicket:container wicket:id="twoCategory">
<option wicket:id="option"></option>
</wicket:container>
</optgroup>
<optgroup label="Category Three">
<wicket:container wicket:id="threeCategory">
<option wicket:id="option"></option>
</wicket:container>
</optgroup>
</select>
Any idea?
Call #setRecreateChoices(true) on all your SelectOptions.
What about updating productViews on saving changes or using LoadableDetachableModel instead of PropertyModel in categorySelectComponent?
here:
new Select("categorySelectComponent", new PropertyModel<ProductView>(this, "productView")

Controller Bean not picking up the username

I'm really in a grave problem with this. All of a sudden my properly working code has stopped working. I have no clue what so ever why!!!! And worst of all I have to deploy my project today :( . Don't know if it will be right to say or not but all of this started 2 days after adding PrimeFaces in build path. Can anyone please direct me to the right direction. Would be great help!
I have following configuration:
Glassfish v3
Mojara 2.1.6-FCS
JPA Eclipselink
Controller Bean
public List<Usergroupdetail> getUsergroupdetail_list() {
List<Usergroupdetail> myUserGroupDetail = new ArrayList<Usergroupdetail>(
lODBN.listUserGroupDetail(loginBean.getUsername()));
System.out.println("username found is:" + loginBean.getUsername());
return myUserGroupDetail;
}
For getting complete list of data from the JPA PoJO UserGroupReport
public List<Usergroupreport> getGroupId_list() {
List<Usergroupreport> myAllgroupIds = new ArrayList<Usergroupreport>(
lODBN.findAllGroupIdByUser(loginBean.getUsername()));
return myAllgroupIds;
}
Stack Trace
WARNING: PWC4011: Unable to set request character encoding to ISO-8859-1 from context /WebApp, because request parameters have already been read, or ServletRequest.getReader() has already been called
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT ROWID, GROUPID, GROUPNAME, USERNAME FROM usergroupdetail WHERE (USERNAME = ?)
bind => [1 parameter bound]
INFO: []
INFO: username found is:null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
FINE: SELECT RowId, LOD1COSTCENTER, LOD1DISPLAYNAME, LOD1DOMAIN, LOD1MAIL, LOD1USER, LOD2COSTCENTER, LOD2DISPLAYNAME, LOD2DOMAIN, LOD2MAIL, LOD2USER, Access, AuthentifizierteBenutzer, Auto, Comment, Comment1, Comment2, Comment3, Domain1, Domain2, EmailFeedback, EmailSendStatus, RechteGruppeChange, RechteGruppeRead, Security, Type, Username FROM lodreport WHERE (Username = ?)
bind => [1 parameter bound]
INFO: []
INFO: LOD list for Username :null
Login Bean
package bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
//import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import ejb.UserDaoBean;
import ejb.UserGroupDaoBean;
import model.User;
#ManagedBean(name = "loginBean")
#SessionScoped
public class LoginBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#EJB
private UserDaoBean uDB;
#EJB
private UserGroupDaoBean uGDB;
private User userId;
public List<User> usernameFirstLastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String firstName;
public String lastName;
public String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<User> getUsernameFirstLastName() {
List<User> myName = new ArrayList<User>(uDB.findFirtLastNames(username));
return myName;
}
public void setUsernameFirstLastName(List<User> usernameFirstLastName) {
this.usernameFirstLastName = usernameFirstLastName;
}
private String username;
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String login() {
FacesContext context = FacesContext.getCurrentInstance();
if (uDB.validateUser(username,password)) {
userId = uDB.findUser(username);
context.getExternalContext().getSessionMap().put("userId", userId);
if (uGDB.validateGroup(userId)) {
return "home.jsf?faces-redirect=true&includeViewParams=true";
}
return "normalHome.jsf?faces-redirect=true&includeViewParams=true";
} else {
FacesMessage message = new FacesMessage();
message.setSeverity(FacesMessage.SEVERITY_ERROR);
message.setSummary("Username doesn't exists! OR User is trying to login from someone else's account");
context.addMessage("", message);
return "newloginerror.jsf?faces-redirect=true";
}
}
public String logout() {
FacesContext.getCurrentInstance().getExternalContext()
.invalidateSession();
return "logout.jsf?faces-redirect=true";
}
}
Login Page
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link href="./css/PageLayout.css" rel="stylesheet" type="text/css" />
<title>Login</title>
</h:head>
<h:body>
<f:view>
<div style="background-color: #205a8c; width: auto; height: 60px">
<h3 style="font-size: large; position: relative;" align="left">Lord
Of Data Web App</h3>
</div>
<div id="wrappers">
<div class="content pls centering">
<h:form>
<table class="form_table" style="background-color: silver;">
<tbody>
<tr>
<td>Username</td>
<td><h:inputText id="inputusername"
value="#{loginBean.username}" required="true"
requiredMessage="Username is required!"></h:inputText> <h:message
for="inputusername"></h:message></td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret id="inputpassword"
value="#{loginBean.password}" required="true"
requiredMessage="Password is required!"></h:inputSecret> <h:message
for="inputpassword"></h:message></td>
</tr>
</tbody>
</table>
<div id="buttonsoptions" align="center" style="padding-top: 10px;">
<h:panelGroup>
<tr>
<td><h:commandButton id="login" value="Login"
action="#{loginBean.login}"></h:commandButton></td>
</tr>
</h:panelGroup>
</div>
</h:form>
</div>
</div>
</f:view>
</h:body>
</html>
EJB Code Snippet for Login Authentication
public boolean validateUser(String username, String password) {
try {
Query myQuery = entityManager.createNamedQuery("userverification")
.setParameter("username", username)
.setParameter("password", password);
User result = (User) myQuery.getSingleResult();
if (result != null) {
System.out.println("Loggin sucessful!");
return true;
} else {
System.out.println("User does not exists in the system");
return false;
}
} catch (NoResultException e) {
return false;
}
}
And I tried to use the username to my other session bean which was working perfectly fine until two days back. Here is the code for this bean where I am trying to call the Username picked from login bean
Bean
package bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import ejb.LODReportDaoBean;
import ejb.LordOfDataDaoBeanNormal;
import ejb.UserDaoBean;
import model.Lodreport;
import model.Usergroupdetail;
import model.Usergroupreport;
#ManagedBean(name = "lordOfDataNormalUserBean")
#SessionScoped
public class LordOfDataNormalUserBean implements Serializable {
/**
* #author Sushant Pandey
*/
private static final long serialVersionUID = 1L;
#EJB
private LordOfDataDaoBeanNormal lODBN;
#EJB
private UserDaoBean uDB;
#EJB
private LODReportDaoBean lONRDB;
#ManagedProperty(value = "#{loginBean}")
private LoginBean loginBean;
public LoginBean getLoginBean() {
return loginBean;
}
public void setLoginBean(LoginBean loginBean) {
this.loginBean = loginBean;
}
public List<Lodreport> lodnormal_list;
public List<Usergroupreport> usergroup_list;
public List<Usergroupdetail> usergroupdetail_list;
public List<Lodreport> findDataByRowId;
private Lodreport myreport = new Lodreport();
public Lodreport getMyreport() {
return myreport;
}
public void setMyreport(Lodreport myreport) {
this.myreport = myreport;
}
public void setFindDataByRowId(List<Lodreport> findDataByRowId) {
this.findDataByRowId = findDataByRowId;
}
public int security;
public String username;
public String access;
public String authentifizierteBenutzer;
public String auto;
public String comment;
public String comment1;
public String comment2;
public String comment3;
public String domain1;
public String domain2;
public String emailFeedback;
public String emailSendStatus;
public String lOD1CostCenter;
public String lOD1DisplayName;
public String lOD1Domain;
public String lOD1Mail;
public String lOD1User;
public String lOD2CostCenter;
public String lOD2DisplayName;
public String lOD2Domain;
public String lOD2Mail;
public String lOD2User;
public String rechteGruppeChange;
public String rechteGruppeRead;
public String type;
public int rowId;
public List<Usergroupreport> groupId_list;
public boolean edit;
public boolean isEdit() {
return edit;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
public void setGroupId_list(List<Usergroupreport> groupId_list) {
this.groupId_list = groupId_list;
}
public void setLodnormal_list(List<Lodreport> lodnormal_list) {
this.lodnormal_list = lodnormal_list;
}
public int getSecurity() {
return security;
}
public void setSecurity(int security) {
this.security = security;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccess() {
return access;
}
public void setAccess(String access) {
this.access = access;
}
public String getAuthentifizierteBenutzer() {
return authentifizierteBenutzer;
}
public void setAuthentifizierteBenutzer(String authentifizierteBenutzer) {
this.authentifizierteBenutzer = authentifizierteBenutzer;
}
public String getAuto() {
return auto;
}
public void setAuto(String auto) {
this.auto = auto;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getComment1() {
return comment1;
}
public void setComment1(String comment1) {
this.comment1 = comment1;
}
public String getComment2() {
return comment2;
}
public void setComment2(String comment2) {
this.comment2 = comment2;
}
public String getComment3() {
return comment3;
}
public void setComment3(String comment3) {
this.comment3 = comment3;
}
public String getDomain1() {
return domain1;
}
public void setDomain1(String domain1) {
this.domain1 = domain1;
}
public String getDomain2() {
return domain2;
}
public void setDomain2(String domain2) {
this.domain2 = domain2;
}
public String getEmailFeedback() {
return emailFeedback;
}
public void setEmailFeedback(String emailFeedback) {
this.emailFeedback = emailFeedback;
}
public String getEmailSendStatus() {
return emailSendStatus;
}
public void setEmailSendStatus(String emailSendStatus) {
this.emailSendStatus = emailSendStatus;
}
public String getlOD1CostCenter() {
return lOD1CostCenter;
}
public void setlOD1CostCenter(String lOD1CostCenter) {
this.lOD1CostCenter = lOD1CostCenter;
}
public String getlOD1DisplayName() {
return lOD1DisplayName;
}
public void setlOD1DisplayName(String lOD1DisplayName) {
this.lOD1DisplayName = lOD1DisplayName;
}
public String getlOD1Domain() {
return lOD1Domain;
}
public void setlOD1Domain(String lOD1Domain) {
this.lOD1Domain = lOD1Domain;
}
public String getlOD1Mail() {
return lOD1Mail;
}
public void setlOD1Mail(String lOD1Mail) {
this.lOD1Mail = lOD1Mail;
}
public String getlOD1User() {
return lOD1User;
}
public void setlOD1User(String lOD1User) {
this.lOD1User = lOD1User;
}
public String getlOD2CostCenter() {
return lOD2CostCenter;
}
public void setlOD2CostCenter(String lOD2CostCenter) {
this.lOD2CostCenter = lOD2CostCenter;
}
public String getlOD2DisplayName() {
return lOD2DisplayName;
}
public void setlOD2DisplayName(String lOD2DisplayName) {
this.lOD2DisplayName = lOD2DisplayName;
}
public String getlOD2Domain() {
return lOD2Domain;
}
public void setlOD2Domain(String lOD2Domain) {
this.lOD2Domain = lOD2Domain;
}
public String getlOD2Mail() {
return lOD2Mail;
}
public void setlOD2Mail(String lOD2Mail) {
this.lOD2Mail = lOD2Mail;
}
public String getlOD2User() {
return lOD2User;
}
public void setlOD2User(String lOD2User) {
this.lOD2User = lOD2User;
}
public String getRechteGruppeChange() {
return rechteGruppeChange;
}
public void setRechteGruppeChange(String rechteGruppeChange) {
this.rechteGruppeChange = rechteGruppeChange;
}
public String getRechteGruppeRead() {
return rechteGruppeRead;
}
public void setRechteGruppeRead(String rechteGruppeRead) {
this.rechteGruppeRead = rechteGruppeRead;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getRowId() {
return rowId;
}
public void setRowId(int rowId) {
this.rowId = rowId;
}
public void setUsergroup_list(List<Usergroupreport> usergroup_list) {
this.usergroup_list = usergroup_list;
}
public void setUsergroupdetail_list(
List<Usergroupdetail> usergroupdetail_list) {
this.usergroupdetail_list = usergroupdetail_list;
}
#PostConstruct
public void init() {
// getLodnormal_list();
getUsergroupdetail_list();
// getGroupId_list();
getUsername();
}
public String displayReport() {
getLodnormal_list();
return "reportLordOfDataNormal.jsf?faces-redirect=true";
}
public List<Lodreport> getLodnormal_list() {
List<Lodreport> myLodreport = new ArrayList<Lodreport>(
lODBN.reportLODNormal(loginBean.getUsername()));
System.out.println("LOD list for Username :" + loginBean.getUsername() );
return myLodreport;
}
public List<Usergroupreport> getUsergroup_list() {
return usergroup_list;
}
public List<Usergroupdetail> getUsergroupdetail_list() {
List<Usergroupdetail> myUserGroupDetail = new ArrayList<Usergroupdetail>(
lODBN.listUserGroupDetail(loginBean.getUsername()));
System.out.println("username found is:" + loginBean.getUsername());
return myUserGroupDetail;
}
public String editLODDataNormal() {
lODBN.updateExistingLODDataNormal(security, loginBean.getUsername(),
access, authentifizierteBenutzer, auto, comment, comment1,
comment2, comment3, domain1, domain2, emailFeedback,
emailSendStatus, lOD1CostCenter, lOD1DisplayName, lOD1Domain,
lOD1Mail, lOD1User, lOD2CostCenter, lOD2DisplayName,
lOD2Domain, lOD2Mail, lOD2User, rechteGruppeChange,
rechteGruppeRead, type, rowId);
return "reportLordOfDataNormal.jsf?faces-redirect=true";
}
public List<Usergroupreport> getGroupId_list() {
List<Usergroupreport> myAllgroupIds = new ArrayList<Usergroupreport>(
lODBN.findAllGroupIdByUser(loginBean.getUsername()));
return myAllgroupIds;
}
public void edit(Lodreport myreport) {
this.myreport = myreport;
edit = true;
}
public void saveMyReport(){
lONRDB.updateReport(myreport);
}
}

Avoiding entity update directly on form submit

I have an entity which is showed on the screen as text in input boxes which can be modified. When i submit the form hitting save, i would like my ejb3 component to handle the data and persist or merge it using the entity manager. But for some reason, when i modify the data and hit save the data directly gets updated in the database by-pasing my ejb3, which is certainly undesirable. My code looks like the following
#Entity
#Table(name = "EMP")
public class Emp implements java.io.Serializable {
private short empno;
private Dept dept;
private String ename;
private String job;
private Short mgr;
private Date hiredate;
private BigDecimal sal;
private BigDecimal comm;
public Emp() {
}
public Emp(short empno) {
this.empno = empno;
}
public Emp(short empno, Dept dept, String ename, String job, Short mgr,
Date hiredate, BigDecimal sal, BigDecimal comm) {
this.empno = empno;
this.dept = dept;
this.ename = ename;
this.job = job;
this.mgr = mgr;
this.hiredate = hiredate;
this.sal = sal;
this.comm = comm;
}
#Id
#Column(name = "EMPNO", unique = true, nullable = false, precision = 4, scale = 0)
public short getEmpno() {
return this.empno;
}
public void setEmpno(short empno) {
this.empno = empno;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "DEPTNO")
public Dept getDept() {
return this.dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
#Column(name = "ENAME", length = 10)
#Length(max = 10)
public String getEname() {
return this.ename;
}
public void setEname(String ename) {
this.ename = ename;
}
#Column(name = "JOB", length = 9)
#Length(max = 9)
public String getJob() {
return this.job;
}
public void setJob(String job) {
this.job = job;
}
#Column(name = "MGR", precision = 4, scale = 0)
public Short getMgr() {
return this.mgr;
}
public void setMgr(Short mgr) {
this.mgr = mgr;
}
#Temporal(TemporalType.DATE)
#Column(name = "HIREDATE", length = 7)
public Date getHiredate() {
return this.hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
#Column(name = "SAL", precision = 7)
public BigDecimal getSal() {
return this.sal;
}
public void setSal(BigDecimal sal) {
this.sal = sal;
}
#Column(name = "COMM", precision = 7)
public BigDecimal getComm() {
return this.comm;
}
public void setComm(BigDecimal comm) {
this.comm = comm;
}
}
#Stateful
#Name("workflow")
#Scope(ScopeType.CONVERSATION)
public class WorkflowBean implements Workflow
{
#Logger private Log log;
#In StatusMessages statusMessages;
#PersistenceContext(type=PersistenceContextType.EXTENDED)
EntityManager entityManager;
#Out(required=false)
Emp employee = new Emp();
#RequestParameter("empEmpno")
String empNo;
public void workflow()
{
log.info("workflow.workflow() action called");
statusMessages.add("workflow");
}
#End
public boolean save(){
entityManager.merge(emp);
entityManger.flush();
}
#Begin(join=true)
public boolean populateEmp(){
entityManager.setFlushMode(FlushModeType.COMMIT);
System.out.println("The Emp No. is---"+empNo);
int no = Integer.parseInt(empNo);
short emp =(short)no;
employee = entityManager.find(Emp.class, emp);
entityManager.flush();
return true;
}
public Emp getEmployee() {
return employee;
}
public void setEmployee(Emp employee) {
this.employee = employee;
}
// add additional action methods
public String getEmpNo() {
return empNo;
}
public void setEmpNo(String empNo) {
this.empNo = empNo;
}
#Remove
#Destroy
public void destroy() {
}
}
My view looks like
<h:form id="emp" styleClass="edit">
<rich:panel>
<f:facet name="header">Edit Emp</f:facet>
<s:decorate id="empnoField" template="layout/edit.xhtml">
<ui:define name="label">Empno</ui:define>
<h:inputText id="empno"
required="true"
value="#{workflow.employee.empno}">
</h:inputText>
</s:decorate>
<s:decorate id="commField" template="layout/edit.xhtml">
<ui:define name="label">Comm</ui:define>
<h:inputText id="comm"
value="#{workflow.employee.comm}"
size="14">
</h:inputText>
</s:decorate>
<s:decorate id="enameField" template="layout/edit.xhtml">
<ui:define name="label">Ename</ui:define>
<h:inputText id="ename"
size="10"
maxlength="10"
value="#{workflow.employee.ename}">
</h:inputText>
</s:decorate>
<s:decorate id="hiredateField" template="layout/edit.xhtml">
<ui:define name="label">Hiredate</ui:define>
<rich:calendar id="hiredate"
value="#{workflow.employee.hiredate}" datePattern="MM/dd/yyyy" />
</s:decorate>
<s:decorate id="jobField" template="layout/edit.xhtml">
<ui:define name="label">Job</ui:define>
<h:inputText id="job"
size="9"
maxlength="9"
value="#{workflow.employee.job}">
</h:inputText>
</s:decorate>
<s:decorate id="mgrField" template="layout/edit.xhtml">
<ui:define name="label">Mgr</ui:define>
<h:inputText id="mgr"
value="#{workflow.employee.mgr}">
</h:inputText>
</s:decorate>
<s:decorate id="salField" template="layout/edit.xhtml">
<ui:define name="label">Sal</ui:define>
<h:inputText id="sal"
value="#{workflow.employee.sal}"
size="14">
</h:inputText>
</s:decorate>
<s:decorate id="deptField" template="layout/edit.xhtml">
<ui:define name="label">Department</ui:define>
<h:inputText id="dname"
value="#{workflow.deptName}">
</h:inputText>
</s:decorate>
<div style="clear:both">
<span class="required">*</span>
required fields
</div>
</rich:panel>
<div class="actionButtons">
<h:commandButton id="save"
value="Save"
action="#{workflow.save}"
rendered="true"/>
</div>
</h:form>
[It was difficult to address issue in comments for your response.]
There are few things which I haven't understand & why it's done that way.
Using transient fields, it will add overhead of adding those to entity object while persisting.
Why is auto-commit causes issue & can't be implemented.
Regardless of these things, you can try
Making the entity detached with entityManager.detach(entity) or clearing the persistence context with entityManager.clear(), detaching all the underlying entities. But prior one is more favourible.
Can manage transaction manually instead of container. Use BMT where you can have control over the operations.