error message not displayed using html:errors in struts 1.3.10 - struts-1

In JSP page having one textbox name and button Login
<html:form action="login">
<html:text property="name"/>
<html:submit value="Login" />
</html:form>
<html:errors/>
and in StructsActionForm has validate() method like
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if (getName() == null || getName().length() < 1) {
errors.add("name", new ActionMessage("error.name.required"));
// TODO: add 'error.name.required' key to your resources
}
return errors;
}
if textbox name has an empty input when Login clicks it should show the error message error.name.required with the help of <html:errors/>, but it not showing the error message.
I am using Net-beans 8.0, Struts 1.3.10.
Pls help me out of this problem Thanks in advance.

i just missed the value of the key in
ApplicationResource.properties
so i cant able to get the error details.just add the value and i got the answer while running the program.
Thanks for the reply..

Related

Form validation in Spring

I want to show errors for all the form, not single field. So I did this:
public void validate(Object target, Errors errors) {
AddUserForm addUserForm = (AddUserForm) target;
if (addUserForm.getPassword().length() == 0) {
errors.reject("Message error");
}
}
Now I'm using reject method instead of rejectValue, because I don't need to set error message to one field.
And this is my jsp:
<form:form method="POST" commandName="addUserForm"
class="form-horizontal" style="width: 510px;">
<form:errors ??? />
...
Which attribute should I use now? I was trying this:
<form:errors commandName="addUserForm"/>
But doesn't help.
If you are rejecting by using a fieldName in form object as:
errors.rejectValue("fieldName", "errorMessage");
This you can display in view as:
<form:errors path="fieldName"/>
If you are rejecting without specifying the fieldname in form object i.e., raising the error on whole form object then you can set these errors as:
errors.reject("Message error");
This you can display in view without any attributes as:
<form:errors/>

Spring MVC : How to pass Model object from one method in controller to another method in same controller?

