I am trying to implement 'forgot password' functionality using JSF SEAM in our index page, I am using a a4j:jsFunction to send the users email and card number via two 's
It seems to work fine when I just send the email (as a string), but when I added card number (int) it threw the following..
Caused by: javax.el.PropertyNotFoundException: /index.xhtml #256,138 assignTo="#{forgotPasswordActions.cardnumber}": The class 'org.javassist.tmp.java.lang.Object_$$_javassist_seam_5' does not have the property 'cardnumber'.
The backing bean looks like this...
#Stateless
#Name("forgotPasswordActions")
public class ForgotPasswordActionsBean implements ForgotPasswordActions, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Logger private Log log;
#In private EmailService emailService;
#In private UserDAO userDAO;
#In private MessagePoster messagePoster;
#In private Map<String, String> messages;
private User user;
private String address;
private String email;
private int cardnumber;
#Override
public void resetPassword(){
new RunAsOperation(true) {
public void execute() {
if(StringUtils.isNotEmpty(email)){
user = userDAO.findByEmail(email);
}
else{
messagePoster.postPopupInfoMessage(messages.get("inputEmpty"));
}
if(user!=null && cardnumber == user.getCardId()){
String newPassword = generateRandomPassword();
log.debug("updating password...");
user.setPassword(newPassword);
user = userDAO.makePersistent(user);
address = user.getEmail();
log.debug("password changed to: "+newPassword);
Map<String, Object> emailInfo = new HashMap<String, Object>();
emailInfo.put("name", user.getFirstname());
emailInfo.put("newPassword", newPassword);
emailService.sendToAddress(Email.user_password_reset, address, emailInfo);
messagePoster.postPopupInfoMessage(messages.get("pwReset")+" "+user.getEmail());
}
else{
messagePoster.postPopupInfoMessage(messages.get("resetFailed"));
}
}
}.run();
}
//---------------------- Setters
#Override
public void setEmail(String email) {
this.email = email;
}
#Override
public void setCardno(int cardnumber) {
this.cardnumber = cardnumber;
}
}
and the JSF / HTML
<div id="forgotPasswordDialog" title="Forgot Password">
<div class="textBox">
<input id="emailLookupval" type="text" />
<input id="cardNoval" type="text" />
<button onclick="resetPassword(jQuery('#emailLookupval').val(),jQuery('#cardNoval').val())" type="button">Reset</button>
<a4j:form id="forgotPassword">
<a4j:jsFunction name="resetPassword"
action="#{forgotPasswordActions.resetPassword}"
oncomplete="jQuery('#forgotPasswordDialog').dialog('open')">
<a4j:actionparam name="userEmail" assignTo="#{forgotPasswordActions.email}" />
<a4j:actionparam name="userCardno" assignTo="#{forgotPasswordActions.cardnumber}" />
</a4j:jsFunction>
</a4j:form>
</div>
</div>
I cant work out why it wont set this bean property?? Any help appreciated!
Your setter is called setCardno() while setCardnumber() is been expected by the view. The #{bean.property} does not relate to property names in the bean. It relates to getter/setter method names. There are 2 ways to fix this:
Rename the setter method:
public void setCardnumber(int cardnumber) {
this.cardnumber = cardnumber;
}
Or, rename the view property:
assignTo="#{forgotPasswordActions.cardno}"
Related
I have a registration form page index.html for users for a car rental app I'm building
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<form action="#" th:action="#{/register}" th:object="${user}"
method="post">
<p>User Name <input type="text" name="name"></p>
<p>Password <input type="password" name="password"></p>
<button type="submit">Register</button>
</form>
</body>
</html>
And a corresponding controller class where I want to invoke a new user using the factory class then save it to MySQL DB
Controller Class:
#Controller
public class IndexController {
#Autowired
private UserService userService;
private CustomerFactory userFactory;
private UserController controller;
#GetMapping("/")
public String registerForm(Model model){
return "index";
}
#GetMapping("/car-list")
public String carList(){
return "index";
}
#PostMapping("/register")
public String registerUser(#ModelAttribute User user){
User u = userFactory.createUser(user.getName(), user.getPassword());
//userService.saveUser(user);
return "car-list";
}
}
Here is the User class:
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userID", nullable = false)
private int userID;
private String name;
private String password;
public User() {
}
public User(String name, String password) {
this.name = name;
this.password = password;
}
//getters setters and toString omitted
}
Here is my factory class:
public class CustomerFactory implements com.project.CS4125.service.UserFactory {
#Override
public User createUser(String name, String password) {
return new User(name, password);
}
}
My problem is I need to create the new User through the factory class then save it but get this error
: Cannot invoke "com.project.CS4125.service.CustomerFactory.createUser(String, String)" because "this.userFactory" is null
Any help appreciated.
Take a look at this section of your code. How many autowired fields does it show?
#Autowired
private UserService userService;
private CustomerFactory userFactory;
private UserController controller;
The answer is one, the UserService.
Annotations such as #Autowired apply only to the element that immediately follows them. This section of code shows one field with an #Autowired annotation and two fields without this annotation. These other two fields are thus left at their default value of null, hence the NullPointerException attempting to call a method of the CustomerFactory.
If you want values for all three of these fields to be autowired, ensure all three fields have an #Autowired annotation:
#Autowired
private UserService userService;
#Autowired
private CustomerFactory userFactory;
#Autowired
private UserController controller;
I'm learning spring boot from a project https://github.com/rstyro/admin
In page/role/list.html,there is code:
<button th:if="${QX.add == '1' && QX.query == '1'}" class="btn btn-success
btn-sm" id="addRole"><i class="fa fa-plus"></i> add role</button>
I want to check what is this QX entity, So I go to RoleController.java
#RequestMapping(value="/list",method=RequestMethod.GET)
public Object list(Model model){
model.addAttribute("roles", roleService.list());
return "page/role/list";
}
then RoleService.java
#Service
public class RoleService implements IRoleService{
#Autowired
private RoleDao roleDao;
#Autowired
private MenuService menuService;
private Logger log = Logger.getLogger(this.getClass());
#Override
public List<ParameterMap> list() {
return roleDao.list();
}
then RoleDao.java
public interface RoleDao {
public List<ParameterMap> list();
public List<ParameterMap> getRoleByuId(ParameterMap pm);
public ParameterMap getRoleById(ParameterMap pm);
public void updateRoleQX(ParameterMap pm);
public void addRole(ParameterMap pm);
public void delRole(String roleId);
public void delUserRole(String roleId);
}
and RoleMapper.xml
<mapper namespace="com.lrs.admin.dao.RoleDao" >
<select id="list" resultType="pm">
SELECT
role_id,
role_name,
role_desc,
rights,
add_qx,
del_qx,
edit_qx,
query_qx
from
sys_role
</select>
and Role.java
public class Role {
private long roleId;
private String roleName;
private String roleDesc;
private String rights;
private String addQX;
private String delQX;
private String editQX;
private String queryQX;
public long getRoleId() {
return roleId;
}
But nothing is there. Am I missing something? Thx.
He is calling
return roleDao.list();
But there is no implementation of that statement, RoleDao interface is not implemented anywhere. Which means there is no bean called roleDao, which means, you cannot run this code. It will give you error.
The author probably did not share RoleDao implementation.
I am trying to learn how to build an application using Spring MVC and Hibernate. Currently I am stuck on inserting checkbox values into MySQL database.
My Database Table Structure is like following:
id name interest
When I fill up my form and hit submit I get this error message :
root cause
java.sql.SQLException: Incorrect string value: '\xAC\xED\x00\x05ur...' for column 'interest' at row 1
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1084)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4232)
I am trying to insert values in my table so that after insertion it looks like following:
id name interest
1 Steve PHP
2 Steve Java
3 Wuagh C#
4 Wuagh PHP
Could you please tell me how to achieve this? And If possible could you also tell me how can I achieve this as well ?
id name interest
1 Steve PHP, Java
2 Wuagh C#, PHP
Please see my codes below
My Form:
<c:url var="action" value="/register" ></c:url>
<form:form action="${action}" modelAttribute="subscriber" method="POST" >
<div>
<label>Name</label>
<form:input path="name"/>
<form:errors path="name" cssClass="error"/>
</div>
<div>
<label>Interests</label>
<form:checkboxes path="interest" items="${records.interests}"/>
</div>
<input type="submit" value="Submit">
</form:form>
Controller:
package com.spring.org;
#Controller
public class HomeController {
#Autowired
private SubscriberService subService;
#RequestMapping(value="/register", method= RequestMethod.GET)
public ModelAndView RegistrationForm(#ModelAttribute Subscriber subscriber, BindingResult result)
{
HashMap<Integer, String> interest = new HashMap<Integer, String>();
interest.put(1,"Java");
interest.put(2,"PHP");
interest.put(3, "C#");
return new ModelAndView("regForm", "records", interest);
}
#RequestMapping(value="/register", method= RequestMethod.POST)
public ModelAndView RegistrationFormSubmit(#ModelAttribute("subscriber") #Valid Subscriber subscriber, BindingResult result)
{
if (result.hasErrors()) {
return new ModelAndView("regForm");
}
else
{
subService.addSubscriber(subscriber);
return new ModelAndView("redirect:/showList");
}
}
}
Model - Subscriber
#Entity
#Table(name = "PERSON", schema = "java2")
public class Subscriber {
#Id
#Column(name="ID")
#GeneratedValue
private int id;
#NotEmpty(message = "Please enter your Name.")
private String name;
private String[] interest;
public String getName() {return name;}
public void setName(String name) { this.name = name; }
public String[] getInterest() { return interest; }
public void setInterest(String[] interest) { this.interest = interest; }
}
SubscribeService Implementation :
#Service
public class SubscriberServiceImpl implements SubscriberService{
#Autowired
private SubscriberDao subsDao ;
#Override
public void addSubscriber(Subscriber subscriber) {
subsDao.addSubscriber(subscriber);
}
}
SubscriberDao Implementation :
#Repository
public class SubscriberDaoImpl implements SubscriberDao {
#Autowired
private SessionFactory sessionFactory ;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
#Override
public void addSubscriber(Subscriber subscriber) {
getSessionFactory().openSession().save(subscriber);
}
}
I have an action class that implements ModelDriven interface. This ModelDriven is a regular POJO, the problem is that one of its properties is another object.
Imagine that my ModelDrivenis a object calledPersonand my person has an attribute calledAddressthat is another object.Addresshas regular properties such asString, Long` and etc.
In the JSP when I submit the form, all the regular properties used such as String, int, long in Person are mapped correctly, but all the data that should be mapped to address are not.
<s:textfield name="name" id="name" size="25" maxlength="15" />
<s:textfield name="address.zipcode" id="zipcode" size="25" maxlength="15" />
That's how I try mapping the properties. The name property I can get it right, but when it comes to map the properties in the person's address this approach does not work.
What am I doing wrong?
In time, my Address property is declared in Person instantiating the object, so it's never null.
EDIT: As requested, here the action source and the DTOs:
The Action:
#Controller
#Scope("request")
public class AnAction extends BaseAction implements ModelDriven<FakeDTO> {
private static final long serialVersionUID = 8238033889271514835L;
#Autowired
private FakeFacade facade;
private FakeDTO fakeDTO = new FakeDTO();
public String action01() {
return Action.SUCCESS;
}
public String action02() {
this.fakeDTO.setAnswer(this.fakeFacade.fakeFacadeMethod(this.fakeDTO.getComplexObject()));
return Action.SUCCESS;
}
#Override
public FakeDTO getModel() {
return this.fakeDTO;
}
}
The main class FakeDTO:
public class FakeDTO implements BaseDTO {
private static final long serialVersionUID = -2093038083351846003L;
private FakeFilterDTO filter = new FakeFilterDTO();
private String name;
public FakeDTO() {
super();
}
#Override
public FakeFilterDTO getFilter() {
return this.filter;
}
public void setFilter(final FakeFilterDTO filterParam) {
this.filter = filterParam;
}
public String getName() {
return this.name;
}
public String setName(final String nameParam) {
this.name = nameParam;
}
}
The class FakeFilterDTO:
public class FakeFilterDTO extends BaseFilterDTO {
private static final long serialVersionUID = 4528040257605851210L;
private Date aDate;
private Long aLong;
private Integer anInteger;
private String aString;
public Date getADate() {
return this.aDate;
}
public void setDataInicial(final Date aDateParam) {
this.aDate = aDateParam;
}
public Long getALong() {
return this.aLong;
}
public void setALong(final Long aLongParam) {
this.aLong = aLongParam;
}
public Integer getAnInteger() {
return this.anInteger;
}
public void setAnInteger(final Integer anIntegerParam) {
this.anInteger = anIntegerParam;
}
public String getAString() {
return this.aString;
}
public void setAString(final String aStringParam) {
this.aString = aStringParam;
}
}
The struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<include file="META-INF/bsad/struts2/struts-config.xml" />
<package name="reports" namespace="/reports" extends="project-default">
<action name="anAction" class="anAction" method="action01">
<result>/WEB-INF/pages/success.jsp</result>
<result name="input">/WEB-INF/pages/input.jsp</result>
</action>
<action name="generateReport" class="anAction" method="action02">
<result>/WEB-INF/pages/reportGenerated.jsp</result>
</action>
</package>
</struts>
The project-default is placed in the include struts-config.xml and extends struts-default package that contains the ModelDrivenInterceptor. I can assure that because I placed a break point in this interceptor and its passing through there.
The JSP that I used as an example before would become as follows:
<s:textfield name="name" id="name" size="25" maxlength="15" />
<s:textfield name="filter.aString" id="zipcode" size="25" maxlength="15" />
For company policies I'm not allowed to copy/paste the actual objects and its names. But that's the idea.
In the fakeDTO that is your model you should have a property address which should return an object like AddressDTO in this object there should be a property zipcode.
public class FakeDTO implements BaseDTO {
private AddressDTO address;
public AddressDTO getAddress() {
return address;
}
public void setAddress (AddressDTO address) {
this.address = address;
}
...
}
public class AddressDTO implements BaseDTO {
private String zipcode;
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
...
}
as you haven't posted struts.xml your action configuration should include modelDriven interceptor which include in the defaultStack by default is used when you extend struts-default package. See example of using ModelDriven. The model is pushed to the top of the valueStack by the interceptor, so the object like address should be available if it has a default constructor it will be created by the OGNL and zipcode set there. When you display the fields in the JSP the address.zipcode is evaluated as an OGNL expression and retrieve zipcode from the address bean if the model is initialized that bean and zipcode itself. All beans referenced in OGNL expression should be initialized and have getter/setter properties.
To make the question clear I make an example:
consider theSubscriber form defined bellow in first.jsp:
<s:form id="theSubscriber" name="theSubscriber" method="post" action="next.action">
<s:bean name="my.hibernate.actors.Subscriber" var="user">
<s:hidden name="id" key="id" value="%{user.id}" />
<s:textfield id="subscriberForename" name="forename"
key="forename" value="%{user.forename}" label="Forename" />
<s:textfield id="subscriberSurname" name="surname"
key="surname" value="%{user.surname}" label="Surname" />
</s:bean>
</s:form>
consider the following action class for the next.action
public class NextAction extends ActionSupport {
private Subscriber user = new Subscriber();
private String forename;
public String getForename() {
return forename;
}
public void setForename(String forename) {
this.forename = forename;
}
public ManageSubscriber() {
// TODO Auto-generated constructor stub
}
public ManageSubscriber(Subscriber user) {
this.user = user;
}
public Subscriber getUser() {
return user;
}
public void setUser(Subscriber user) {
this.user = user;
}
public String execute() {
System.out.println(getUser());//This prints out null
System.out.println(getForename());//This prints out the posted forename
return SUCCESS;
}
}
The question is: I know that defining all the form fields as action class properties let the class fill them correctly. But I want to make it fill the relevant fields in another class which contains all necessary properties. The user/subscriber class is like this:
public class User {
private long id;
private String username;
private String password;
private UserLevel userLevel;
private String forename;
private String surname;
private String email;
private String phoneNumber;
private String address;
private Date birthday;
private Date registrationDate;
}
I have defined all accessor methods.
In fact the problem is that it looks very annoying and redundant to define all these fields for the nextAction class and then evaluate the instance of user in that class.
How should I solve this problem?
It is easier than you think.
You are very close, and you've already done it for value attribute (used to pre-set the value for the item on the page):
now just do it for name attribute (used to send the value to the Action), like this:
<s:hidden name="user.id" key="id" value="%{user.id}" />
<s:textfield id="subscriberForename" name="user.forename"
value="%{user.forename}" label="Forename" />
<s:textfield id="subscriberSurname" name="user.surname"
value="%{user.surname}" label="Surname" />
(Key attribute was not necessary here)
Note that for this to work, you will need a bean with a no-args constructor (as you have).
Avoid initializating it yourself too.
Change this:
private Subscriber user = new Subscriber();
to this
private Subscriber user;
I think you are asking how you can persist in memory a User object that will be used across multiple actions.
You have a couple of options if I understand your question correctly.
One option, which is not very Struts like, would be to add the User object to a session variable. You can access the session variable as described here.
Another option, which I would recommend if you plan on maintaining the object in your session for a specific set of actions (or steps, such as a 'wizard' portion of your app) is the ScopeInterceptor. You can read about that here and here.
Hope that helps.