I am new to java and trying to learn how to add data into database.
I cannot make my submit button work. I am getting error of "target unreachable". I am using hibernate and phpMyAdmin.
As I said I new to this. Please let me know if I am missing information that needed.
Instead of calling class in my submit button should I create private String method for the text boxes?
I am confused.
Thanks a lot for your help.
additem.xhtml
<h:body>
<ui:composition template="template.xhtml">
<ui:define name="content">
<h1>Add a New Item</h1>
<br />
<h:form>
<p:panel id="panel" header="Enter an Item" style="margin-bottom:20px;">
<p:growl id="growl" showDetail="true" sticky="false" />
<h:outputLabel value="Item Number" />Item Number:
<p:inputText value="#{LibraryItem.itemNumber}" />
<br />
<h:outputLabel value="Title" />Title:
<p:inputText value="#{LibraryItem.title}" />
<br />
<h:outputLabel for="type" value="Type">Item Type:
<p:selectOneMenu value="#{libraryItem.type}" style="width:228px">
<f:selectItem itemValue="" itemLabel="Select One" />
<f:selectItem itemValue="book" itemLabel="Book" />
<f:selectItem itemValue="magazine" itemLabel="Magazine" />
<f:selectItem itemValue="movie" itemLabel="Movie" />
<f:selectItem itemValue="music" itemLabel="Music" />
</p:selectOneMenu>
</h:outputLabel>
<br />
<h:outputLabel value="Status" />Status:
<p:inputText value="#{LibraryItem.status}" />
<br />
<p:commandButton value="Submit" actionListener="#{AddLibraryItem.addItem}" update="growl" />
<br />
</p:panel>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
AddLibraryItem.java
#Named
#ManagedBean
#Scope("request")
public class AddLibraryItem {
//no arg constructor
public AddLibraryItem(){
}
#Inject private LibraryItem libraryItem;
#Inject private ILibraryService libraryService;
public String addItem(){
//return value
String returnValue = "success";
//assign values
libraryItem.setStatus("CHECKED_IN");
//add to library
try {
libraryService.add(libraryItem);
displayMessage("Success","Item added");
}catch (Exception e){
displayMessage("Error", e.toString());
return "fail";
}
return returnValue;
}
//Getters and Setters
public LibraryItem getLibraryItem() {
return libraryItem;
}
public void setLibraryItem(LibraryItem libraryItem) {
this.libraryItem = libraryItem;
}
public ILibraryService getLibraryService() {
return libraryService;
}
public void setLibraryService(ILibraryService libraryService) {
this.libraryService = libraryService;
}
//method to display messages
private void displayMessage(String title, String message){
//get faces context
FacesContext currentInstance = FacesContext.getCurrentInstance();
//message to show
FacesMessage fm = new FacesMessage(FacesMessage.SEVERITY_INFO, title, message);
//display the message
currentInstance.addMessage(null, fm);
}
}
Related
The short version of my problem is that the inputtext will not change the value in bean after I modified the value from the bean.
The longer version:
There is a form in which is a dataTable with user information; some inputTexts, and two buttons. If you fill the inputTexts, a new user will be created with the given data, and appears in dataTable - this works fine, I can create as many users as I can.
The tricky part is if you select a row from the dataGrid, the user information has to appear in the inputText fields - this works fine - so the admin can modify them. But after changing the inputText values in the bean, if the admin changes someting in the inputText, the value "will not follow" tha changes, the value remains the same. What could I do wrong?
The JSF page looks like this:
<html>
<h:body>
<h:form style="font-size:14px;" id="setupform">
...
<p:panel header="Edit users" id="userAddingPanel" rendered="#{settingsbean.validLogin}">
<p:panelGrid columns="2" id="userAddingGrid">
<p:outputLabel value="User Name: " />
<p:inputText id="userName" value="#{settingsbean.userName}" />
<p:outputLabel value="User Password: " />
<p:password id="userPass" value="#{settingsbean.userPassword}" />
<p:outputLabel value="E-mail address: " />
<p:inputText id="userMailAddress" value="#{settingsbean.mailAddress}" />
<p:outputLabel id="userDelete" value="Inactivate User: " />
<p:selectBooleanCheckbox id="isUserDeleted" value="#{settingsbean.deletedUser}" />
<p:commandButton id="addUser" value="Create User" update="userAddingGrid" icon="ui-icon-disk" action="#{settingsbean.addNewUser}" />
<p:commandButton id="modifyUser" value="Modify User" icon="ui-icon-wrench" update="userAddingGrid" action="#{settingsbean.updateUser}" process="setupform"/>
</p:panelGrid>
<br/>
<p:dataTable id="usersTable" var="users" value="#{settingsbean.userList}" tableStyle="overflow: auto;" stickyHeader="true" selectionMode="single" rowKey="#{users.id}" selection="#{settingsbean.selectedUser}">
<p:ajax event="rowSelect" update=":setupform:userName, :setupform:userName,
:setupform:userPass, :setupform:userMailAddress, :setupform:isUserDeleted" />
<p:column headerText="#ID">
<h:outputText value="#{users.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{users.loginName}" />
</p:column>
...
</p:dataTable>
</p:panel>
</h:form>
</h:body>
</html>
And my bean looks like this:
#ManagedBean(name ="settingsbean")
#ViewScoped
public class SettingsBean {
private String userName;
private String userPassword;
private boolean deletedUser;
private List<UserDTO> userList;
private UserDTO selectedUser;
/*with getters and setters, what is uncenventional is this setter*/
public void setSelectedUser(UserDTO selectedUser) {
/*if admin selects/unselects a user from dataTable*/
this.selectedUser = selectedUser;
/*if unselect user*/
if(selectedUser == null){
userName = "";
mailAddress = "";
deletedUser = false;
/*if selects user*/
}else {
userName = selectedUser.getLoginName();
mailAddress = selectedUser.getMailAddress();
deletedUser = selectedUser.getDeleted();
}
}
...
public void addNewUser(){
//creates a new user in DB
}
public void updateUser(){
//will update user in DB
}
}
You have to process the components that you want to be updated
<p:commandButton id="modifyUser" value="Modify User" icon="ui-icon-wrench" update="userAddingGrid" action="#{settingsbean.updateUser}" process="userAddingGrid"/>
I have gone through a few answers on this topic already, especially from BalusC blogs. But its somehow not working in the implementation below. Am I missing something or doing something completely wrong.
I have a basic form with a few dropdowns, when I submit the form i.e. call submitDetails it returns the following String "phaseTwo?faces-redirect=true" which is backed by bean called PhaseTwoController.java
So on submit from phaseOne.xhtml I want to see phaseTwo.xhtml with values selected on phaseOne.xhtml
Here is the code:
THis is PhaseOne.xhtml backed by PhaseOneController.java
<h:form>
<p:panel header="Select country" style="margin-bottom:10px;">
<h:panelGrid columns="2" cellpadding="5">
<p:outputLabel for="country" value="Country: " />
<p:selectOneMenu id="country" value="#{phaseOneController.country}" style="width:150px">
<p:ajax listener="#{phaseOneController.onCountryChange}" update="subCategory" />
<f:selectItem itemLabel="Select Country" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{phaseOneController.countries}" />
</p:selectOneMenu>
<p:outputLabel for="province" value="Province: " />
<p:selectOneMenu id="province" value="#{phaseOneController.province}" style="width:150px">
<p:ajax listener="#{phaseOneController.onProvinceChange}" update="city" />
<f:selectItem itemLabel="Select Province" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{phaseOneController.provinces}" />
</p:selectOneMenu>
<p:outputLabel for="city" value="City: " />
<p:selectOneMenu id="city" value="#{phaseOneController.city}" style="width:150px">
<f:selectItem itemLabel="Select City" itemValue="" noSelectionOption="true" />
<f:selectItems value="#{phaseOneController.cities}" />
</p:selectOneMenu>
</h:panelGrid>
<p:separator />
<p:commandButton value="Select" actionListener="#{phaseOneController.submitDetails}" icon="ui-icon-check">
<f:param name="country" value="#{phaseOneController.country}" />
<f:param name="province" value="#{phaseOneController.province}" />
<f:param name="city" value="#{phaseOneController.city}" />
</p:commandButton>
</p:panel>
</h:form>
#ManagedBean
#RequestScoped
public class PhaseTwoController {
#ManagedProperty(value="#{param.country}")
private String country;
#ManagedProperty(value="#{param.province}")
private String province;
public void setCountry(String country) {
this.country = country;
}
public void setProvince(String province) {
this.province = province;
}
public void setCity(String city) {
this.city = city;
}
}
P.S. I havent posted the code for PhaseOneController.java as I am not sure if it is needed. But if someone wants to look at it, I can post it.
I have a huge problem with my jsf page. I have to pass a Parameter in Post request to a request scoped Bean. All works fine except one little bug. The button to update my information reacts only from second click on.
This Page has to be request scope.
Everytime i push the button it first runs the #PostConstruct and is then ready for a click. I tried to delete the PostConstruct method but my program than stops. I tried nearly everything. Any ideas please?
Here is my Code: I enter this page by calling the Methode "showEditEvent" from another Bean.
package model.backingBean.event;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
//import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import model.backingBean.system.SessionBean;
import model.bean.event.Event;
import model.database.EventManager;
import model.enums.EColorTheme;
import model.exceptions.DatabaseException;
import model.utility.Cryptography;
import model.utility.system.ConfigurationReader;
/**
* Bean for is responsible for the edit actions, which are performed with an
* event. That means you can change eventdetails.
*
* #author 101 Computing
*
*/
#ManagedBean
#RequestScoped
public class EditEventBean implements Serializable {
private static final long serialVersionUID = 1L;
private Event event;
private UIComponent generateVerCode;
private UIComponent updateButton;
private Part uploadedImage;
private static Logger logger = LogManager.getLogger(EditEventBean.class
.getName());
private String color;
private ResourceBundle rb = FacesContext.getCurrentInstance().getApplication().
getResourceBundle(FacesContext.getCurrentInstance(),"msgs");
#ManagedProperty("#{param.eventID}")
private int eventID;
/**
* Injects SessionBean.
*/
#ManagedProperty("#{sessionBean}")
private SessionBean sb;
public String showEditEvent(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
this.setEventID(eventID);
try {
this.event = EventManager.getEvent(eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_ERROR,
rb.getString("exceptions_database"), null);
fcxt.addMessage(null, msgs);
}
return "/facelets/eventAdmin/editEvent.xhtml";
}
public int getEventID() {
return eventID;
}
public void setEventID(int eventID) {
this.eventID = eventID;
}
/**
* Method initializes the event.
*
* #throws IOException
*/
#PostConstruct
public void init() {
FacesContext fcxt = FacesContext.getCurrentInstance();
String id = FacesContext.getCurrentInstance().getExternalContext()
.getRequestParameterMap().get("eventID");
if (id != null) {
this.eventID = Integer.parseInt(id);
try {
this.event = EventManager.getEvent(this.eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
}
}
/**
*
* #param eventID
* #return
*/
public void update(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
if (this.event.getEndOfEvent().after(this.event.getStartOfEvent())
&& this.event.getEntireTicketamount() > 0) {
if (this.uploadedImage != null) {
upload();
}
if (this.color.equals(EColorTheme.THEME_PINK.toString())) {
this.event.setColorTheme(EColorTheme.THEME_PINK);
} else if (this.color.equals(EColorTheme.THEME_BLUE.toString())) {
this.event.setColorTheme(EColorTheme.THEME_BLUE);
}
EventManager.updateEvent(this.event);
try {
this.event = EventManager.getEvent(this.eventID);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(
FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
// Message for updating
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_INFO,
rb.getString("editEvent_successUpdate"), null);
fcxt.addMessage(null, msgs);
} else {
// Message for updating
FacesMessage message = new FacesMessage("Not updated "
+ "- ends before it starts!");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(updateButton.getClientId(context), message);
}
}
/**
* Method generates a new verification code and saves it in the database.
*/
public void generateNewVerificationCode(int eventID) {
FacesContext fcxt = FacesContext.getCurrentInstance();
String newCode = verificationGenerator();
this.event.setVerificationCode(newCode);
try {
EventManager.setNewVerificationCode(this.event.getEventID(),
newCode);
} catch (DatabaseException e) {
FacesMessage msgs = new FacesMessage(FacesMessage.SEVERITY_ERROR,
rb.getString("exception_database"), null);
fcxt.addMessage(null, msgs);
}
FacesMessage message = new FacesMessage("New VC generated.");
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(generateVerCode.getClientId(context), message);
logger.info("Generated a new verification code for event with id="
+ this.event.getEventID() + ".");
}
And here is my Facelet
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<ui:composition template="../../templates/basicTemplate.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="eventID" value="#{editEventBean.eventID}" />
<f:viewAction action="#{editEventBean.init}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h1 style="color: #808080; font-size: large">#{msgs.event_editEvent_h1}
</h1>
<br />
<h:form enctype="multipart/form-data">
<f:view>
<input type="hidden" name="eventID"
value="#{editEventBean.eventID}" />
<h:outputText value="#{msgs.editEvent_pictureSize}" /> <br/>
<h:panelGrid columns="3">
<h:outputLabel for="eventPic" value="#{msgs.event_picture}" />
<h:inputFile id="eventPic" value="#{editEventBean.uploadedImage}" sizeLimit="20480"/>
<h:message for="eventPic" errorStyle="color:red" />
<h:outputLabel for="title" value="#{msgs.event_title}" />
<h:inputText id="title" value="#{editEventBean.event.title}"
required="true" requiredMessage="#{msgs.event_reqTitle}"
label="#{msgs.event_title}" size="74">
<f:validateLength minimum="2" maximum="70" />
</h:inputText>
<h:message for="title" errorStyle="color:red" />
<h:outputLabel for="description" value="#{msgs.event_description}" />
<h:inputTextarea id="description"
value="#{editEventBean.event.description}" required="true"
requiredMessage="#{msgs.event_reqDescription}"
label="#{msgs.event_description}" cols="60">
<f:validateLength minimum="2" maximum="500" />
</h:inputTextarea>
<h:message for="description" errorStyle="color:red" />
<h:outputLabel for="location" value="#{msgs.event_location}" />
<h:inputText id="location" value="#{editEventBean.event.location}"
required="true" requiredMessage="#{msgs.event_reqLocation}"
label="#{msgs.event_location}" size="50">
<f:validateLength minimum="2" maximum="50" />
</h:inputText>
<h:message for="location" errorStyle="color:red" />
<h:outputLabel for="startOfEvent"
value="#{msgs.event_editStartDate}" />
<h:inputText id="startOfEvent"
value="#{editEventBean.event.startOfEvent}" required="true"
requiredMessage="#{msgs.event_reqStartDate}"
label="#{msgs.event_startDate}" size="50">
<f:convertDateTime pattern="#{msgs.longDate}" />
</h:inputText>
<h:message for="startOfEvent" errorClass="error" />
<h:outputLabel for="endOfEvent" value="#{msgs.event_editEndDate}" />
<h:inputText id="endOfEvent"
value="#{editEventBean.event.endOfEvent}" required="true"
requiredMessage="#{msgs.event_reqEndDate}"
label="#{msgs.event_endDate}" size="50">
<f:convertDateTime pattern="#{msgs.longDate}" />
</h:inputText>
<h:message for="endOfEvent" errorClass="error" />
<h:outputLabel for="ticketAmount"
value="#{msgs.event_ticketAmount}" />
<h:inputText id="ticketAmount"
value="#{editEventBean.event.entireTicketamount}" required="true"
requiredMessage="#{msgs.event_reqTicketAmount}"
label="#{msgs.event_ticketAmount}" size="50">
<f:convertNumber integerOnly="true" />
</h:inputText>
<h:message for="ticketAmount" errorStyle="color:red" />
<h:outputLabel for="ticketPrice" value="#{msgs.event_ticketPrice}" />
<h:inputText id="ticketPrice"
value="#{editEventBean.event.ticketPrice}" required="true"
requiredMessage="#{msgs.event_reqTicketPrice}"
label="#{msgs.event_ticketPrice}" size="50">
<f:convertNumber type="currency" currencySymbol="€"
maxFractionDigits="2" />
</h:inputText>
<h:message for="ticketPrice" errorStyle="color:red" />
<h:outputLabel for="accountNumber"
value="#{msgs.event_accountNumber}" />
<h:inputText id="accountNumber"
value="#{editEventBean.event.accountNumber}" required="true"
requiredMessage="#{msgs.event_reqAccountNumber}"
label="#{msgs.event_accountNumber}" size="50">
<f:convertNumber integerOnly="true" />
</h:inputText>
<h:message for="accountNumber" errorStyle="color:red" />
<h:outputLabel for="cashPayment" value="#{msgs.event_cashPayment}" />
<h:selectBooleanCheckbox id="cashPayment"
value="#{editEventBean.event.cashPayment}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="creditPayment"
value="#{msgs.event_creditPayment}" />
<h:selectBooleanCheckbox id="creditPayment"
value="#{editEventBean.event.creditPayment}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="isActive" value="#{msgs.event_isActive}" />
<h:selectBooleanCheckbox id="isActive"
value="#{editEventBean.event.isActive}" />
<h:outputLabel></h:outputLabel>
<h:outputLabel for="isActive"
value="#{msgs.event_chooseTicketColor}" />
<h:selectOneMenu value="#{editEventBean.color}">
<f:selectItem itemValue="PINK" itemLabel="Pink" />
<f:selectItem itemValue="BLUE" itemLabel="Blue" />
</h:selectOneMenu>
<h:outputLabel></h:outputLabel>
<h:commandButton id="updateButton" value="#{msgs.event_update}"
action="#{editEventBean.update(editEventBean.eventID)}"
binding="#{editEventBean.updateButton}" />
<h:message for="updateButton" infoClass="info" />
</h:panelGrid>
<h:panelGrid columns="4">
<h:outputLabel for="verificationCode" value="#{msgs.event_vc}" />
<h:inputText id="verificationCode"
value="#{editEventBean.event.verificationCode}" readonly="true">
</h:inputText>
<h:commandButton id="generateVerCode"
value="#{msgs.event_generateVC}"
action="#{editEventBean.generateNewVerificationCode(editEventBean.eventID)}"
binding="#{editEventBean.generateVerCode}" />
<h:message for="generateVerCode"
infoStyle="color:darkgreen; font-weight: bold;" />
</h:panelGrid>
</f:view>
</h:form>
<br />
</ui:define>
</ui:composition>
Found my error. And it was as easy as frustrating…
the
h:form enctype="multipart/form-data"
needs an id. I need the enctype for uploading files. And then the form has to have an id…
Two pages helped me finding this bug:
"7. If a parent of the with the UICommand button is been rendered/updated by an ajax request beforehand, then the first action will always fail."
(commandButton/commandLink/ajax action/listener method not invoked or input value not updated)
and this example of using file upload:
http://jsflive.wordpress.com/2013/04/23/jsf22-file-upload/
It's difficult find such tiny errors if the code is not your own…
I am trying to set up 2 chained select boxes using JSF and PrimeFaces. I have created them as in the example on the official site, however:
When i enter the page using the new button(no existing record to be displayed) the change event will return a 500 error from the controller
When i enter the page using the edit button(there is an existing record) the change event will not return a 500 error, however the id from the select is not mapped to the record.
Any help would be appreciated.
Relevant code bits below:
<?xml version="1.0" encoding="UTF-8"?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:o="http://omnifaces.org/ui"
template="/WEB-INF/templates/page.xhtml">
<f:metadata>
<o:viewParam name="userUploadedWorkId" value="#{userUploadedWorkController.userUploadedWork}"
converter="#{userUploadedWorkConverter}"
converterMessage="Solicitare eronata. Va rugam sa navigati in aceasta pagina dintr-o lista de lucrari"/>
</f:metadata>
<ui:define name="bread-crumb">
<p:menuitem value="Lucrarile mele" outcome="user-uploaded-work-list?faces-redirect=true"/>
<p:menuitem
value="#{userUploadedWorkController.userUploadedWork.id eq null ? 'Lucrare noua' : userUploadedWorkController.userUploadedWork.title}"
url="#"/>
</ui:define>
<ui:define name="page-content">
<h:form>
<p:panelGrid columns="2" columnClasses="right-aligned,raw" id="user-uploaded-work-details">
<f:facet name="header">Detalii lucrare</f:facet>
<p:outputLabel value="Titlu" for="uuwTitle"/>
<p:inputText id="uuwTitle" value="#{userUploadedWorkController.userUploadedWork.title}" required="true"
style="width: 400px"/>
<p:outputLabel value="Capitol" for="chapter"/>
<p:selectOneMenu style="width: 400px" required="true" id="chapter" value="#{userUploadedWorkController.userUploadedWork.criterion eq null?'':userUploadedWorkController.userUploadedWork.criterion.chapter.id}" effect="fade">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{chapters}" var="ch" itemLabel="#{ch.name}" itemValue="#{ch.id}"/>
<p:ajax update="uuwCriterion" listener="#{userUploadedWorkController.chapterChange}"/>
</p:selectOneMenu>
<p:outputLabel value="Criteriu" for="uuwCriterion"/>
<p:selectOneMenu style="width: 400px" required="true" id="uuwCriterion" value="#{userUploadedWorkController.userUploadedWork.criterion eq null?'':userUploadedWorkController.userUploadedWork.criterion.id}" effect="fade">
<f:selectItem itemLabel="Select One" itemValue="" />
<f:selectItems value="#{userUploadedWorkController.criteria}" var="criterion" itemLabel="#{criterion.name}" itemValue="#{criterion.id}"/>
</p:selectOneMenu>
<f:facet name="footer">
<p:message for="uuwTitle"/>
<p:message for="uuwCriterion"/>
<p:message for="uuwChapter"/>
<p:commandButton action="#{userUploadedWorkController.save}" value="Salveaza atribute" process="#form"
update="#form :messages" icon="ui-icon-disk"/>
<p:button outcome="user-uploaded-work-list?faces-redirect=true" value="Lista lucrari"
icon="ui-icon-arrowreturnthick-1-e"/>
</f:facet>
</p:panelGrid>
</h:form>
</ui:define>
The managed bean:
#Named
#ViewScoped
public class UserUploadedWorkController implements Serializable {
private static final long serialVersionUID = -4736897416993974840L;
#Inject
private OrganizationalChartService service;
private UserUploadedWork userUploadedWork = new UserUploadedWork();
private List<Criterion> criteria;
public UserUploadedWork getUserUploadedWork() {
return userUploadedWork;
}
public void setUserUploadedWork(UserUploadedWork userUploadedWork) {
this.userUploadedWork = userUploadedWork;
}
#PostConstruct
public void init() {
criteria = service.findAllCriteria();
}
public List<Criterion> getCriteria() {
return criteria;
}
public void setCriteria(List<Criterion> criteria) {
this.criteria = criteria;
}
public String save() {
userUploadedWork.setCriterion(service.findById(Criterion.class, userUploadedWork.getCriterion().getId()));
userUploadedWork.setUser(service.findBySimpleProperty(User.class, "email", LoginController.getRequest().getUserPrincipal().getName()));
userUploadedWork = service.merge(userUploadedWork);
Messages.addFlashGlobalInfo("Salvare efectuata cu succes");
return "user-uploaded-work-list?faces-redirect=true";
}
public void chapterChange() {
if (userUploadedWork.getChapter() != null
&& userUploadedWork.getChapter().getId() != null) {
criteria = service.findCriteriaByChapter(userUploadedWork.getChapter().getId());
} else {
criteria = new ArrayList<Criterion>();
}
}
}
I have a web application which have to implement login. user provide username and pwd after authenticating user should redirect to page which they have privilages pages are differant from user to user. Sometimes 2 or more users can get same page but available data should differant for do this I have pass users privilage ID(divisionId) to other beans
for now i have tried URL tagging parameter tagged to URL and dirrect to page successfully but I can't take it to bean variable.
Itried this with p:Button then textbox inputs won't get to bean class to execute the method when button click.
xhtml code -
<h:body>
<p:growl id="growl" showDetail="true" life="3000" />
<p:dialog id="dialog" header="Login" widgetVar="dlg" visible="true" closable="false" >
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel for="username" value="Username: " />
<p:inputText id="username" value="#{loginBean.username}"
required="true" requiredMessage="Enter Username"/>
<h:outputLabel for="password" value="Password: " />
<p:password id="password" value="#{loginBean.password}"
required="true" requiredMessage="Enter Password"/>
</h:panelGrid>
<p:commandButton id="LoggingButton" value="Login" action="#{loginBean.doLogin()}"
update=":growl" oncomplete="handleLoginRequest(xhr, status, args),">
</p:commandButton>
</h:form>
</p:dialog>
</h:body>
loginbean-
public class LoginBean{
private String username;
private String password;
private int divisionId;
/**
* Creates a new instance of loginBean
*/
public LoginBean() {
}
public String doLogin() {
DbUser du = new DbUser();
divisionId = du.ValidateUser(username, password);
if(divisionId==0)
addMessage("Invalied username or password", false);
else{
if(divisionId==1){
// return "superuser.xhtml?faces-redirect=true";
return "superuser.xhtml?test="+divisionId+"faces-redirect=true";
//superAdmin
}
else if(divisionId==2||divisionId==3){
// return "engadmin_create_div.xhtml?faces-redirect=true";
return "engadmin_create_div.xhtml?test="+divisionId+"faces-redirect=true";
//ENG/IT ADMIN
}
else{
// return "viewonly_user.xhtml?faces-redirect=true";
return "viewonly_user.xhtml?test="+divisionId+"faces-redirect=true";
//View only users
}
}
return null;
}
I think that work :)
<p:growl id="growl" showDetail="true" life="3000" />
<p:dialog id="dialog" header="Login" widgetVar="dlg" visible="true" closable="false" >
<h:form id="form">
<h:panelGrid columns="2">
<h:outputLabel for="username" value="Username: " />
<p:inputText id="username" value="#{loginBean.username}"
required="true" requiredMessage="Enter Username"/>
<h:outputLabel for="password" value="Password: " />
<p:password id="password" value="#{loginBean.password}"
required="true" requiredMessage="Enter Password"/>
</h:panelGrid>
<p:commandButton id="LoggingButton" value="Login" actionListener="#{loginBean.doLogin()}">
</p:commandButton>
</h:form>
</p:dialog>
</h:body>
Bean
public class LoginBean{
private String username;
private String password;
private int divisionId;
/**
* Creates a new instance of loginBean
*/
public LoginBean() {
}
public static void redirect(String strDes) throws IOException {
ExternalContext ext = FacesContext.getCurrentInstance().getExternalContext();
ext.redirect(ext.getRequestContextPath() + strDes);
}
public void doLogin() {
DbUser du = new DbUser();
divisionId = du.ValidateUser(username, password);
if(divisionId==0)
addMessage("Invalied username or password", false);
else{
if(divisionId==1){
LoginBean.redirect("superuser.xhtml?test="+divisionId+"faces-redirect=true");
//superAdmin
}
else if(divisionId==2||divisionId==3){
LoginBean.redirect("engadmin_create_div.xhtml?test="+divisionId+"faces-redirect=true");
//ENG/IT ADMIN
}
else{
LoginBean.redirect("viewonly_user.xhtml?test="+divisionId+"faces-redirect=true");
//View only users
}
}
}
you get parameter from bean:
Map<String,String> params =
FacesContext.getExternalContext().getRequestParameterMap();
String action = params.get("test");