Error setting expression 'userBean.password' with value ['', ] - java

I'm using struts 2 and tomcat together.
The problem I'm facing is: whenever I submit data whether is wrong or not (username and password) it ALLWAYS makes following field error appear:
.Error setting expression 'userBean.password' with value ['XXX', ]
.Error setting expression 'userBean.username' with value ['YYY', ]
where 'XXX' is the password and 'YYY' is the username.
My action class is:
package direstruts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import direstruts.model.UserBean;
public class LoginAction extends GenericAction {
#Override
public void validate() {
UserBean uB = getUserBean();
if(uB.getUsername().isEmpty()) {
addFieldError("userBean.username", "Por favor Insira o Username de Utilizador");
}
if(uB.getPassword().isEmpty()) {
addFieldError("userBean.password", "Por favor Insira a Password de Utilizador");
}
}
public String getAuthentication() throws Exception {
if(getUserBean().getAuthentication()) {
addActionMessage("Log in bem Sucedido!");
return SUCCESS;
}
addActionError("Utilizador e/ou Password errados e/ou Utilizador já está logado");
return ERROR;
}
public String setNewUser() throws Exception {
if(getUserBean().setNewUser()) {
addActionMessage("User registado!");
return SUCCESS;
}
addActionError("Utilizador Já Existe! Tente Outro Username!");
return ERROR;
}
public String setQuitUser() throws Exception {
if(getUserBean().setQuitUser()) {
addActionMessage("User LoggedOut!");
return SUCCESS;
}
return ERROR;
}
public UserBean getUserBean() {
if(!session.containsKey("userBean"))
this.setUserBean(new UserBean());
return (UserBean) session.get("userBean");
}
public void setUserBean(UserBean userBean) {
session.put("userBean", userBean);
}
}
My jsp is:
<%# taglib prefix="s" uri="/struts-tags"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>MeeTO</title>
</head>
<body>
<s:form action="loginAction" method="post" >
<s:label cssClass="login" value="Please fill in the form below in order to Register or Log in:" /> <br>
<s:label for="userBean.username" value="Username:"/>
<s:textfield name="userBean.username" /> <br>
<s:label for="userBean.password" value="Password:"/>
<s:password name="userBean.password" /> <br>
<s:submit value="LogIn" action="loginAction" /> <br>
<s:submit value="Register" action="registerAction" /> <br>
</s:form>
<s:fielderror/>
<s:actionerror/>
<s:actionmessage/>
</body>
</
My bean is:
package direstruts.model;
import cliente.replies.ReplyLogin;
import cliente.replies.ReplyObj;
import cliente.requests.lookup.GetAuthentication;
import cliente.requests.modify.SetNewUser;
import cliente.requests.modify.SetQuitUser;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Properties;
import servidorRMI.ExecuteCommands;
public class UserBean {
ExecuteCommands eC;
private static String ip_RMI = "127.0.0.1";
private static int serverRMI = 1099;
private static InputStream in;
private String username;
private String password;
private int idUser;
public UserBean() {
readProperties();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getIdUser() {
return this.idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public boolean getAuthentication() {
GetAuthentication gA = new GetAuthentication(getUsername(), getPassword(), 0);
ReplyLogin rL = null;
boolean cond = false;
do{
try {
eC = (ExecuteCommands)Naming.lookup("rmi://" + ip_RMI + ":" + serverRMI + "/ServerRMI");
rL = eC.getAuthentication(gA);
cond = false;
} catch (RemoteException ex) {
System.err.println("Erro no servidor RMI Remote! A tentar restablecer a ligação!");
cond = true;
} catch (NotBoundException ex) {
System.err.println("Erro no servidor RMI NotBound! A tentar restablecer a ligação!");
cond = true;
} catch (MalformedURLException ex) {
System.err.println("Erro no servidor RMI MalformedURL! A tentar restablecer a ligação!");
cond = true;
}
} while(cond);
setIdUser(rL.getIdUser()); // Faz set ao idUser para poder ser usado nos pedidos subsequentes
return rL.isHasRegister();
}
public boolean setNewUser() {
SetNewUser sNU = new SetNewUser(getUsername(), getPassword(), 0);
boolean cond = false;
ReplyObj rO = null;
do{
try {
eC = (ExecuteCommands)Naming.lookup("rmi://" + ip_RMI + ":" + serverRMI + "/ServerRMI");
rO = eC.setNewUser(sNU);
cond = false;
} catch (RemoteException ex) {
System.err.println("Erro no servidor RMI Remote! A tentar restablecer a ligação!");
cond = true;
} catch (NotBoundException ex) {
System.err.println("Erro no servidor RMI NotBound! A tentar restablecer a ligação!");
cond = true;
} catch (MalformedURLException ex) {
System.err.println("Erro no servidor RMI MalformedURL! A tentar restablecer a ligação!");
cond = true;
}
} while(cond);
return rO.getSuccess();
}
public boolean setQuitUser() {
SetQuitUser sQU = new SetQuitUser(idUser, 0);
boolean cond = false;
ReplyObj rO = null;
do{
try {
eC = (ExecuteCommands)Naming.lookup("rmi://" + ip_RMI + ":" + serverRMI + "/ServerRMI");
rO = eC.setQuitUser(sQU);
cond = false;
} catch (RemoteException ex) {
System.err.println("Erro no servidor RMI Remote! A tentar restablecer a ligação!");
cond = true;
} catch (NotBoundException ex) {
System.err.println("Erro no servidor RMI NotBound! A tentar restablecer a ligação!");
cond = true;
} catch (MalformedURLException ex) {
System.err.println("Erro no servidor RMI MalformedURL! A tentar restablecer a ligação!");
cond = true;
}
} while(cond);
return rO.getSuccess();
}
static public void readProperties() {
try {
Properties properties = new Properties();
in = UserBean.class.getClassLoader().getResourceAsStream("app.properties");
properties.load(in);
ip_RMI = properties.getProperty("serverRMI.address");
serverRMI = Integer.parseInt (properties.getProperty("serverRMI.port"));
} catch(IOException e) {
System.err.println("Erro a ler o ficheiro .properties!");
} finally {
if(in != null) {
try {
in.close();
} catch(IOException e) {System.out.println("Erro a fechar!"); }
}
}
}
}
Here is Tomcat Log:
19-Nov-2014 14:21:04.618 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn Parameter [action:loginAction] is on the excludeParams list of patterns!
19-Nov-2014 14:21:05.086 SEVERE [http-apr-8080-exec-109] null.null Notificação para o Desenvolvedor (altere o paramêtro struts.devMode para false para desabilitar esta mensagem):
Unexpected Exception caught setting 'userBean.password' on 'class direstruts.action.LoginAction: Error setting expression 'userBean.password' with value ['YYY', ]
19-Nov-2014 14:21:05.101 SEVERE [http-apr-8080-exec-109] null.null Notificação para o Desenvolvedor (altere o paramêtro struts.devMode para false para desabilitar esta mensagem):
Unexpected Exception caught setting 'userBean.username' on 'class direstruts.action.LoginAction: Error setting expression 'userBean.username' with value ['XXX', ]
19-Nov-2014 14:21:05.210 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn Caught an exception while evaluating expression 'userBean.username' against value stack
Caught an Ognl exception while getting property userBean - Class: ognl.OgnlRuntime
File: OgnlRuntime.java
Method: getMethodValue
Line: 1456 - ognl/OgnlRuntime.java:1456:-1
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:143)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:494)
at com.opensymphony.xwork2.ognl.OgnlUtil.getValue(OgnlUtil.java:255)
at com.opensymphony.xwork2.ognl.OgnlValueStack.getValue(OgnlValueStack.java:358)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValue(OgnlValueStack.java:347)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValueWhenExpressionIsNotNull(OgnlValueStack.java:322)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:308)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:366)
at com.opensymphony.xwork2.util.TextParseUtil$1.evaluate(TextParseUtil.java:157)
at com.opensymphony.xwork2.util.OgnlTextParser.evaluate(OgnlTextParser.java:49)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:167)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:112)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:85)
at org.apache.struts2.components.Component.findValue(Component.java:353)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:813)
at org.apache.struts2.components.UIBean.end(UIBean.java:544)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005ftextfield_005f0(loginPage_jsp.java:273)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005fform_005f0(loginPage_jsp.java:182)
at org.apache.jsp.loginPage_jsp._jspService(loginPage_jsp.java:114)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: ognl.OgnlException: userBean [java.lang.NullPointerException]
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1456)
at ognl.ObjectPropertyAccessor.getPossibleProperty(ObjectPropertyAccessor.java:60)
at ognl.ObjectPropertyAccessor.getProperty(ObjectPropertyAccessor.java:147)
at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.getProperty(ObjectAccessor.java:17)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:138)
... 68 more
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at direstruts.model.UserBean.readProperties(UserBean.java:128)
at direstruts.model.UserBean.<init>(UserBean.java:27)
at direstruts.action.LoginAction.getUserBean(LoginAction.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:891)
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1454)
... 73 more
19-Nov-2014 14:21:05.288 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn NOTE: Previous warning message was issued due to devMode set to true.
19-Nov-2014 14:21:05.429 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn Caught an exception while evaluating expression 'userBean.password' against value stack
Caught an Ognl exception while getting property userBean - Class: ognl.OgnlRuntime
File: OgnlRuntime.java
Method: getMethodValue
Line: 1456 - ognl/OgnlRuntime.java:1456:-1
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:143)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:494)
at com.opensymphony.xwork2.ognl.OgnlUtil.getValue(OgnlUtil.java:255)
at com.opensymphony.xwork2.ognl.OgnlValueStack.getValue(OgnlValueStack.java:358)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValue(OgnlValueStack.java:347)
at com.opensymphony.xwork2.ognl.OgnlValueStack.tryFindValueWhenExpressionIsNotNull(OgnlValueStack.java:322)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:308)
at com.opensymphony.xwork2.ognl.OgnlValueStack.findValue(OgnlValueStack.java:366)
at com.opensymphony.xwork2.util.TextParseUtil$1.evaluate(TextParseUtil.java:157)
at com.opensymphony.xwork2.util.OgnlTextParser.evaluate(OgnlTextParser.java:49)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:167)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:112)
at com.opensymphony.xwork2.util.TextParseUtil.translateVariables(TextParseUtil.java:85)
at org.apache.struts2.components.Component.findValue(Component.java:353)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:813)
at org.apache.struts2.components.UIBean.end(UIBean.java:544)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005fpassword_005f0(loginPage_jsp.java:313)
at org.apache.jsp.loginPage_jsp._jspx_meth_s_005fform_005f0(loginPage_jsp.java:191)
at org.apache.jsp.loginPage_jsp._jspService(loginPage_jsp.java:114)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:721)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
at org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:562)
at org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2403)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2392)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: ognl.OgnlException: userBean [java.lang.NullPointerException]
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1456)
at ognl.ObjectPropertyAccessor.getPossibleProperty(ObjectPropertyAccessor.java:60)
at ognl.ObjectPropertyAccessor.getProperty(ObjectPropertyAccessor.java:147)
at com.opensymphony.xwork2.ognl.accessor.ObjectAccessor.getProperty(ObjectAccessor.java:17)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2317)
at com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.getProperty(CompoundRootAccessor.java:138)
... 68 more
Caused by: java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at direstruts.model.UserBean.readProperties(UserBean.java:128)
at direstruts.model.UserBean.<init>(UserBean.java:27)
at direstruts.action.LoginAction.getUserBean(LoginAction.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at ognl.OgnlRuntime.invokeMethod(OgnlRuntime.java:891)
at ognl.OgnlRuntime.getMethodValue(OgnlRuntime.java:1454)
... 73 more
19-Nov-2014 14:21:05.507 WARNING [http-apr-8080-exec-109] com.opensymphony.xwork2.util.logging.jdk.JdkLogger.warn NOTE: Previous warning message was issued due to devMode set to true.
[EDIT]
I forgot to mention I have an action in which all other actions extend.
Here it is:
package direstruts.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
public class GenericAction extends ActionSupport implements SessionAware{
protected static final long serialVersionUID = 4L;
protected Map<String, Object> session;
#Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
}
To preserve action memory, the GenericAction implements SessionAware. Is that ok?

As reported in Parameters Interceptor documentation (and also explained in this answer), the exception:
.Error setting expression 'userBean.password' with value ['XXX', ]
means you are missin a Setter.
JavaBeans convention establishes that you should have a property, with a getter and a setter with the same name, and Struts2 works following those principles, performing introspection through reflection to outline your Action's objects.
What do you have in your code instead ?
public UserBean getUserBean() {
if(!session.containsKey("userBean"))
this.setUserBean(new UserBean());
return (UserBean) session.get("userBean");
}
public void setUserBean(UserBean userBean) {
session.put("userBean", userBean);
}
A little un-standard, uh !
The property private UserBean userBean; does not even exists, and getters and setters are doing strange session things (while they should not even have any business).
Change it to
private UserBean userBean;
public UserBean getUserBean() {
return userBean;
}
public void setUserBean(UserBean userBean) {
this.userBean = userBean;
}
And it will work.
Then IF needed, find another way to deal with the session and your object (like prepare() method, or even execute()).

Related

Exception when submitting a page containing <s:select>

I am working on a project using Struts2. In that, there is a dynamic dropdown. Whenever I select values and submit the page I'm getting below exception. I tried a few alternatives but nothing worked for me. Below is the exception stack trace.
SEVERE: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'locname': The requested list key 'requestListLocationInfo' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:260)
at org.apache.struts2.components.Component.findValue(Component.java:356)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:84)
at org.apache.struts2.components.Select.evaluateExtraParams(Select.java:104)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:886)
at org.apache.struts2.components.UIBean.end(UIBean.java:535)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.AddReader_jsp._jspx_meth_s_005fselect_005f0(AddReader_jsp.java:592)
at org.apache.jsp.AddReader_jsp._jspx_meth_s_005fform_005f0(AddReader_jsp.java:426)
at org.apache.jsp.AddReader_jsp._jspService(AddReader_jsp.java:332)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:720)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:466)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:391)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:318)
at org.apache.struts2.result.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:173)
at org.apache.struts2.result.StrutsResultSupport.execute(StrutsResultSupport.java:208)
at com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:373)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:277)
at org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:253)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:176)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:260)
at org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:52)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.doIntercept(ConversionErrorInterceptor.java:139)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:134)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:199)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:69)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.DateTextFieldInterceptor.intercept(DateTextFieldInterceptor.java:115)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:88)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:246)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:99)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:139)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:157)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:174)
at com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:171)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:201)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:193)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:247)
at org.apache.struts2.factory.StrutsActionProxy.execute(StrutsActionProxy.java:53)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:577)
at org.apache.struts2.dispatcher.ExecuteOperations.executeAction(ExecuteOperations.java:81)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:143)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
JSP Code
<s:if test="hasActionMessages()">
<div class="welcome">
<s:actionmessage />
</div>
</s:if>
<s:elseif test="hasActionErrors()">
<div class="errors">
<s:actionerror />
</div>
</s:elseif>
<div id="myDIV" style="margin-top: 8%; margin-left: 25%;">
<label>Reader IP:</label>&nbsp <input type="text" name="readerIp" id="readerIp" required>&nbsp &nbsp &nbsp <br>
<label>Antenna ID:</label>&nbsp <input type="text" name="antennaId" id="antennaId" required>&nbsp
&nbsp &nbsp <br> <label>Select Gate:</label>&nbsp
<s:select id="locname" name="locname" list = "requestListLocationInfo" listKey = "locId" listValue = "locname" headerKey = "-1" headerValue = "Select Gate" />
<br>
<button class="btn" id="newBtn"
style="margin-top: 2%; margin-left: 17%; width: 17%; text-decoration: none;"
onclick="clickedMe(this.id)">Add</button>
</div>
</s:form>
Method in Action class:
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String addReaderConfig() {
HttpServletRequest req = ServletActionContext.getRequest();
try {
String locName = req.getParameter("newButton");
int locationid = Integer.parseInt(locName);
String readerIp = req.getParameter("readerIp");
String antenaID = req.getParameter("antennaId");
int antennaId = Integer.parseInt(antenaID);
String created_by = req.getParameter("created_by");
String company_id = (String) ActionContext.getContext().getSession().get("company_id");
int companyId = Integer.parseInt(company_id);
int i = ChartDAO.addReader(readerIp, antennaId, locationid, companyId, created_by);
if (i > 0) {
msg = Constants.READER_ADDED_SUCCESSFULLY;
addActionMessage(msg);
} else {
msg = Constants.READER_ADDING_FAILED;
addActionError(msg);
return Constants.ERROR;
}
} catch (Exception e) {
e.printStackTrace();
return Constants.ERROR;
}
return Constants.SUCCESS;
}
POJO
private int locId;
private String locname;
private List < ChartPOJO > requestListLocationInfo = null;
public String getLocname() {
return locname;
}
public void setLocname(String locname) {
this.locname = locname;
}
public int getLocId() {
return locId;
}
public void setLocId(int locId) {
this.locId = locId;
}
public List < ChartPOJO > getRequestListLocationInfo() {
return requestListLocationInfo;
}
public void setRequestListLocationInfo(List < ChartPOJO > requestListLocationInfo) {
this.requestListLocationInfo = requestListLocationInfo;
}
Method in DAO class
public static int addReader(String readerIp, int antennaId, int locId, int company_id, String created_by) {
int status = 0;
String driverClass = Constants.DB_Driver;
Class.forName(driverClass);
String url = Constants.DB_Address;
String username = Constants.DB_Username;
String password = Constants.DB_Password;
try (Connection conn = DriverManager.getConnection(url, username, password);) {
try (PreparedStatement ps1 = conn.prepareStatement("select locationid,loc_name from locations where locationid=?");) {
ps1.setInt(1, locId);
try (ResultSet rs2 = ps1.executeQuery();) {
if (!rs2.next()) {
String query = "INSERT INTO reader(ipaddress,antenaid,companyid,locationid,status,created_by,created_date) values(?,?,?,?,?,?,?)";
try(PreparedStatement ps = conn.prepareStatement(query);) {
ps.setString(1, readerIp);
ps.setInt(2, antennaId);
ps.setInt(3, company_id);
ps.setInt(4, locId);
ps.setInt(5, 1);
ps.setString(6, created_by);
LocalDateTime now = LocalDateTime.now();
System.out.println("Before : " + now);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatDateTime = now.format(formatter);
System.out.println("After : " + formatDateTime);
ps.setString(7, formatDateTime);
status = ps.executeUpdate();
System.out.println("after adding reader successfully");
}
} else {
System.out.println("location already exists");
}
}
}
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
return status;
}
return status;
}
May I know the reason for this exception and how to fix it. Thanks in advance.
You have to remove listKey or resolve it in select field somewhere in you project.
Your logs complain about requestListLocationInfo list probably without properly listKey value or with null value

