Form is not submitted - jsf

I wrote a simple JSF form. The problem is that there is a bug that I can't find. When I open the main page and enter the username and password the page must redirect me to the next page but this is not happening. Can you help me to find my mistake?
This is the main login JSF page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="resources/css/style.css" />
<script src="resources/js/cufon-yui.js" type="text/javascript"></script>
<script src="resources/js/ChunkFive_400.font.js" type="text/javascript"></script>
<script type="text/javascript">
Cufon.replace('h1',{ textShadow: '1px 1px #fff'});
Cufon.replace('h2',{ textShadow: '1px 1px #fff'});
Cufon.replace('h3',{ textShadow: '0px 1px #000'});
Cufon.replace('.back');
</script>
</head>
<body>
<div class="wrapper">
<div class="content">
<div id="form_wrapper" class="form_wrapper">
<form class="login active">
<h3><center><img src="resources/images/title.png"/></center></h3>
<div>
<label>Username:</label>
<h:inputText value="#{loginController.user}"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password:</label>
<h:inputSecret value="#{loginController.password}"/>
<span class="error">This is an error</span>
</div>
<div class="bottom">
<h:commandButton label="Login" value="Login" action="#{loginController.user_compare}"/>
<div class="clear"></div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
This is the managed bean
/** Bean for checking users and passwords.
If the user enters the correct username and password
the user will be redirected to main.xhtml
If not the page will refresh. */
package com.dx.sr_57;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
#Named("loginController")
#SessionScoped
public class user_check implements Serializable {
private String user;
private String password;
public user_check(){
}
public user_check(String user, String password){
super();
this.user = user;
this.password = password;
}
/** get the content of the variables from the JSF Login page */
public String setUser(String newValue) {
user = newValue;
return user;
}
public String getUser(){
return user;
}
public String setPassword(String newValue) {
password = newValue;
return password;
}
public String getPassword(){
return password;
}
public String user_compare() {
return "success";
}
}

You need to use a <h:form> component in order to get JSF inputs and commands to work.
So, replace
<form class="login active">
...
</form>
by
<h:form styleClass="login active">
...
</h:form>
You also need to fix your setters to be fullworthy setters, otherwise you might face a PropertyNotFoundException.
So, replace
public String setUser(String newValue) {
user = newValue;
return user;
}
public String setPassword(String newValue) {
password = newValue;
return password;
}
by
public void setUser(String newValue) {
user = newValue;
}
public void setPassword(String newValue) {
password = newValue;
}
Unrelated to the concrete problem, the HTML <center> tag is deprecated since 1998 and invalid in XHTML strict. Remove it. You need to set CSS text-align: center on the <img> instead.

Related

After form submission , using java ee and jsf 2,2, my backing bean properties are still null

Basically , in the input.xhtml there is a form which takes a username and password and if they are equal to a specific value(doesn't matter the value) the program should print a message in the browser, but this doesn't happen. To make sure of the problem i added 2 lines of "System.out.println(...)" where i print the value of the property and what i found out is that the properties are still null even after i submit. So after i click send in the console is written "null null". Any help is appreciated!
This is the UserBean class (backing bean)
package bean;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class UserBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String password;
private String output_message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String go(){
output_message = "";
if(name == null && password == null){
output_message += "Both fields cannot be empty!";
}else if(name == "name" && password == "pass"){
output_message += "Success!";
}else{
output_message += "Data is wrong!";
}
System.out.println(name);
System.out.println(password);
return output_message;
}
public String getOutput_message() {
return output_message;
}
public void setOutput_message(String output_message) {
this.output_message = output_message;
}
public String ret(String r){
return r;
}
}
This is the input.xhtml file, that contains the form that will submit the data to the bean. (Ignore the url to template.xhtml, it's just a parent template that has a header and a footer other than the mid-content that input.xhtml defines)
<!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:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:cc="http://java.sun.com/jsf/composite/myComponent">
<ui:composition template="/WEB-INF/templates/template.xhtml">
<ui:define name="content">
<style type="text/css">
#form1{
position: absolute;
top: 20%;
left:40%;
border: 1px solid black;
background-color: orange;
}
td{
padding-top:10px;
}
input[type="text"]{
backgorund-color:blue;
}
</style>
<form id="form1" method="post">
<table columns="2">
<tr>
<td><span>Emri:</span></td>
<td><input type="text" id="emri" value="#{userBean.name}"/></td>
</tr>
<tr>
<td><span>Password:</span></td>
<td><input type="password" id="pass" value="#{userBean.password}"/></td>
</tr>
<tr>
<td colspan="2" align="center"><button type="submit" onclick="#{userBean.go()}">Send</button></td>
</tr>
</table>
</form>
<p>#{user.output_message}</p>
</ui:define>
</ui:composition>
</html>
The problem caused by the button html tag. Don't use HTML buttons or anchors if you want to use the JSF mechanism. Instead use (button/link) components to submit the page. Define the navigation rules ot the userBean.go should pass back the next page name.
I just solved this. the problem was with the input tag, the value attribute does not represent the value written in the textbox is just some kind of a default value or somekind of a pre-value. Anyway instead of input and form tags i used and which worked out fine
h is a namespace with url xmlns:h="http://xmlns.jcp.org/jsf/html"