I have integrated Spring Security in my application , and would like to display an error message to the user in case of Bad credentials.
jsp:
<c:out value='${secerror}' /> //prints nothing on screen
<c:if test="${empty secerror}">
error is empty or null. //always prints this line on screen
</c:if>
<c:if test="${not empty secerror}">
<div class="errorblock">
Your login attempt was not successful, try again.<br /> Caused :
${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
</div>
</c:if>
<c:set var = "url" value = "/j_spring_security_check" />
<form:form method="post" commandName="portalLogin" action="${pageContext.servletContext.contextPath}${url}" name="f">
[Update]: Sorry all, i realized that my Model object was getting overriden after i redirect to portalLogin.html as i had created a new model object created there previously.
But i tried few easy options by which i can pass Model object from one controller method to another method in the same controller. But nothing worked.
I tried using forward: prefix instead of redirect prefix. For this, i didn't get error message at all.
I tried below code in loginerror method.
return new ModelAndView("portalLogin","secerror","true");
I was getting following error for the above code:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'portalLogin' available as request attribute
I did come across this link, but i found it to be a very lengthy solution and wasn't sure if iv'e to write that much code.
I wasn't sure if i can use Model object for #ModelAttribute annotations#ModelAttribute.
Please provide me with code snippets / examples which i can try out.
My controller method is like this:
#RequestMapping("/portalLogin")
public ModelAndView goToLogin(Model model) {
try {
System.out.println("Enter goToLogin************************");
} catch (Exception exception) {
}
return new ModelAndView("portalLogin", "portalLogin", new LoginModel());
//return new ModelAndView("portalLogin", model);
}
#RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public ModelAndView loginerror(ModelMap model) {
//model.addAttribute("secerror", "true");
//return "redirect:portalLogin.html";
return new ModelAndView("portalLogin","secerror","true");
}
[Update]: As a work around i added goToLogin method logic inside loginerror method as my only intention is to get portalLogin page. Error was thrown as expected.
#RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public ModelAndView loginerror(Model model) {
model.addAttribute("secerror", "true");
return new ModelAndView("portalLogin", "portalLogin", new LoginModel());
}
But still i would like to know if i can pass Model object from one controller method to another method in the same controller through some way.
You can also try something like this
<c:if test="${not empty secerror == 'true'}">
<tr>
<td colspan="2" align="center"><font style="color: red">Your login attempt was not successful, try again</font>
</td></tr></c:if>
Let`s make things easy, if you want to show a Bad credentials message, you can simply do something like this:
In your spring-security.xml:
<sec:form-login login-page="/login.jsp"
default-target-url="/default-url-when-login-correct"
authentication-failure-url="/login.jsp?error=true"
login-processing-url="/login" always-use-default-target="true" />
In your login.jsp:
<c:if test="${not empty param.error}">
<span>${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}</span>
</c:if>

how to use custom validation message for html form in liferay6 with custom portlet?

I am using liferay to develop a custom portlet (mvc portlet) my problem is that i have one form in jsp page in HTML and and what i want is to validate some field of the forms.and on submit button its redirecting to another page.the validation i have done is working but what happen is when am clicking the submit button its redirect to another page and on that page its just showing default error from liferay. What i want is to display same page if request not completed with the error message near the field which validation has false.
How can i solve this issue?
this is my code to checking validation while add method in action class
public void addRestaurant(ActionRequest request, ActionResponse response) {
log.info("Inside addRegistration");
List<String> errors = new ArrayList<String>();
restaurant rest = RestaurantActionUtil
.getRestaurantFromRequest(request);
boolean restValid = RestaurantValidator
.validateRestaurant(rest, errors);
if (restValid) {
try {
log.info(rest);
restaurant test = restaurantLocalServiceUtil
.addrestaurant(rest);
if (test == null) {
log.error("Restaurant was Found Null");
response.setRenderParameter("jspPage", errorJSP);
return;
}
} catch (SystemException e) {
log.error(e);
/*
* If there is an error then divert the control to the error
* page.
*/
response.setRenderParameter("jspPage", errorJSP);
return;
}
SessionMessages.add(request, "restaurant-added");
return;
} else {
for (String error : errors) {
SessionErrors.add(request, error);
}
SessionErrors.add(request, "error-while-adding");
request.setAttribute("rest", rest);
return;
}
}
This is my validator class
public class RestaurantValidator {
public static boolean validateRestaurant(restaurant rest, List errors) {
boolean valid=true ;
if (Validator.isNull(rest.getName())) {
errors.add("Name-required");
valid = false;
}
if (Validator.isNull(rest.getLicensekey())) {
errors.add("license-key-required");
valid = false;
}
following is my view.jsp code
Restaurant Name*
" />
<span class="help-block">help block</span>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<label>License Key<span class="f_req">*</span></label>
<liferay-ui:error key="license-key-required" message="license-key-required" />
<input type="text" name="licensekey" class="span8" value="<%=restaurantOBJ.getLicensekey() %>"/>
</div>
</div>
the error message is deisplaying on the redirected page with following way rather then on same page i want the error near textbox of name with the error of "Name_required"
The error message is displaying on the redirected page the following way rather then on same page, I want the error near the name-textbox with the error of "Name_required".
what I want is when name is blank then it should not submit the form and give error near text box of name in my view.jsp page.
I would try to answer your question, try to set a actionResponse.setRenderParameter("valid", "NO"); in your addRestaurant method if the validation fails.
And get this parameter in the doView method and set the renderPage accordingly in this method: include(renderPage, renderRequest, renderResponse); at the end of the doView method.
If you can provide all the information in your question with nice formatting like the validator method, <aui:form> and the javascript method called on onSubmit then we can go ahead with looking for other solution.
In the mean-while you can try this out and see if it works. :-)

Value remains in form field after it is cleared in bean in JSF2

In my JSF2 application, I have "Clear" button, which is supposed to clear all the fields. However, it doesn't always work.
My page fragment:
<h:form id="bi">
<h:inputText value="#{bean.entity.firstname}" />
<h:inputText value="#{bean.entity.surname}" />
<h:commandButton value="Clear" immediate="true" action="#{bean.clear}">
<f:ajax render="bi" />
</h:commandButton>
<h:commandButton value="Submit" action="#{bean.submit}" />
</h:form>
And clear() method in my bean:
public void clear() {
entity = new Entity();
}
If I enter values in the fields, and click "Clear", everything is cleared as expected. However, consider such scenario:
1. Enter value only in one field (both are required by JSR303 annotations on entity).
2. Click "Submit". Error message appears.
3. Click "Clear".
Entered value remains. Why is it not cleared?
Moreover, if I clear it by hand, and click "Clear", it returns to the field. I checked that it comes to the browser in partial response after clicking "Clear" button. I suspect it has something to do with view state.
Moreover, if I add validator="#{bean.validate}" to the field, it enter this validation. Even if button has immediate="true" attribute. Why? Shouldn't immediate button ommit validation?
You've run into a more or less well-known issue regarding updating components for which validation has already happened.
This post is rather old, but still relevant: http://ishabalov.blogspot.com/2007/08/sad-story-about-uiinput.html
There is a community created solution for A4J in JSF 1.2 posted here: http://community.jboss.org/thread/8446?start=15&tstart=0
But unfortunately, this doesn't work directly in JSF 2.0 and in your case it wouldn't work at all since it's A4J specific. Nevertheless it might be a source of inspiration.
Basically you need to walk the component tree and clear its state. The neatest thing is to clear exactly the state of the components that you are going to re-render. But you might take the brute-force approach and just clear all if your particular application or page can tolerate that.
I wound up having to avoid submit or action to get the form to clear properly. I used actionListener with a void bean method instead.
But then I faced the problem of conditionally needing navigation which is usually done with a String method from action. I used ExternalContext.redirect() to accomplish that which I learned from the following:
JSF PostConstruct Exception Handling - Redirect
JSF navigation redirect to previous page
my page code:
<p:commandButton value="Login" update=":loginForm"
actionListener="#{loginBean.login}"/>
my bean code:
public void login() {
RtsLDAPAD laLdap = new RtsLDAPAD();
boolean lbAuthenticated = false;
try
{
lbAuthenticated = laLdap.login(userName, password);
System.out.println(
"The Result is " + lbAuthenticated + " for " + userName);
}
catch (Exception aeRTSEx)
{
aeRTSEx.printStackTrace();
}
if (lbAuthenticated) {
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("taskform.jsf");
} catch (IOException e) {
e.printStackTrace();
}
} else {
FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null,
new FacesMessage("Login failed for " + userName + "."));
UIViewRoot uiViewRoot = facesContext.getViewRoot();
HtmlInputText inputText = null;
Password pwd = null;
inputText = (HtmlInputText) uiViewRoot.findComponent("loginForm:username");
inputText.setSubmittedValue(null);
inputText.setValue(null);
inputText.setLocalValueSet(false);
inputText.setValid(true);
pwd = (Password) uiViewRoot.findComponent("loginForm:password");
pwd.setSubmittedValue(null);
pwd.setValue(null);
pwd.setLocalValueSet(false);
pwd.setValid(true);
userName = null;
password = null;
}
}

Access model objects from view in Spring 2.5

Is there a way to access the objects in the model set by a Controller on a View in Spring 2.5? I'm using a SimpleFormController but instead of using a proper Validator, I perform the checks directly into the onSubmit() method because I'm working with jQuery on the client side and I don't want the whole ViewForm (a complete page) to be shown in case of errors (in which case I send back the HTML block with some error strings).
I'm therefore creating my own map in the onSubmit() but I can't manage to read it from the JSP page. Is there a clean way of doing this in Spring 2.5?
This is the first version of my controller:
protected ModelAndView onSubmit( Object command,
BindException errors ) throws Exception {
User user = ( User )command;
// This is a common validator that I wanted to remain untouched.
validator.validate( user, errors );
// In this way I wanted to try to have both errors and the model in the view.
return new ModelAndView( getSuccessView(), "model", errors.getModel() );
}
As I couldn't access the error list from my jsp, I tried to change the controller by using a class (KeepInformedPageData) that re-maps the model and the error in a new map that I know how to access:
protected ModelAndView onSubmit( HttpServletRequest request,
HttpServletResponse response,
Object command,
BindException errors ) throws Exception {
KeepInformedPageData pageData = new KeepInformedPageData( messageSource, request.getLocale() );
User user = ( User )command;
// This is a common validator that I wanted to remain untouched.
validator.validate( user, errors );
// As I couldn't access the model provided by errors.getModel(), I tried to
// build up my own model but unfortunately with the same result.
pageData.addErrors( errors );
pageData.addCommandModel( errors.getModel() );
return new ModelAndView( getSuccessView(), "model", pageData.getRebuiltModel() );
}
I tried every possible combination on the jsp side but with no result, these are some of the attempts:
<br />
${model.command.email}
<br />
${model.errors.defaultMessage}
<br />
<form:form name="command" action="index.htm" method="POST">
<form:errors path="model.invalid.email" />
<div>Email <input type="text" name="email" value="Your email address"></div>
<div><input type="submit" value="Submit" /></div>
</form:form>
So the final question is: how do I access the Map received from the controller?
http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/mvc/SimpleFormController.html
Method onBindAndValidate
Ok, maybe it was too simple to be even considered a problem: while trying to work on the "errors" object received as a parameter in my Controller, I realized there was a method "getModel()" and from such a property I was trying to get all the subproperties coming from the command and this was the mistake that pushed me in the wrong direction.
I'm now simply passing the "errors" object from the Controller:
return new ModelAndView( getSuccessView(), "dataBlock", errors );
And I'm using the properties in the "errors" object within the JSP page:
<div>${resultBlock.fieldError.defaultMessage}</div>

Resources