NullPointerException при использовании перехватчика в Struts2
Моя проблема заключается в том, что, когда я пытаюсь войти в свое веб-приложение, используя Struts2, и в спящем режиме выдается исключение нулевого указателя. Мой сервер tomcat выдает следующее:
INFOS: Server startup in 10968 ms
inside execute
inside find
java.lang.NullPointerException
Nameeee admin passwordddd admin
session getuser null
at com.inwi.dao.UserDAOImpl.find(UserDAOImpl.java:43)
at com.inwi.action.LoginAction.execute(LoginAction.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
LoginAction:
public class LoginAction extends ActionSupport implements SessionAware, ModelDriven<User>{
private static final long serialVersionUID = -3369875299120377549L;
private User user = new User();
private SessionMap<String, Object> sessionAttributes = null;
private List<User> userList = new ArrayList<User>();
private UserDAO userDAO = new UserDAOImpl();
@Override
public String execute(){
System.out.println("inside execute");
if(userDAO.find(user.getName(),user.getPassword())){
//if(user.getName().equals(user.getName()) && user.getName().equals(user.getPassword())){
System.out.println("ggggggggggggg");
sessionAttributes.put("USER", user);
return SUCCESS;
}
return INPUT;
}
@Override
public void setSession(Map<String, Object> sessionAttributes) {
this.sessionAttributes = (SessionMap<String, Object>)sessionAttributes;
}
@Override
public User getModel() {
return user;
}
Класс UserDaoImpl:
public class UserDAOImpl implements SessionAware,UserDAO {
@SessionTarget
Session session;
@TransactionTarget
Transaction transaction;
private Map<String, Object> sessionAttributes = null;
@Override
public void setSession(Map<String, Object> sessionAttributes) {
this.session = (Session) sessionAttributes;
}
@SuppressWarnings("unchecked")
public boolean find(String name, String password) {
System.out.println("inside find");
System.out.println("Nameeee "+name +" passwordddd "+password);
boolean result = false;
List<User> user = null;
try {
System.out.println("session getuser "+session);
String hql = "from User u where u.name = : name and u.password = : password";
user = session.createQuery(hql).list();
while (!user.isEmpty()) {
result = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Класс AuthenticationInterceptor:
public class AuthenticationInterceptor implements Interceptor {
private static final long serialVersionUID = -5011962009065225959L;
@Override
public void destroy() {
//release resources here
}
@Override
public void init() {
// create resources here
}
@Override
public String intercept(ActionInvocation actionInvocation)
throws Exception {
System.out.println("inside auth interceptor");
Map<String, Object> sessionAttributes = actionInvocation.getInvocationContext().getSession();
User user = (User) sessionAttributes.get("USER");
if(user == null){
return Action.LOGIN;
}else{
Action action = (Action) actionInvocation.getAction();
if(action instanceof UserAware){
((UserAware) action).setUser(user);
}
return actionInvocation.invoke();
}
}
}
Приветственное мероприятие
public class WelcomeAction extends ActionSupport implements UserAware, ModelDriven<User> {
private static final long serialVersionUID = 8111120314704779336L;
@Override
public String execute(){
return SUCCESS;
}
private User user;
@Override
public void setUser(User user) {
this.user=user;
}
public User getUser(User user){
return this.user;
}
@Override
public User getModel() {
return this.user;
}
}
Struts.xml
<struts>
<constant name="struts.mapper.action.prefix.enabled" value="true" />
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<!-- <constant name="struts.ui.theme" value="simple" /> -->
<package name="default" extends="hibernate-default">
<interceptors>
<interceptor name="authentication"
class="com.inwi.interceptors.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="authStack">
<interceptor-ref name="authentication"></interceptor-ref>
<interceptor-ref name="defaultStackHibernate"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="authStack"></default-interceptor-ref>
<global-results>
<result name="loginAction" type="redirect">/home.action</result>
</global-results>
<action name="home">
<interceptor-ref name="defaultStackHibernate"></interceptor-ref>
<result>/login.jsp</result>
</action>
<action name="loginAction" class="com.action.LoginAction">
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/dashboard.jsp</result>
<result name="input">/loginError.jsp</result>
</action>
<action name="welcome" class="com.action.WelcomeAction">
<result name="success">/dashboard.jsp</result>
<!-- <result name="success">/siteMain.jsp</result> -->
</action>
<action name="logOut" method="logout" class="com.action.LoginAction">
<result name="success" type="redirect">/</result>
</action>
Логин jsp:
<form action="loginAction" method="post" id="login_form">
<s:textfield id="username" name="name" placeholder="Username" required="required"/>
<s:password id="password" name="password" placeholder="Password" required="required" />
<button type="submit">Se connecter</button>
</form>
Edite 1:
java.lang.NullPointerExceptioninside execute
inside find
Nameeee admin passwordddd admin
session getuser null
at com.inwi.dao.UserDAOImpl.find(UserDAOImpl.java:43)
at com.inwi.action.LoginAction.execute(LoginAction.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:870)
3 ответа
Ваша СЕССИЯ может быть нулевой и другие вещи, которые вы не присвоили значения для параметров. Проверьте обе вещи
user = session.createQuery(hql).list();
List result = session.createQuery(hql).setParameter("name","ARUN")..setParameter("password", "124").list();
Я решил это, отредактировав код фоллинга в sruts.xml
<action name="loginAction" method="executee" class="com.inwi.action.LoginAction">
<interceptor-ref name="defaultStackHibernate"></interceptor-ref>
<result name="success">/dashboard.jsp</result>
<result name="input">/loginError.jsp</result>
</action>*
И в LoginAction я меняю название метода execute
в executee
,
Судя по ответам, которые вы дали, проблема в этой строке:
Query q = session.createQuery(hql);
Так как сессия пуста, вы получаете исключение NullPointerException.
Глядя на ваш сеттер для сессии:
@Override
public void setSession(Map<String, Object> sessionAttributes) {
this.session = (Session) sessionAttributes;
}
Я не уверен, как вы ожидаете привести карту к объекту Session.