Getting 404 error when trying to load Partial View into a View using MVC 5 and ASP.net 4.5

I have been working on this for a couple of weeks now. I’ve tried displaying my partial view into a view using many different methods (Html.Action, Html.Partial, Html.RenderAction & Html.RenderPartial). I’m getting a 404 error, which to me means that the ID is not getting passed into the controller action. This is just an assumption. The partial view I’m working with can be displayed directly by passing a URL parameter like so. https://siteurl.net/PersonalOffers/Snippet/2763795c-2d7b-462a-a7f6-ff966be83cfe I would like for the _Snippet Partial View to display in the Index page like so. https://siteurl.net/PersonalOffers/Index/2763795c-2d7b-462a-a7f6-ff966be83cfe I believe the answer lies in this post, but I can’t get the correct code combinations to work. How can I pass parameters to a partial view in mvc 4
What code should I use for the View? Here is the code I'm working with. Thanks!
ViewModel (SnippetViewModel.cs)
using SiteName.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SiteName.Web.ViewModels
{
public class SnippetViewModel
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Terms { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public string Image { get; set; }
public string QrImageCode { get; set; }
public string RedemptionLimit { get; set; }
public List<OfferLocation> OfferLocations { get; set; }
}
}
Partial View (_Snippet.cshtml)
#using Zen.Barcode;
#using Zen.Barcode.Web;
#using Zen.Barcode.Web.Mvc;
#model SiteName.Web.ViewModels.SnippetViewModel
<!doctype html>
<html lang="en">
<head>
<title>Offer Snippet</title>
#Styles.Render("~/Content/css")
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.centerPS {
margin: auto;
width: 20%;
padding: 5px;
}
</style>
</head>
<body>
<div id="content-wrapper" style="padding:5px; font-family: 'Times New Roman', Times, serif; font-size:22px;">
<div class="container">
<div class="page-header" style="text-align:center;"><h1><b>#Model.Name</b></h1></div>
<div class="well" style="text-align:center;">
<img src="#Model.Image" alt="Offer Image" /><br /><br />
<!-- Consumer Summary -->
<div class="row">
<div class="col-md-3 consumer-summary">
<div class="preloader-con">
<span><img src="~/Content/images/loader5.gif" /> Loading Consumer Details ...</span>
</div>
</div>
</div>
<div style="text-align:center; margin-bottom:20px; font-size:18px;"><div style="width:250px; display:inline-block;">#Model.Description</div></div>
<div style="text-align:center; margin-bottom:20px; font-size:18px;"><div style="width:250px; display:inline-block;">#Model.Terms</div></div>
<div style="text-align:center; margin-bottom:20px; font-size:18px;">
<div style="text-align:center;">Valid at:</div>
<div style="font-size: 14px; text-align:center;">
#foreach (var offerLocation in #Model.OfferLocations)
{
<p style="margin:0; padding:0;">#offerLocation.MerchantLocation.CompleteAddress</p><br />
<p style="margin:0; padding:0;">#offerLocation.MerchantLocation.Name</p>
}
</div>
</div>
<div style="clear:both; margin-bottom:20px;"></div>
<div style="text-align:center; font-size:18px;">
<div style="text-align:center;">
<div>Starts on: #Convert.ToDateTime(Model.StartDate).ToString("MM/dd/yyyy hh:mm tt")</div>
<div>Redeem by: #Convert.ToDateTime(Model.EndDate).ToString("MM/dd/yyyy hh:mm tt")</div>
<br />
<div>Redemption Limit: #Model.RedemptionLimit</div>
</div><br />
<div style="text-align:center;">
<img width="130" src="data:image/jpeg;base64,#Model.QrImageCode" />
</div>
</div>
<div style="clear:both; margin-bottom:20px;"></div>
<div style="text-align:center; margin-bottom:20px; font-size:20px;">#Model.Id</div>
<div style="text-align:center;"><h3>Mobile Wallet Pass</h3></div>
<!-- PassSlot widget -->
<div id="pslot-widget-container" class="centerPS" data-passtemplate="https://d.pslot.io/BqRFTzQ7M" data-show="true" data-zoom="50" data-placeholder-name="#Model.Name" data-placeholder-description="#Model.Description" data-placeholder-termsconditions="#Model.Terms" data-placeholder-expirydate="#Convert.ToDateTime(Model.EndDate).ToString("MM/dd/yyyy hh:mm tt")"></div>
<br />
<div style="text-align:center; margin-bottom:20px; font-size:20px;"><b>Powered by</b> <img src="~/Content/images/SiteName-blue.png" width="150" alt="SiteName Logo" style="margin-bottom: -6px;" /></div>
</div>
<!-- End Well -->
</div>
<!-- End Container -->
</div>
<!-- End Wrapper -->
<!-- PassSlot widget Java Script -->
<script id="pslot-wjs" src="https://www.passslot.com/public/passslot/pslot/widget/widget.js" type="text/javascript"></script>
<!-- Consumer Details Java Script -->
<script src="~/Scripts/SiteNameApp/consumer-details.js" type="text/javascript"></script>
</body>
</html>
Controller (PersonalOffersContoller.cs)
using SiteName.Infrastructure.Services;
using SiteName.Web.ViewModels;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Zen.Barcode;
using Zen.Barcode.Web;
using Zen.Barcode.Web.Mvc;
namespace SiteName.Web.Controllers
{
public class PersonalOffersController : Controller
{
private IOfferService _offerService;
private IOfferLocationService _offerLocationService;
private IUniqueOfferService _uniqueOfferService;
private IMerchantConsumerService _merchantConsumerService;
public PersonalOffersController(IOfferService offerService, IOfferLocationService offerLocationService, IUniqueOfferService uniqueOfferService, IMerchantConsumerService merchantConsumerService)
{
_offerService = offerService;
_offerLocationService = offerLocationService;
_uniqueOfferService = uniqueOfferService;
_merchantConsumerService = merchantConsumerService;
}
// Index view
public ActionResult Index(Guid id)
{
ViewData["id"] = id;
return View();
}
// GET: PublicOffers
public async Task<ActionResult> Snippet(Guid id)
{
var offer = await _offerService.FindAsync(id);
var offerLocations = await _offerLocationService.GetByOfferIdAsync(offer.Id);
var barcodeString = "https://sitename.net/PersonalOffers/Snippet/" + offer.Id.ToString();
CodeQrBarcodeDraw bd = BarcodeDrawFactory.CodeQr;
Image img = bd.Draw(barcodeString, 30, 3);
string limit = "";
if (offer.Limited && offer.RedemptionLimit != 0)
limit = offer.RedemptionLimit.ToString();
else
limit = "Unlimited";
SnippetViewModel model = new SnippetViewModel()
{
Id = offer.Id,
Name = offer.Name,
Description = offer.Description,
Terms = offer.TermsConditions,
OfferLocations = offerLocations.ToList(),
StartDate = offer.StartDate,
EndDate = offer.EndDate,
Image = "https://sitenamestorage.blob.core.windows.net/offers/thumb_" + offer.OfferImage,
RedemptionLimit = limit,
QrImageCode = this.getBase64Code(img)
};
return PartialView("_Snippet", model);
}
private string getBase64Code(Image img)
{
using (MemoryStream ms = new MemoryStream())
{
img.Save(ms, ImageFormat.Jpeg);
byte[] imageBytes = ms.ToArray();
string base64String = Convert.ToBase64String(imageBytes);
//string src = "data:image/jpeg;base64," + base64String;
return base64String;
}
}
}
}

