Why Spring Security is not working in my Spring Boot project? - security

MY QUESTION! WHY Once admin or users after login, they can not get on their dashboards. It updates the pages "/" or "/ home", but does not go
to UserDashboards or AdminDashboards?!
I am trying to configure Spring boot with Spring security and DB() for an application.
I have login-form in my home.jsp. User can login or registred in my site in modal window.
I will show you only a portion of home.jsp
<!-- Header -->
<li><spring:message code="nav.section.link5"/></li>
<c:if test="${email == null}">
<li><spring:message code="nav.section.link6"/></li>
<li><spring:message code="nav.section.link9"/></li>
</c:if>
<c:if test="${email != null}">
<li>${email}</li>
<li><spring:message code="nav.section.link10"></spring:message> </li>
</c:if>
<!-- modal login
================================================== -->
<div class="modal" id="modal-1">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default active"><spring:message code="nav.section.link6"/></button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal-2" data-dismiss="modal"><spring:message code="nav.section.link9"/></button>
</div>
</div>
</div>
<div class="modal-footer">
<div align="center">
<ul class="sign-social-icon">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="or">
<p><spring:message code="modal.section.h3"/></p>
</div >
<form:form method="post" action="/userLogin" id="contact-formL" class="form-horizontal">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<div class="control-group controls">
<input type="email" class="reg" placeholder="<spring:message code="modal.section.h6"/>" name="email" id="emailL" value="${dto.email}">
</div>
<div class="control-group controls ">
<input type="password" class="reg" id="passwordL" placeholder="<spring:message code="modal.section.h7"/>" name="password" value="${dto.password}" >
</div>
<div class="sign form-actions">
<input role="button" type="submit" class="btn btn-primary btn-block" value="<spring:message code="nav.section.link6"/>">
</div>
</form:form>
<%--<div class="fmp">--%>
<%--<a><spring:message code="modal.section.h4"/></a>--%>
<%--</div>--%>
</div>
</div>
</div>
</div>
<!-- modal registration
================================================== -->
<div class="modal" id="modal-2">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body">
<div class="btn-group btn-group-justified" role="group" aria-label="...">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal-1" data-dismiss="modal" ><spring:message code="nav.section.link6"/></button>
</div>
<div class="btn-group" role="group">
<button type="button" class="btn btn-default active"><spring:message code="nav.section.link9"/></button>
</div>
</div>
</div>
<div class="modal-footer">
<div align="center">
<ul class="sign-social-icon">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div class="or">
<p><spring:message code="modal.section.h3"/></p>
</div>
<form:form action="/saveUser" modelAttribute="dto" name="myForm" id="contact-form" class="form-horizontal">
<div class="control-group controls">
<input type="email" class="reg" placeholder="<spring:message code="modal.section.h6"/>" name="email" id="email" value="${dto.email}">
</div>
<div class="control-group controls ">
<input type="password" class="reg" id="password" placeholder="<spring:message code="modal.section.h7"/>" name="password" value="${dto.password}" >
</div>
<div class="control-group controls">
<input type="password" class="reg" id="conf" placeholder="<spring:message code="modal.section.h8"/>" name="conf">
</div>
<div class="sign form-actions">
<input role="button" type="submit" class="btn btn-primary btn-block" value="<spring:message code="nav.section.link9"/>">
</div>
</form:form>
<div class="policy">
<spring:message code="modal.section.h5"/> </div>
</div>
</div>
</div>
</div>
This is my login method in HomeController.class:
#RequestMapping(value = "/userLogin", method = RequestMethod.POST)
public String updateOne(#RequestParam(required = true) String email, #RequestParam(required = true) String password, HttpServletRequest request) throws SQLException {
HttpSession session = request.getSession();
User user = userService.getByEmail(email);
System.out.println("проверка пароля и имейла с БД");
if (user != null && user.getPassword().equals(password)) {
session.setAttribute("email", user.getEmail());
System.out.println("ЛОГИНИТСЯ!!!");
if (userService.getByEmail(email).getRole().equals(Role.USER)) {
System.out.println("SALUT USER!!");
session.setAttribute("user", user);
return "redirect:/";
} else if (userService.getByEmail(email).getRole().equals(Role.MODERATOR)) {
System.out.println("SALUT MODERATOR!!");
session.setAttribute("moderator", user);
return "redirect:/";
} else if (userService.getByEmail(email).getRole().equals(Role.ADMIN)) {
System.out.println("SALUT ADMIN!!");
session.setAttribute("admin", user);
return "redirect:/";
}
}
return "redirect:/loginProblems";
}
The users and admin then has to open their dashboards(using click on button <li>${email}</li> in HEADER).
This is my DashboardController.class:
#Controller
public class DashboardsConroller {
#Autowired
UserService userService;
#Autowired
UserDataService userDataService;
#RequestMapping(value = "/dashboards", method = RequestMethod.GET)
public String selectDashboard(HttpServletRequest request) {
System.out.println("method selectDashboard!!");
HttpSession session = request.getSession();
User user = userService.getByEmail((String) session.getAttribute("email"));
System.out.println("СМОТРИ СЮДА = " + user);
if (userService.getByEmail(user.getEmail()).getRole().equals(Role.USER)) {
System.out.println("USER want to open dashboard!!");
session.setAttribute("user", user);
return "redirect:/userDash";
} else if (userService.getByEmail(user.getEmail()).getRole().equals(Role.MODERATOR)) {
System.out.println("Moderator want to open dashboard!!");
session.setAttribute("moderator", user);
return "redirect:/moderatorDash";
} else if (userService.getByEmail(user.getEmail()).getRole().equals(Role.ADMIN)) {
System.out.println("ADMIN want to open dashboard!!");
session.setAttribute("admin", user);
return "redirect:/adminDash";
} else {
System.out.println("LAST ELSE IS WORKING");
return "redirect:/home";
}
}
}
This is my showAdminDashboard() method in AdminDashController.class:
#PreAuthorize("hasAuthority('ADMIN')")
#RequestMapping(value = "/adminDash", method = RequestMethod.GET)
public ModelAndView showAdminDashboard(#ModelAttribute("myUserData") UserData myUserData,
#RequestParam(required = false) String firstName,
#RequestParam(required = false) String secondName,
HttpServletRequest request) throws SQLException {
...
}
This is my showUserDashboard() method in UserDashController.class:
#PreAuthorize("hasAuthority('USER')")
#RequestMapping(value = "/userDash", method = RequestMethod.GET)
public ModelAndView showUserDashboard(#ModelAttribute("myUserData") UserData myUserData,
#RequestParam(required = false) String firstName,
#RequestParam(required = false) String secondName,
HttpServletRequest request) throws SQLException, InstantiationException, IllegalAccessException {
...
return modelAndView;
}
This is my SecurityConfig.class :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/**");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/userLogin", "/dashboards", "/saveUser").permitAll()
.antMatchers("/adminDash").hasAuthority("ADMIN")
.antMatchers("/userDash").hasAuthority("USER")
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/")
.usernameParameter("email")
.passwordParameter("password")
.failureUrl("/loginProblems")
.permitAll()
.and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/accountLogout"));
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

WHY Once admin or users after login, they can not get on their dashboards.
It happens because user wasn't authenticated properly, in fact for a Spring Security, user is still not authenticated.
When you're using Spring Security, it should authenticate users (by finding user in the database, comparing passwords, assigning roles and so on). But you're trying to authenticate users by your own code (in /userLogin).

Related

Laravel 7 Password Reset error: We can't find a user with that email address

Working on Laravel 7 Project. Required to reset password for multiuser (Admin,supervisor,student). Posting my code below. Password reset email link is working fine, but when i try to change my password it gives me error with email. I tried finding its root but couldn't find it. Request help..
Thanks in advance..
Posting necessory files below.. if require more, please tell me.
AdminForgetPasswordController
<?php
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Password;
class AdminForgotPasswordController extends Controller
{
public function __construct()
{
$this->middleware('guest:admin');
}
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset emails and
| includes a trait which assists in sending these notifications from
| your application to your users. Feel free to explore this trait.
|
*/
use SendsPasswordResetEmails;
protected function broker()
{
return Password::broker('admins');
}
public function showLinkRequestForm()
{
return view('auth.passwords.admin-email');
}
}
AdminResetPasswordController
<?php
namespace App\Http\Controllers\Admin\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Auth;
use Password;
use Illuminate\Http\Request;
class AdminResetPasswordController extends Controller
{
/*
|--------------------------------------------------------------------------
| Password Reset Controller
|--------------------------------------------------------------------------
|
| This controller is responsible for handling password reset requests
| and uses a simple trait to include this behavior. You're free to
| explore this trait and override any methods you wish to tweak.
|
*/
use ResetsPasswords;
/**
* Where to redirect users after resetting their password.
*
* #var string
*/
protected $redirectTo = '/admin/home';
public function __construct()
{
$this->middleware('guest:admin');
}
protected function broker()
{
return Password::broker('admin');
}
public function showResetForm(Request $request, $token = null)
{
return view('auth.passwords.admin-reset')->with(
['token' => $token, 'email' => $request->email]);
}
}
Admin Model
<?php
namespace App\Model\admin;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use App\Notifications\AdminResetPasswordNotification;
use Illuminate\Auth\Passwords\CanResetPassword;
class Admin extends Authenticatable
{
use Notifiable;
protected $guard = 'admin';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function sendPasswordResetNotification($token)
{
$this->notify(new AdminResetPasswordNotification($token));
}
}
AdminResetPasswordNotification
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class AdminResetPasswordNotification extends Notification
{
use Queueable;
public $token;
/**
* Create a new notification instance.
*
* #return void
*/
public function __construct($token)
{
$this->token=$token;
}
/**
* Get the notification's delivery channels.
*
* #param mixed $notifiable
* #return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account.')
->action('Reset Password', route('admin.password.reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
/**
* Get the array representation of the notification.
*
* #param mixed $notifiable
* #return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
Resources/views/Auth/password/admin-email.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Admin Reset Password') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<form method="POST" action="{{ route('admin.password.email') }}">
#csrf
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Send Password Reset Link') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
resources/views/auth/password/admin-reset.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Reset Password') }}</div>
<div class="card-body">
<form method="POST" action="{{ route('password.update') }}">
#csrf
<input type="hidden" name="token" value="{{ $token }}">
<div class="form-group row">
<label for="email" class="col-md-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="email" type="email" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ $email ?? old('email') }}" required autocomplete="email" autofocus>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">{{ __('Password') }}</label>
<div class="col-md-6">
<input id="password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" required autocomplete="new-password">
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="form-group row">
<label for="password-confirm" class="col-md-4 col-form-label text-md-right">{{ __('Confirm Password') }}</label>
<div class="col-md-6">
<input id="password-confirm" type="password" class="form-control" name="password_confirmation" required autocomplete="new-password">
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Reset Password') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection

JSF APPLY_REQUEST_VALUES lifecycle not call during POST request process

I create JSF form with Jquery Diaolg. When I submit my form , the request doesn't invoke my bean method on first click but calls it at second click. I implement a PhaseListener to debug and found out that during first click only RESTORE_VIEW and RENDER_RESPONSE were called. My Question is what can cause this.
<?xml version='1.0' encoding='UTF-8' ?>
<!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://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:forseti="http://xmlns.jcp.org/jsf/composite/components"
xmlns:jsf="http://xmlns.jcp.org/jsf"
xmlns:p="http://xmlns.jcp.org/jsf/passthrough"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<ui:composition >
<div jsf:id="modal-wizard-edit" class="modal">
<div id="user-profile-3" class="modal-dialog">
<div class="modal-content" style="width:800px;">
<div id="modal-content">
<form class="form-horizontal" jsf:id="personne-morale-edit-form" jsf:prependId="false">
<div class="modal-header no-padding">
<div class="table-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<span class="white">×</span>
</button>
Results for "Latest Registered Domains
</div>
</div>
<div class="tabbable" style="margin-top: 20px; margin-left: 20px;margin-right: 20px; margin-bottom: 20px;">
<ul class="nav nav-tabs padding-16">
<li class="active">
<a data-toggle="tab" href="#edit-basic">
<i class="green ace-icon fa fa-pencil-square-o bigger-125"></i>
Etat civil/Identité
</a>
</li>
</ul>
<div class="tab-content profile-edit-tab-content">
<div id="edit-basic" class="tab-pane in active">
<div class="row">
<div class="col-xs-6 col-lg-6 col-md-6 col-sm-6">
<div class="form-group">
<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="edit-raison-sociale">Raison sociale:</label>
<div class="col-xs-12 col-sm-9">
<input id="edit-raison-sociale" type="text" jsf:value="#{personneMoraleBean.selectedPersonneMorale.raisonSociale}"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="edit-ifu">IFU:</label>
<div class="col-xs-12 col-sm-9">
<input id="edit-ifu" type="text" jsf:value="#{personneMoraleBean.selectedPersonneMorale.ifu}"/>
</div>
</div>
</div>
<div class="col-xs-6 col-lg-6 col-md-6 col-sm-6">
<div class="form-group">
<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="nature_juridique_edit">Nature juridique:</label>
<div class="col-xs-12 col-sm-9">
<h:selectOneMenu class="chosen-select" id="nature_juridique_edit" value="#{personneMoraleBean.selectedPersonneMorale.natureJuridique}" p:data-placeholder="#{bundle.champNatureAffaireClassification}" required="true" >
<f:selectItem itemValue="" itemLabel="" />
<f:selectItems value="#{personneMoraleBean.listeNatureJuridiques}" var="item" itemValue="#{item}" itemLabel="#{item.libelle}" />
<f:converter converterId="natureJuridiqueConverter" />
</h:selectOneMenu>
</div>
<script src="../../resources/components/chosen.jquery.min.js"></script>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="secteur_edit">Secteurs d'activités:</label>
<div class="col-xs-12 col-sm-9">
<h:selectManyListbox class="multiselect" id="secteur_edit" value="#{personneMoraleBean.selectedPersonneMorale.secteurs}" p:data-placeholder="#{bundle.champNatureAffaireClassification}" p:multiple="" required="true" >
<f:selectItems value="#{personneMoraleBean.listeSecteurActivites}" var="item"
itemLabel="#{item.libelle}" itemValue="#{item}"/>
<f:converter converterId="secteurActiviteConverter"/>
</h:selectManyListbox>
</div>
</div>
<script src="../../resources/js/bootstrap-multiselect.min.js"></script>
<script type="text/javascript">
$('#secteur_edit').multiselect({
enableFiltering: true,
buttonClass: 'btn btn-white btn-primary',
templates: {
button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>',
ul: '<ul class="multiselect-container dropdown-menu"></ul>',
filter: '<li class="multiselect-item filter"><div class="input-group"><span class="input-group-addon"><i class="fa fa-search"></i></span><input class="form-control multiselect-search" type="text"/></div></li>',
filterClearBtn: '<span class="input-group-btn"><button class="btn btn-default btn-white btn-grey multiselect-clear-filter" type="button"><i class="fa fa-times-circle red2"></i></button></span>',
li: '<li><label></label></li>',
divider: '<li class="multiselect-item divider"></li>',
liGroup: '<li class="multiselect-item group"><label class="multiselect-group"></label></li>'
}
});
</script>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-3 no-padding-right" for="telephone_edit">Telephone:</label>
<div class="col-xs-12 col-sm-9">
<forseti:phoneNumber id="telephone_edit" value="#{personneMoraleBean.selectedPersonneMorale.telephone}"/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 20px; margin-left: 20px;margin-right: 20px; margin-bottom: 20px;">
<div class="clearfix col-sm-12 ">
<button type="submit" jsf:id="submit-morale-edit" class="btn btn-primary btn-block" jsf:action="#{personneMoraleBean.doEdit}">
Block Button
</button>
</div>
</div>
</form>
</div>
</div><!-- /.span -->
</div><!-- /.user-profile -->
</div><!-- PAGE CONTENT ENDS -->
<script type="text/javascript">
function ajaxMonitoringFinishEdit(data) {
if (data.status == "success") {
$('#modal-wizard-edit').modal('hide');
}
}
</script>
</ui:composition>
</html>
This is my form code source
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package forseti.controller.personne;
import forseti.ejb.NatureJuridiqueFacade;
import forseti.ejb.PersonneMoraleFacade;
import forseti.ejb.SecteurActiviteFacade;
import forseti.jpa.personne.NatureJuridique;
import forseti.jpa.personne.PersonneMorale;
import forseti.jpa.personne.SecteurActivite;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
/**
*
* #author Gildasdarex
*/
#Named(value = "personneMoraleBean")
#ViewScoped
public class PersonneMoraleBean implements Serializable {
/**
* Creates a new instance of PersonneMoraleBean
*/
#Inject
private PersonneMoraleFacade personneMoraleFacade;
#Inject
private SecteurActiviteFacade secteurActiviteFacade;
#Inject
private NatureJuridiqueFacade natureJuridiqueFacade;
private PersonneMorale newPersonneMorale;
private PersonneMorale selectedPersonneMorale;
private List<PersonneMorale> listePersonneMorales;
private SecteurActivite selectedSecteurActivite;
public PersonneMoraleBean() {
}
#PostConstruct
public void init() {
newPersonneMorale = new PersonneMorale();
selectedPersonneMorale = new PersonneMorale();
}
public PersonneMorale getNewPersonneMorale() {
return newPersonneMorale;
}
public void setNewPersonneMorale(PersonneMorale newPersonneMorale) {
this.newPersonneMorale = newPersonneMorale;
}
public PersonneMorale getSelectedPersonneMorale() {
return selectedPersonneMorale;
}
public void setSelectedPersonneMorale(PersonneMorale selectedPersonneMorale) {
this.selectedPersonneMorale = selectedPersonneMorale;
}
public List<PersonneMorale> getListePersonneMorales() {
listePersonneMorales = personneMoraleFacade.findAll();
return listePersonneMorales;
}
public List<SecteurActivite> getListeSecteurActivites() {
return secteurActiviteFacade.findAll();
}
public List<NatureJuridique> getListeNatureJuridiques() {
return natureJuridiqueFacade.findAll();
}
public SecteurActivite getSelectedSecteurActivite() {
return selectedSecteurActivite;
}
public void setSelectedSecteurActivite(SecteurActivite selectedSecteurActivite) {
this.selectedSecteurActivite = selectedSecteurActivite;
}
public void doCreate() {
newPersonneMorale.setId(newPersonneMorale.getIfu());
personneMoraleFacade.create(newPersonneMorale);
listePersonneMorales = personneMoraleFacade.findAll();
}
public void doDel() {
personneMoraleFacade.remove(selectedPersonneMorale);
}
public void doEdit() {
System.out.println("edit "+selectedPersonneMorale.getId());
System.out.println("edit "+selectedPersonneMorale.getIfu());
System.out.println(selectedPersonneMorale.getRaisonSociale());
System.out.println(selectedPersonneMorale.getNatureJuridique());
System.out.println(selectedPersonneMorale.getSecteurs().size());
personneMoraleFacade.edit(selectedPersonneMorale);
}
public void doRemoveSecteur() {
selectedPersonneMorale.getSecteurs().remove(selectedSecteurActivite);
personneMoraleFacade.edit(selectedPersonneMorale);
listePersonneMorales = personneMoraleFacade.findAll();
}
public void passItemMoraleSecteur(PersonneMorale personneMorale, SecteurActivite secteurActivite) {
selectedPersonneMorale = personneMorale;
selectedSecteurActivite = secteurActivite;
}
public void passItem(PersonneMorale item) {
selectedPersonneMorale = item;
System.out.println("getItem "+selectedPersonneMorale.getId());
}
}

Calling a managed bean method from JSF

I have been through many questions here but doesn't solve my problem. I have an HTML form and I want to call a method of a managed bean class, when the submit button is clicked. Here are the code.
HTML Form:
<form class="form-horizontal" action= "" method="post">
<div class="control-group">
<label class="control-label" for="inputEmail">Username</label>
<div class="controls">
<input type="text" id="inputUsrname" name="usrname" placeholder="Username" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<input type="text" id="inputUsrname" name="email" placeholder="Email"/>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
<h:commandButton value="click" action="#{hello_World.getMessage()}"/>
<button class="btn" type="reset">Reset</button>
</form>
Managed Bean class:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
#ManagedBean(name="hello_World", eager=true)
public class HelloWorld {
public HelloWorld() {
System.out.println("Helloworld started from managed bean");
}
public String getMessage() {
System.out.println("sjdfksadfbasdjkfh");
return "indexx.xhtml";
}
}
When I click the click button, nothing happens.
Thank you.

Required Attribute not firing

The following is my class. I am trying to make a small login form. I have a class LoginApp which has username and password. Both I have made required.
[Required(ErrorMessage="This Is a required field")]
[Display(Name="User Name")]
public string userName { get; set; }
[Required]
[Display(Name = "PassWord")]
public string passWord { get; set; }
Following is my controller where i have used tryUpdateModel for checking.
public ActionResult Login(Models.LoginApp LA)
{
LoginApp LAPP = new LoginApp();
bool g = TryUpdateModel(LAPP);
if (ModelState.IsValid)
{
if (LA.userName == "admin" && LA.passWord == "admin")
return RedirectToAction("LoginSuccessful", new { userName = LA.userName});
else
return RedirectToAction("Index");
}
else
return RedirectToAction("Index");
}
Here is the view.
<div class="container">
#using (Html.BeginForm("Login", "Login"))
{
#Html.ValidationSummary(true)
<div class="row">
<div class="form-group ">
#Html.Label("User Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(Model => Model.userName, "", new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.userName)
</div>
</div>
<br />
<br />
<div class="form-group ">
#Html.Label("PassWord", new { #class = "col-md-2 control-label" })
<div class="col-md-10 ">
#Html.PasswordFor(u => u.passWord, new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.passWord)
</div>
</div>
<br />
<br />
<div class="form-group ">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
<input type="button" id="btn" value="Reset" onclick="" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
When I click the log in button without supplying the username or password it doesn't give me validation messages. Where I am going wrong.
You didn't include the validate.js and unobtrusiveon the page.
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
You should check if the ModelState.IsValid in the controller in order to ake the validation in back-end too (so in both side)

AllowHtml attribute not working on production

I have a model that required that html be captured. I have added the [AllowHtml] attribute to the model property and it works correctly on my local server when debugging.
Once deployed to production however, it works correctly when executed on the production server (i.e. I remote onto the server and browse it there), but fails with the the usual "potentially dangerous blah blah blah " message when executed from any other machine.
So it seems to me that there is something to do with the location involved in the validation, or am I completely missing the boat.
Just to confirm, I have made no "special" changes to the web.config.
Please can someone explain why I am having this issue.
Model
[AllowHtml]
[Display(Name = "Overview")]
public string Overview { get; set; }
Controller
//
// POST: /Product/
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditFeature(BackOffice.Models.ProductFeature model)
{
if (ModelState.IsValid)
{
//insert the new product
}
//invalid model, return with errors
return View(model);
}
View
#model BackOffice.Models.ProductFeature
#using (Html.BeginForm("AddFeature", "Product", null, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.Hidden("ProductID", #Model.ProductID)
<div class="modal fade" id="FeatureModal" tabindex="-1" role="dialog" aria-labelledby="FeatureModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Add a Feature</h4>
</div>
<div class="modal-body">
<div class='form-group'>
<label class='col-lg-2 control-label'>Title</label>
<div class="col-lg-10">
#Html.TextBoxFor(m => m.Title, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Title)
</div>
</div>
<div class='form-group'>
<label class='col-lg-2 control-label'>Overview</label>
<div class="col-lg-10">
#Html.TextAreaFor(m => m.Description, 10, 40, new { #class = "ckeditor", id = "overview" })
</div>
</div>
</div>
<div class='clearfix'></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
}
There is a mis-match in the method names here. You have
#using (Html.BeginForm("AddFeature", "Product", null, FormMethod.Post, new { role = "form", #class = "form-horizontal" }))
{
}
But Your action method is called
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditFeature(BackOffice.Models.ProductFeature model)
{
}
Where is the AddFeature action method?

Resources