How to fix HTTP Status 500 - Internal Server Error | Servlet Error

I'm trying to send variables between jsp and servlets, but I got this error that I still can't figure out why. It keeps sending HTTP Status 500 error.
it sending HTTP status 500 eror and java.lang.NullPointerException
but when i test java class in junit it ran fine.
this is jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="model.StudentDao"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Student</h1>
<table class="table">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach items="${requestScope.students}" var="student">
<tr>
<td><c:out value="${student.getStudentId()}"/></td>
<td><c:out value="${student.getStudentName()}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
and this my servlet:
package controller;
import...
#WebServlet("/StudentListServlet")
public class StudentListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DbConnect dbConnect = new DbConnect();
Connection connection = dbConnect.connect();
StudentDao studentDao = new StudentDao(connection);
ArrayList<Student> students = null;
try {
students = studentDao.findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("students", students);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
StudentDao :
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentDao {
private Connection connection;
public StudentDao(Connection connection) {
super();
this.connection = connection;
}
public ArrayList<Student> findAll() throws SQLException{
ArrayList<Student> students = new ArrayList<>();
Student student = null;
Statement statement = this.connection.createStatement();
String sqlText = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(sqlText);
while(resultSet.next()){
student = new Student();
student.setStudentId(resultSet.getString("student_Id"));
student.setStudentName(resultSet.getString("student_Name"));
students.add(student);
}
resultSet.close();
statement.close();
return students;
}
}
DbConnect:
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnect {
private static final String URL = "jdbc:mysql://localhost:3306/university";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection connection;
public Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
if(!this.connection.isClosed())
System.out.println("MySQL Connected");
else
System.out.println("MySQL Connect fail!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return this.connection;
}
public void close() throws SQLException {
this.connection.close();
}
}
Stack Trace :
SEVERE: Servlet.service() for servlet [controller.StudentListServlet] in context with path [/MySQLDemo] threw exception
java.lang.NullPointerException
at model.StudentDao.findAll(StudentDao.java:21)
at controller.StudentListServlet.doGet(StudentListServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Sorry for the long post.
anyone with an idea why this get error?
You are not loading the jdbc driver in your servelet
you can the jdbc driver as follows:
String driver = "com.mysql.jdbc.Driver";
// Load the JDBC driver
Class driver_class = Class.forName(driver);

How to solve UnknownSessionException thrown in logout method in Apache Shiro?

Good afternoon guys! I have a project in JSF that uses Apache Shiro Authentication. The login method works fine, but the logout method throw UnknownSessionException.
Here is my dependencies on pom.xml(Maven):
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
StackTrace:
abr 07, 2017 9:20:26 PM com.sun.faces.context.AjaxExceptionHandlerImpl handlePartialResponseError
GRAVE: java.lang.IllegalStateException: org.apache.shiro.session.UnknownSessionException: There is no session with id [e3b18152-09c3-4644-8815-f3bf7dd77513]
at org.apache.shiro.web.servlet.ShiroHttpSession.getAttribute(ShiroHttpSession.java:133)
at com.sun.faces.context.SessionMap.put(SessionMap.java:127)
at com.sun.faces.context.SessionMap.put(SessionMap.java:61)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.getResponseEncoding(FaceletViewHandlingStrategy.java:1310)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.createResponseWriter(FaceletViewHandlingStrategy.java:1198)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:405)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.shiro.session.UnknownSessionException: There is no session with id [e3b18152-09c3-4644-8815-f3bf7dd77513]
at org.apache.shiro.session.mgt.eis.AbstractSessionDAO.readSession(AbstractSessionDAO.java:170)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSessionFromDataSource(DefaultSessionManager.java:236)
at org.apache.shiro.session.mgt.DefaultSessionManager.retrieveSession(DefaultSessionManager.java:222)
at org.apache.shiro.session.mgt.AbstractValidatingSessionManager.doGetSession(AbstractValidatingSessionManager.java:118)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupSession(AbstractNativeSessionManager.java:148)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.lookupRequiredSession(AbstractNativeSessionManager.java:152)
at org.apache.shiro.session.mgt.AbstractNativeSessionManager.getAttribute(AbstractNativeSessionManager.java:249)
at org.apache.shiro.session.mgt.DelegatingSession.getAttribute(DelegatingSession.java:141)
at org.apache.shiro.session.ProxiedSession.getAttribute(ProxiedSession.java:121)
at org.apache.shiro.web.servlet.ShiroHttpSession.getAttribute(ShiroHttpSession.java:131)
... 49 more
Shiro.ini:
# =======================
# Shiro INI configuration
# =======================
[main]
# ===============================
# ===============================
# Session Manager SHIRO NATIVE (WEB)
# ===============================
# ===============================
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
securityManager.sessionManager = $sessionManager
securityManager.sessionManager.globalSessionTimeout = 3600000
shiro.loginUrl = /faces/paginalogin.xhtml
sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
# ===============================
# ===============================
# DATABASE SQL
# ===============================
# ===============================
jdbcRealm=org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = false
jdbcRealm.authenticationCachingEnabled = false
jdbcRealm.authenticationQuery = SELECT senha FROM usuario WHERE email = ?
jdbcRealm.userRolesQuery = SELECT if(nivel='A','admin','normal') FROM usuario WHERE email = ?
# ===============================
# MySQL
# ===============================
dbs=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
#dbs.driverClass = com.mysql.jdbc.Driver
dbs.user=root
dbs.databaseName=shiroexemplo
dbs.serverName=localhost
dbs.portNumber=3306
# ===============================
# ===============================
# DATABASE INSTANCE
# ===============================
# ===============================
jdbcRealm.dataSource=$dbs
[users]
# The 'users' section is for simple deployments
# when you only need a small number of statically-defined
# set of User accounts.
[roles]
admin=*
normal=*
[urls]
/faces/admin/*= authc, roles[admin]
/faces/normal/*=authc, roles[normal]
/faces/paginalogin.xhtml = anon
Java class:
package com.mycompany.shiroexemplo.bean;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.mycompany.shiroexemplo.dao.UsuarioDAO;
import com.mycompany.shiroexemplo.model.Usuario;
#ManagedBean
#SessionScoped
public class LoginController implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String senha;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public Usuario getUsuario() {
return usuario;
}
public void setUsuario(Usuario usuario) {
this.usuario = usuario;
}
public Usuario usuario;
private static final Logger log = LoggerFactory.getLogger(LoginController.class);
public String autenticate() {
SimpleHash hash = new SimpleHash("md5", senha);
UsernamePasswordToken token = new UsernamePasswordToken(username, hash.toHex());
token.setRememberMe(true);
Subject currentUser = SecurityUtils.getSubject();
log.info("logando usando o email [" + username + "] e senha [" + hash.toHex() + "]");
try {
if (!currentUser.isAuthenticated()) {
currentUser.login(token);
UsuarioDAO ud = new UsuarioDAO();
usuario = ud.getUsuario(username);
}
if (currentUser.hasRole("admin")) {
return "Admin";
} else {
return "Normal";
}
} catch (AuthenticationException e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro: ", "Usuário ou senha incorretos"));
return "paginalogin";
}
}
public String logout(ActionEvent ev) {
Subject currentUser = SecurityUtils.getSubject();
try {
if(currentUser.isAuthenticated()){
currentUser.logout();
}
} catch (Exception e) {
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro: ", e.getMessage()));
return null;
}
return "paginalogin";
}
}
Can you issue a redirect after logout? It's been a while since I've done anything with Faces, so I'm not sure of the request flow that you are seeing. Basically, you would want the logout request to be the last thing to happen before a redirect.
thanks for answer me. Doing some researches, I could solve the problem. First, I commented these lines in my Shiro.ini:
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
securityManager.sessionManager = $sessionManager
securityManager.sessionManager.globalSessionTimeout = 3600000
After that, I implemented javax.servlet.http.HttpSession to get the current session, like this:
HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
Finally, I did a session.invalidate() and also a redirect in the page, like this:
session.invalidate();
FacesContext.getCurrentInstance().getExternalContext.redirect("faces/paginaLogin.xhtml");
The final version of logout method :
public void logout(){
try{
Subject currentUser = SecurityUtils.getSubject();
HttpSession session=(HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if(currentUser.isAuthenticated()){
session.invalidate();
FacesContext.getCurrentInstance().getExternalContext().redirect("faces/paginalogin.xhtml");
}
}catch(Exception e){
e.printStackTrace();
FacesContext.getCurrentInstance().addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro: ", e.getMessage()));
}
}

Executing Unix command from jsp

So I need a unix command to be executed by clicking a button in a jsp.
Here's the jsp:
<body>
<div align="center">
<h2>Welcome to ETL Automation Testing Tool</h2>
<h3>Please select Graph:</h3>
<table border="1">
<th>Graph</th>
<tr>
<td>Graph 1</td>
<td><INPUT TYPE="radio" NAME="graph" VALUE="radio1"></td>
</tr>
</table>
<form action="${pageContext.request.contextPath}/myservlet" method="post">
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</body>
All pretty straightforward there.
Here's the servlet:
#WebServlet("/myservlet")
public class MyServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UnixPrompt unixprompt = new UnixPrompt();
unixprompt.connect();
}
}
Here's the code to connect to ssh and execute a command:
import com.jcraft.jsch.*;
import java.io.*;
public class UnixPrompt{
public static void connect(){
try{
JSch jsch=new JSch();
String host=null;
String user="******";
host="*******";
String config =
"Port 22\n"+
"\n"+
"Host foo\n"+
" User "+user+"\n"+
" Hostname "+host+"\n"+
"Host *\n"+
" ConnectTime 30000\n"+
" PreferredAuthentications keyboard-interactive,password,publickey\n"+
" #ForwardAgent yes\n"+
" #StrictHostKeyChecking no\n"+
" #IdentityFile ~/.ssh/id_rsa\n"+
" #UserKnownHostsFile ~/.ssh/known_hosts";
ConfigRepository configRepository =
com.jcraft.jsch.OpenSSHConfig.parse(config);
jsch.setConfigRepository(configRepository);
Session session=jsch.getSession("foo");
String passwd ="*****";
session.setPassword(passwd);
UserInfo ui = new MyUserInfo(){
public boolean promptYesNo(String message){
int foo = 0;
return foo==0;
}
};
session.setUserInfo(ui);
session.connect();
String command="pwd";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
byte[] tmp=new byte[1024];
while(true){
while(in.available()>0){
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
}
if(channel.isClosed()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
public static void main(String arg[]){
connect();
}
public static abstract class MyUserInfo
implements UserInfo, UIKeyboardInteractive{
public String getPassword(){ return null; }
public boolean promptYesNo(String str){ return false; }
public String getPassphrase(){ return null; }
public boolean promptPassphrase(String message){ return false; }
public boolean promptPassword(String message){ return false; }
public void showMessage(String message){ }
public String[] promptKeyboardInteractive(String destination,
String name,
String instruction,
String[] prompt,
boolean[] echo){
return null;
}
}
}
I am able to connect to the SSH and execute commands through the standalone UnixPrompt class but am not able to do so through the jsp.
This is the error I am getting:
SEVERE: Servlet.service() for servlet [unix.MyServlet] in context with
path [/Scratchpad] threw exception [Servlet execution threw an
exception] with root cause java.lang.ClassNotFoundException:
com.jcraft.jsch.ConfigRepository at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1858)
at
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1709)
at unix.MyServlet.doPost(MyServlet.java:17) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:722)
The class the error refers to is present in the newer JSch jar having version 0.1.54 which I have included in the build path so I'm not sure what the problem is.
Any help would be appreciated

Using RMI with JSF and Tomcat

I want to write a simple application using RMI. On the server side I have an interface foo and a class fooImpl.
My interface is:
import java.rmi.Remote;
public interface Foo extends Remote {
public String exec(String test) throws Exception;
}
My implementation of the the above interface is:
import java.rmi.server.UnicastRemoteObject;
public class FooImpl extends UnicastRemoteObject implements Foo {
public FooImpl() throws Exception {
java.rmi.registry.LocateRegistry.createRegistry(1099);
java.rmi.Naming.rebind("myFoo",this);
}
public String exec(String test) {
return "This is a Test";
}
public static void main(String[] args) {
try {
FooImpl fooImpl = new FooImpl();
} catch (Exception e) {
e.printStackTrace();
}
}
}
On the client side, I have web application using PrimeFace which is runnig on Tomcat. There is a IndexBean on client side:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
#ManagedBean
#RequestScoped
public class IndexBean {
public void execute() {
try {
Foo foo = (Foo) java.rmi.Naming.lookup("//localhost/myFoo");
System.out.println(foo.exec());
} catch (NotBoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
when I execute the code, I get the following error at the client side:
java.rmi.UnmarshalException: error unmarshalling return; nested
exception is: java.lang.ClassNotFoundException: Foo (no security
manager: RMI class loader disabled) at
sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source) at
java.rmi.Naming.lookup(Naming.java:101) at
bean.IndexBean.execute(IndexBean.java:15) 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
org.apache.el.parser.AstValue.invoke(AstValue.java:245) at
org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:277)
at
org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:96)
at
javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:88)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:51)
at
javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:409)
at javax.faces.component.UICommand.broadcast(UICommand.java:103) at
javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1013)
at
javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:284)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1302)
at
javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:745)
at
org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:38)
at
org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
at
org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:744) Caused by:
java.lang.ClassNotFoundException: Foo (no security manager: RMI class
loader disabled) at
sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:553)
at
java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:646)
at
java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:311)
at
sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:255)
at
java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1558)
at
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1514)
at
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1771)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1350)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:370)
... 44 more
Also, I changed the port which Tomcat uses to do not have conflict with RMI port.
The client doesn't have the remote interface on its CLASSPATH, or, probably, the stub either. To avoid using a stub, add
super(0);
as the first line of the constructor.
NB you must store the result of createRegistry() in a static variable, to prevent the Registry from exiting.

Categories