Not able to call processAction of Portlet

My game.jsp code -
<%#page import="java.io.Console"%>
<%#page import="com.liferay.portal.kernel.util.WebKeys"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<portlet:defineObjects />
<script>
function updateGames() {
document.getElementById("gameForm").submit();
}
</script>
<portlet:actionURL name="sampleActionUrl" var="sampleActionUrl">
</portlet:actionURL>
<form id="gameForm" action="${sampleActionUrl}">
<div onclick="updateGames()">CLICK HERE</div>
</form>
My Portlet Code -
package com.home;
import java.io.IOException;
public class Game extends GenericPortlet {
#Override
#RenderMode(name = "VIEW")
protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
response.setContentType(request.getResponseContentType());
PortletContext context = getPortletContext();
PortletRequestDispatcher rd = context
.getRequestDispatcher("/WEB-INF/jsp/game.jsp");
System.out.println("Game.doView() >> rendering");
rd.include(request, response);
}
#Override
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {
System.out.println("Game.processAction() >> processAction");
}
}
When the Form is submitted on click of the div.
doView gets called for rendering the portlet, but not the processAction.
Is there anything I am missing?
Please use below code and give a try
<portlet:actionURL name="sampleActionUrl" var="sampleActionUrl">
</portlet:actionURL>
<form id="gameForm" action="<%=sampleActionUrl.toString()%>" method="post">
<input type="hidden" id="env" name="env"/>
<div onclick="updateGames()">CLICK HERE</div>
</form>
<script>
function updateGames() {
document.getElementById("env").value = 'DEV';
document.getElementById("gameForm").submit();
}
</script>
If you are not using JSTL then you can use <%=sampleActionUrl.toString()%> instead of ${sampleActionUrl}
update
remove below piece of code
#RenderMode(name = "EDIT")
First check that you have set the following in WEB-INF\portlet.xml
<portlet>
...
<portlet-class>com.home.Game</portlet-class>
...
</portlet>

Login required twice after logging out due to ViewExpiredException

I have a JSF page on Websphere Process Server (on top of WAS 7) which has ViewExpiredException. When this happens I want the user to be logged out and then logged back in
I've set up a redirect on this exception in web.xml to the following logout page:
<%
session.invalidate();
response.sendRedirect("ibm_security_logout?logoutExitPage=/faces/ToDosOpen.jsp");
%>
Which then redirects to a login page:
<%# page import="com.ibm.wbit.tel.client.jsf.infrastructure.Messages, java.util.Locale" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%
String contextPath = request.getContextPath();
Locale locale = request.getLocale();
final String SECURITY_CHECK = "j_security_check";
%>
...
</head>
<body>
...
<h1><%= Messages.getString("LOGIN_LINE", locale) %></h1>
<div class="help-text"><%= Messages.getString("LOGIN_LINE_DESCR", locale) %></div>
<form target="_top" method="POST" action=<%= SECURITY_CHECK %>>
<table id="login-form">
<tr>
<td><%= Messages.getString("LOGIN_NAME", locale) %>:</td>
<td><input type="text" name="j_username"></td>
</tr>
<tr>
<td><%= Messages.getString("LOGIN_PASSWORD", locale) %>:</td>
<td><input type="password" name="j_password"></td>
</tr>
<tr>
<td id="login-button" colspan="2">
<input type="submit" name="login" value="
<%= Messages.getString("BUTTON_LOGIN", locale) %>"></td>
</tr>
</table>
</form>
And when you login you're redirected to the page that caused the exception in the first place. Except what actually happens is the exception is thrown again, and back we go to the login page.
So you have to login twice.
Not sure what to do about this or where to start looking. Any help would be appreciated.
I have looked through existing questions on this and haven't been able to solve it.
EDIT: I've forgotten to mention that this works fine if the action that triggered the exception was a refresh, but fails (having to login twice) if the action was clicking on a commandbar.
Finally solved it using the following ViewHandler.
This basically recreates the view that expired. In the case where there were POST parameters, they've obviously been lost so any view that cannot be created without them needs special handling.
Hopefully this is useful to anyone else who runs into this problem, and please let me know if you see anything wrong with this solution because I am not 100% confident in it.
/**
* This class just handles cases where the session expired
* which causes an exception on reload.
*/
public class ViewExpiredHandler extends ViewHandlerWrapper {
private ViewHandler wrapped;
public ViewExpiredHandler(ViewHandler wrapped) {
this.wrapped = wrapped;
}
#Override
public UIViewRoot restoreView( FacesContext ctx, String viewId )
{
UIViewRoot viewRoot = super.restoreView( ctx, viewId );
try {
if ( viewRoot == null) {
viewRoot = super.createView( ctx, viewId );
ctx.setViewRoot( viewRoot );
}
} catch (Exception e) {
e.printStackTrace();
}
return viewRoot;
}
#Override
protected ViewHandler getWrapped() {
return wrapped;
}
}

Manage back and forward in Richfaces

I'm using RichFaces component library and I want to manage the history of Ajax navigation, so the enduser can use the browser back and forward buttons.
Is there any clean way to do it, design pattern, library, etc?
You can use RSH to handle Ajax history
For the example lets assume that you have a page where the user should select a color.
Then, the selected color is posted to the server using XmlHttpRequest.
Now we want to restore previous selection when the back and forward navigation buttons is pressed.
Code Example
Bean:
public class Bean {
private static final String DAFAULT_COLOR = "green";
private Map<String, Color> colors;
private Color selectedColor;
private String restoredColor;
#PostConstruct
public void init() {
this.colors = new HashMap<String, Color>();
this.colors.put("green", new Color("Green", "008000"));
this.colors.put("blue", new Color("Blue", "0000FF"));
this.colors.put("red", new Color("Red", "FF0000"));
this.colors.put("purple", new Color("Purple", "FF0000"));
this.colors.put("purple", new Color("Purple", "800080"));
this.colors.put("yellow", new Color("Yellow", "FFFF00"));
this.colors.put("silver", new Color("Silver", "C0C0C0"));
this.colors.put("black", new Color("Black", "000000"));
this.colors.put("white", new Color("White", "FFFFFF"));
this.selectedColor = this.colors.get(DAFAULT_COLOR);
}
public void setSelectedColor(ActionEvent event) {
UIComponent component = event.getComponent();
String color = ((String)component.getAttributes().get("color")).toLowerCase();
this.selectedColor = this.colors.get(color);
}
public void restoreColor() {
if(restoredColor.equals("") || restoredColor.equals("null")) {
restoredColor = DAFAULT_COLOR;
}
this.selectedColor = this.colors.get(restoredColor);
}
public List<Color> getColors() {
return Arrays.asList(colors.values().toArray(new Color[0]));
}
public Color getSelectedColor() {
return selectedColor;
}
public String getRestoredColor() {
return restoredColor;
}
public void setRestoredColor(String restoredColor) {
this.restoredColor = restoredColor.toLowerCase();
}
}
View:
<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:t="http://myfaces.apache.org/tomahawk"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
template="/WEB-INF/template/default.xhtml">
<ui:define name="head">
<script type="text/javascript" src="#{request.contextPath}/js/rsh/rsh.js"></script>
<script type="text/javascript">
window.dhtmlHistory.create({
toJSON: function(o) {
return Object.toJSON(o);
},
fromJSON: function(s) {
return s.evalJSON();
}
});
Event.observe(window, 'load', function() {
dhtmlHistory.initialize();
dhtmlHistory.addListener(handleHistoryChange);
});
var registerHistoryPoint = function(newLocation, historyData) {
dhtmlHistory.add(newLocation, historyData);
};
</script>
</ui:define>
<ui:define name="content">
<a4j:form id="frmColor">
<div class="colors">
<ul>
<a4j:repeat value="#{bean.colors}" var="color">
<li style="background:##{color.hex};">
<a4j:commandLink value=" "
actionListener="#{bean.setSelectedColor}"
reRender="frmColor"
oncomplete="registerHistoryPoint('#{color.name}', '#{color.name}');">
<f:attribute name="color" value="#{color.name}"/>
</a4j:commandLink>
</li>
</a4j:repeat>
</ul>
</div>
<div class="selection" style="background:##{bean.selectedColor.hex};">
<div class="selected-color"
style="color: ##{bean.selectedColor.name eq 'White' or
bean.selectedColor.name eq 'Yellow' ? '000000' : 'ffffff'}">
<h:outputText value="#{bean.selectedColor.name}"/>
</div>
</div>
<a4j:jsFunction name="handleHistoryChange" reRender="frmColor"
action="#{bean.restoreColor}">
<a4j:actionparam name="historyData" assignTo="#{bean.restoredColor}" />
</a4j:jsFunction>
</a4j:form>
</ui:define>
</ui:composition>
Now when the user click on a color the registerHistoryPoint is invoked. This will register historyData that will be passed to the bean when the back and forward buttons is pressed.
e.g.
User select Yellow.
Yellow is registered.
User select Blue.
Blue is registered.
User click on back.
Yellow is restored.
User click forward.
Blue is restored.

Resources