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()));
}
}
Related
I have a database table named USER and a model class named User which is annotated as #Entity using javax.persistence. When I try to query a user I get the following exception:
SEVERE: Servlet.service() for servlet [Jersey Web Application] in context with path [/myapp] threw exception [java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped [FROM User u WHERE u.username = :username]] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: User is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3696)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3585)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:720)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:576)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:313)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:261)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:266)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:153)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:546)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:655)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:679)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
at com.xxxxxxx.myapp.myapp.sevice.UserService.getUser(UserService.java:32)
at com.xxxxxxx.myapp.myapp.resources.UserResource.getUser(UserResource.java:23)
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:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$TypeOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:205)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:326)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
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:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
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:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:861)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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:748)
Aug 20, 2017 5:29:58 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/myapp] has started
Aug 20, 2017 5:29:58 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
WARNING: The web application [myapp] registered the JDBC driver [org.postgresql.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
Aug 20, 2017 5:29:58 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesThreads
WARNING: The web application [myapp] appears to have started a thread named [pool-2-thread-1] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
sun.misc.Unsafe.park(Native Method)
java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:215)
java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:2078)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1093)
java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:809)
java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
java.lang.Thread.run(Thread.java:748)
My query is in a service class called UserService.java which is as below:
import javax.persistence.TypedQuery;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.xxxxxx.model.User;
public class UserService {
private static SessionFactory factory;
public UserService() {
}
public User getUser(String username) {
try{
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
Session session = factory.openSession();
Transaction tx = null;
User user = null;
try {
tx = session.beginTransaction();
TypedQuery<User> query = session.createQuery("FROM User u WHERE u.username = :username", User.class).setParameter("username", username);
user = query.getSingleResult();
} catch(HibernateException e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return user;
}
}
My model class is below:
import javax.persistence.*;
#Entity
#Table(name="USER")
public class User {
#Id #GeneratedValue
#Column(name="id")
private long id;
#Column(name="username", unique=true)
private String username;
#Column(name="email")
private String email;
#Column(name="created")
private Timestamp created;
public User(long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
}
For most people who had the same issue it seems that they were using the table name instead of the entity name. However, in my case, I think I'm using the correct entity name. I also tried removing the arguments and body of the constructor of the User but didn't help.
For clarity, below is my hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<!-- connection settings -->
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/myapp</property>
<property name="hibernate.connection.username">admin</property>
<property name="hibernate.connection.password">xxxxx</property>
<!-- sql dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- mapping files -->
<!-- dev config - remove at prod -->
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
For some reason, the annotation is not being processed. You either need to create a mapping file and include in your config, https://www.tutorialspoint.com/hibernate/hibernate_mapping_files.htm or as long as I remember there is a way to specify annotation configuration during hibernate session creation where you specify annotated entities. You are probably missing that part. Please, check this for reference Add Annotated Class in Hibernate by adding all classes in some package. JAVA
I have run into a problem that I have been trying to figure out for days:
I added my driver: mysql-connector-java-5.1.40.jar to build path.
web-inf lib folder, apache tomcat lib folder. And also I have it in web app libaries.
However when I just run a main class and run it works, it is something to do with the web app?
This is my code:
This is the servlet class, that I use to connect to my database
package sql;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterServlet
*/
#WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbUtil sql = new DbUtil();
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (sql.addToAccountToDatabase(username, password, email)) {
System.out.println("Gongratz");
} else {
System.out.println("mhhh ?");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
}
this is the second class how i make connection
package sql;
import java.sql.*;
public class DbUtil {
public Connection getConnection() {
Connection connect = null;
try {
String url = "jdbc:mysql://hidden:3306/hidden";
connect = DriverManager.getConnection(url, "hidden", "hidden");
return connect;
} catch (Exception e) {
System.out.println("Cannot connect to database");
e.printStackTrace();
}
return connect;
}
public boolean addToAccountToDatabase(String username, String password, String email) {
try {
String query = "INSERT INTO Account (username, password, email) VALUES (?, ?,?)";
PreparedStatement pStat = getConnection().prepareStatement(query);
pStat.setString(1, username);
pStat.setString(2, password);
pStat.setString(3, email);
pStat.executeUpdate();
return true;
} catch (Exception e) {
System.out.println("User already exists");
e.printStackTrace();
return false;
}
}
}
And I get this error:
Cannot connect to database
java.sql.SQLException: No suitable driver found for jdbc:mysql://192.185.227.214:3306/ratekas9_illegalminds
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sql.DbUtil.getConnection(DbUtil.java:15)
at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
at sql.RegisterServlet.doPost(RegisterServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
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)
User already exists
java.lang.NullPointerException
at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
at sql.RegisterServlet.doPost(RegisterServlet.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
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)
mhhh ?
Because the String "jdbc:mysql" doesn't declare the driver Class itself, but only the name registered by a potential driver. You have to force the JVM to load the Driver class with a :
Class.forName("com.mysql.jdbc.Driver").newInstance();
before starting the JDBC connection.
You need 3 steps to solve your problem:
Add this code before connection Class.forName("com.mysql.jdbc.Driver");
Add 'JConnector.jar' into your project and build path.
Don't try enter same person because there is error in stack trace "User all ready exist ".
Adding the JAR file into your CLASSPATH (for compilation needs) / project's BUILDPATH and also under your project's WEB-INF/lib folder (for runtime references, i.e., when you deploy your application to an application server). For further reference, please go through this link
Class.forName("com.mysql.jdbc.Driver");
This is no longer required as per Official Java documentation here, but it is a mandatory step if you are using prior versions of JDBC 4.0.
This question can provide you lot many details on this regards.
Hope all these details help you resolve your issue!
follows:
jasig cas 4.0 + shiro 1.2.1 +spring 3.2.1
client configuration file is as follows:
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="https://sso.h-guiyang.com:8443/cas/login?service=https://admin.h-guiyang.com:8081/admin/" />
<property name="successUrl" value="https://admin.h-guiyang.com:8081/admin/"></property>
<property name="filters">
<map>
<entry key="casFilter" value-ref="casFilter"/>
</map>
</property>
<property name="filterChainDefinitions">
<value>
/admin/management/index = casFilter
/ehrLoginSSO/**= anon
/unauthorized = anon
/loginSSO/**= anon
/Captcha.jpg = anon
/styles/** = anon
/ws/** = anon
/resources/** = anon
/styles/** = anon
/login/timeout = anon
<!-- /login = authc -->
/logout = logout
</value>
</property>
</bean>
<bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory"/>
<!-- Shiro's main business-tier object for web-enabled applications -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="shiroDbRealm" />
<property name="cacheManager" ref="shiroEhcacheManager" />
<property name="subjectFactory" ref="casSubjectFactory"/>
</bean>
<bean id="shiroDbRealm" class="net.hp.es.adm.healthcare.rphcp.shiro.ShiroDbCasRealm" depends-on="userDAO, userRoleDAO, organizationRoleDAO, roleDAO">
<property name="userService" ref="userServiceImpl"/>
<property name="userRoleService" ref="userRoleServiceImpl"/>
<property name="roleService" ref="roleServiceImpl"/>
<property name="organizationRoleService" ref="organizationRoleServiceImpl"/>
<property name="casServerUrlPrefix" value="https://sso.h-guiyang.com:8443/cas"/>
<property name="casService" value="https://admin.h-guiyang.com:8081/admin"/>
<property name="useCaptcha" value="false"/>
<property name="activeRoot" value="false"/>
</bean>
<bean id="casFilter" class="org.apache.shiro.cas.CasFilter">
<property name="failureUrl" value="/unauthorized"/>
</bean>
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml"/>
</bean>
<bean id="dWZUserFilter" class="net.hp.es.adm.healthcare.rphcp.shiro.DWZUserFilter"/>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
When I from CAS login successfully into the subsystem,subsystem shiro error as follows:
org.apache.shiro.authz.UnauthenticatedException: Attempting to perform a user-only operation. The current Subject is not a user (they haven't been authenticated or remembered from a previous login). Access denied.
at org.apache.shiro.authz.aop.UserAnnotationHandler.assertAuthorized(UserAnnotationHandler.java:61) ~[shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor.assertAuthorized(AuthorizingAnnotationMethodInterceptor.java:84) ~[shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor.assertAuthorized(AnnotationsAuthorizingMethodInterceptor.java:100) ~[shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.authz.aop.AuthorizingMethodInterceptor.invoke(AuthorizingMethodInterceptor.java:38) ~[shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor.invoke(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:115) ~[shiro-spring-1.2.1.jar:1.2.1]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653) ~[spring-aop-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at net.hp.es.adm.healthcare.rphcp.controller.IndexController$$EnhancerBySpringCGLIB$$e57cb6e1.index(<generated>) ~[spring-core-4.1.2.RELEASE.jar:0.0.1-SNAPSHOT]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_79]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_79]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_79]
at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_79]
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) ~[spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) ~[spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) ~[spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781) ~[spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721) ~[spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) ~[spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) [spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) [spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) [spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857) [spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624) [servlet-api.jar:na]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) [spring-webmvc-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) [servlet-api.jar:na]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) [catalina.jar:7.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.68]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) [tomcat7-websocket.jar:7.0.68]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.68]
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449) [shiro-web-1.2.1.jar:1.2.1]
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365) [shiro-web-1.2.1.jar:1.2.1]
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90) [shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83) [shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383) [shiro-core-1.2.1.jar:1.2.1]
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362) [shiro-web-1.2.1.jar:1.2.1]
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125) [shiro-web-1.2.1.jar:1.2.1]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344) [spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261) [spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.68]
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:176) [spring-orm-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.68]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-4.1.2.RELEASE.jar:4.1.2.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) [catalina.jar:7.0.68]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) [catalina.jar:7.0.68]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:203) [catalina.jar:7.0.68]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) [catalina.jar:7.0.68]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) [catalina.jar:7.0.68]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169) [catalina.jar:7.0.68]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) [catalina.jar:7.0.68]
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) [catalina.jar:7.0.68]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) [catalina.jar:7.0.68]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436) [catalina.jar:7.0.68]
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078) [tomcat-coyote.jar:7.0.68]
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) [tomcat-coyote.jar:7.0.68]
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) [tomcat-coyote.jar:7.0.68]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [na:1.7.0_79]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [na:1.7.0_79]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-coyote.jar:7.0.68]
at java.lang.Thread.run(Thread.java:745) [na:1.7.0_79]
Caused by: org.apache.shiro.authz.AuthorizationException: Not authorized to invoke method: public java.lang.String net.hp.es.adm.healthcare.rphcp.controller.IndexController.index(java.util.Map)
at org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor.assertAuthorized(AuthorizingAnnotationMethodInterceptor.java:90) ~[shiro-core-1.2.1.jar:1.2.1]
... 62 common frames omitted
2016-03-23 10:12:27,808 [http-bio-8081-exec-3] ERROR 500.jsp - org.apache.shiro.authz.UnauthenticatedException: Attempting to perform a user-only operation. The current Subject is not a user (they haven't been authenticated or remembered from a previous login). Access denied.
at org.apache.shiro.authz.aop.UserAnnotationHandler.assertAuthorized(UserAnnotationHandler.java:61)
at org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor.assertAuthorized(AuthorizingAnnotationMethodInterceptor.java:84)
at org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor.assertAuthorized(AnnotationsAuthorizingMethodInterceptor.java:100)
at org.apache.shiro.authz.aop.AuthorizingMethodInterceptor.invoke(AuthorizingMethodInterceptor.java:38)
at org.apache.shiro.spring.security.interceptor.AopAllianceAnnotationsAuthorizingMethodInterceptor.invoke(AopAllianceAnnotationsAuthorizingMethodInterceptor.java:115)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at net.hp.es.adm.healthcare.rphcp.controller.IndexController$$EnhancerBySpringCGLIB$$e57cb6e1.index(<generated>)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
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.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.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:176)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
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:203)
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:169)
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:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
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:745)
Caused by: org.apache.shiro.authz.AuthorizationException: Not authorized to invoke method: public java.lang.String net.hp.es.adm.healthcare.rphcp.controller.IndexController.index(java.util.Map)
at org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor.assertAuthorized(AuthorizingAnnotationMethodInterceptor.java:90)
... 62 more
ShiroDbrealm code :
public class ShiroDbCasRealm extends CasRealm {
private static final Logger log = LoggerFactory.getLogger(ShiroDbCasRealm.class);
private static final int INTERATIONS = 1024;
private static final int SALT_SIZE = 8;
private static final String ALGORITHM = "SHA-1";
protected boolean activeRoot = false;
protected boolean useCaptcha = false;
#Autowired
protected UserService userService;
#Autowired
private RolePermissionService rolePermissionService;
#Autowired
protected RoleService roleService;
#Autowired
protected UserRoleService userRoleService;
#Autowired
protected OrganizationRoleService organizationRoleService;
public ShiroDbCasRealm() {
HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(ALGORITHM);
matcher.setHashIterations(INTERATIONS);
setCredentialsMatcher(matcher);
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
throws AuthenticationException {
System.out.println("================");
CasToken casToken = (CasToken) authcToken;
if (authcToken == null)
return null;
String ticket = (String) casToken.getCredentials();
if (!StringUtils.hasText(ticket))
return null;
TicketValidator ticketValidator = ensureTicketValidator();
try {
Assertion casAssertion = ticketValidator.validate(ticket, getCasService());
AttributePrincipal casPrincipal = casAssertion.getPrincipal();
String userId = casPrincipal.getName();
log.debug("Validate ticket : {} in CAS server : {} to retrieve user : {}",
new Object[] { ticket, getCasServerUrlPrefix(), userId });
Map attributes = casPrincipal.getAttributes();
casToken.setUserId(userId);
User user = userService.getByUsername(userId);
if (user != null) {
if (user.getStatus().equals(User.STATUS_DISABLED)) {
throw new DisabledAccountException();
}
byte[] salt = Encodes.decodeHex(user.getSalt());
ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUsername());
shiroUser.setUser(userService.get(shiroUser.getId()));
return new SimpleAuthenticationInfo(shiroUser, user.getPassword(), ByteSource.Util.bytes(salt),
getName());
} else {
return null;
}
// String rememberMeAttributeName = getRememberMeAttributeName();
// String rememberMeStringValue = (String)
// attributes.get(rememberMeAttributeName);
// boolean isRemembered = rememberMeStringValue != null &&
// Boolean.parseBoolean(rememberMeStringValue);
// if (isRemembered)
// casToken.setRememberMe(true);
// List principals = CollectionUtils.asList(new Object[] { userId,
// attributes });
// PrincipalCollection principalCollection = new
// SimplePrincipalCollection(principals, getName());
// return new SimpleAuthenticationInfo(principalCollection, ticket);
} catch (TicketValidationException e) {
throw new CasAuthenticationException(
(new StringBuilder()).append("Unable to validate ticket [").append(ticket).append("]").toString(),
e);
}
}
#Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
System.out.println((String) principals.getPrimaryPrincipal() + "我进来了~~~~~~~");
Collection<String> hasPermissions = null;
Collection<String> hasRoles = null;
String username = (String) principals.getPrimaryPrincipal();
User user = userService.getByUsername(username);
ShiroUser shiroUser = new ShiroUser(user.getId(), user.getUsername());
shiroUser.setUser(userService.get(shiroUser.getId()));
List<UserRole> userRoles = userRoleService.findByUserId(shiroUser.getId());
List<OrganizationRole> organizationRoles = organizationRoleService
.findByOrganizationId(shiroUser.getUser().getOrganization().getId());
Collection<Role> roles = getUserRoles(userRoles, organizationRoles);
hasRoles = makeRoles(roles, shiroUser);
hasPermissions = makePermissions(roles, shiroUser);
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRoles(hasRoles);
info.addStringPermissions(hasPermissions);
shiroUser.setAttribute("roleNames", hasRoles);
// return newAuthorizationInfo(shiroUser);
return info;
}
private SimpleAuthorizationInfo newAuthorizationInfo(ShiroUser shiroUser) {
Collection<String> hasPermissions = null;
Collection<String> hasRoles = null;
// 是否启用超级管理员 && id==1为超级管理员,构造所有权限
if (activeRoot && shiroUser.getId() == 1) {
hasRoles = new HashSet<String>();
Page page = new Page();
page.setNumPerPage(Integer.MAX_VALUE);
List<Role> roles = roleService.findAll(page);
for (Role role : roles) {
hasRoles.add(role.getName());
}
hasPermissions = new HashSet<String>();
hasPermissions.add("*");
if (log.isInfoEnabled()) {
log.info("使用了" + shiroUser.getLoginName() + "的超级管理员权限:" + "。At " + new Date());
log.info(shiroUser.getLoginName() + "拥有的角色:" + hasRoles);
log.info(shiroUser.getLoginName() + "拥有的权限:" + hasPermissions);
}
} else {
List<UserRole> userRoles = userRoleService.findByUserId(shiroUser.getId());
List<OrganizationRole> organizationRoles = organizationRoleService
.findByOrganizationId(shiroUser.getUser().getOrganization().getId());
Collection<Role> roles = getUserRoles(userRoles, organizationRoles);
hasRoles = makeRoles(roles, shiroUser);
hasPermissions = makePermissions(roles, shiroUser);
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRoles(hasRoles);
info.addStringPermissions(hasPermissions);
shiroUser.setAttribute("roleNames", hasRoles);
return info;
}
private Collection<Role> getUserRoles(List<UserRole> userRoles, List<OrganizationRole> organizationRoles) {
Set<Role> roles = new HashSet<Role>();
for (UserRole userRole : userRoles) {
roles.add(userRole.getRole());
}
for (OrganizationRole organizationRole : organizationRoles) {
roles.add(organizationRole.getRole());
}
return roles;
}
private Collection<String> makeRoles(Collection<Role> roles, ShiroUser shiroUser) {
Collection<String> hasRoles = new HashSet<String>();
for (Role role : roles) {
hasRoles.add(role.getName());
}
if (log.isInfoEnabled()) {
log.info(shiroUser.getLoginName() + "拥有的角色:" + hasRoles);
}
return hasRoles;
}
private Collection<String> makePermissions(Collection<Role> roles, ShiroUser shiroUser) {
// 清空shiroUser中map
shiroUser.getHasDataControls().clear();
shiroUser.getHasModules().clear();
Collection<String> stringPermissions = new ArrayList<String>();
for (Role role : roles) {
List<RolePermission> rolePermissions = role.getRolePermissions();
for (RolePermission rolePermission : rolePermissions) {
Permission permission = rolePermission.getPermission();
String resource = permission.getModule().getSn();
String operate = permission.getSn();
StringBuilder builder = new StringBuilder();
builder.append(resource + ":" + operate);
shiroUser.getHasModules().put(resource, permission.getModule());
// StringBuilder dcBuilder = new StringBuilder();
// for (RolePermissionDataControl rpdc :
// rolePermission.getRolePermissionDataControls()) {
// DataControl dataControl = rpdc.getDataControl();
// dcBuilder.append(dataControl.getName() + ",");
//
// shiroUser.getHasDataControls().put(dataControl.getName(),
// dataControl);
// }
// if (dcBuilder.length() > 0) {
// builder.append(":" + dcBuilder.substring(0,
// dcBuilder.length() - 1));
// }
//
stringPermissions.add(builder.toString());
}
}
if (log.isInfoEnabled()) {
log.info(shiroUser.getLoginName() + "拥有的权限:" + stringPermissions);
}
return stringPermissions;
}
public static class HashPassword {
public String salt;
public String password;
}
public static HashPassword encryptPassword(String plainPassword) {
HashPassword result = new HashPassword();
byte[] salt = Digests.generateSalt(SALT_SIZE);
result.salt = Encodes.encodeHex(salt);
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, INTERATIONS);
result.password = Encodes.encodeHex(hashPassword);
return result;
}
public static boolean validatePassword(String plainPassword, String password, String salt) {
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), Encodes.decodeHex(salt), INTERATIONS);
String oldPassword = Encodes.encodeHex(hashPassword);
return password.equals(oldPassword);
}
#Override
protected Object getAuthorizationCacheKey(PrincipalCollection principals) {
ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
return shiroUser.getLoginName();
}
public void clearCachedAuthorizationInfo(String loginName) {
ShiroUser shiroUser = new ShiroUser(loginName);
SimplePrincipalCollection principals = new SimplePrincipalCollection(shiroUser, getName());
clearCachedAuthorizationInfo(principals);
}
public void clearAllCachedAuthorizationInfo() {
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
if (cache != null) {
for (Object key : cache.keys()) {
cache.remove(key);
}
}
}
public void setActiveRoot(boolean activeRoot) {
this.activeRoot = activeRoot;
}
/**
* 设置 useCaptcha 的值
*
* #param useCaptcha
*/
public void setUseCaptcha(boolean useCaptcha) {
this.useCaptcha = useCaptcha;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
public void setUserRoleService(UserRoleService userRoleService) {
this.userRoleService = userRoleService;
}
/**
* 设置 organizationRoleService 的值
*
* #param organizationRoleService
*/
public void setOrganizationRoleService(OrganizationRoleService organizationRoleService) {
this.organizationRoleService = organizationRoleService;
}
/**
* #param roleService
* the roleService to set
*/
public void setRoleService(RoleService roleService) {
this.roleService = roleService;
}
}
How can I solve this problem, thank you!
shiro-cas module is now deprecated in Shiro: you should use: https://github.com/bujiio/buji-pac4j instead.
That said, I'm a bit confused by your configuration: how the redirection to CAS is trigered? The casFilter should be configured on a callback url...
I'm new to connecting to MySQL using JDBC with tomcat. I've been following an excellent tutorial here but am struggling. I have ensured my EC2 security group is configured to MYSQL port 3306 0.0.0.0/0 and HTTP port 80 0.0.0.0/0. I'm currently getting the error: Name [jdbc/bbytesting] is not bound in this Context. Unable to find [jdbc].
Here is stacktrace:
javax.naming.NameNotFoundException: Name [jdbc/bbytesting] is not bound in this Context. Unable to find [jdbc].
at org.apache.naming.NamingContext.lookup(NamingContext.java:818)
at org.apache.naming.NamingContext.lookup(NamingContext.java:166)
at org.apache.naming.SelectorContext.lookup(SelectorContext.java:157)
at javax.naming.InitialContext.lookup(InitialContext.java:417)
at com.youtube.dao.MySQL308tube.MySQL308tubeConn(MySQL308tube.java:31)
at com.youtube.rest.status.V1_status.returnDatabaseStatus(V1_status.java:61)
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 com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
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:502)
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:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
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)
Here are the steps I've performed up to this point:
Downloaded MySQL JDBC Driver and put in lib folder
JDBC Resource Configuration
<Context>
<Resource name="jdbc/bbytesting" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="username" password="password"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://awsurl:3306/bbytesting">
</Context>
Return database status code:
public String returnDatabaseStatus() throws Exception {
PreparedStatement query = null;
String myString = null;
String returnString = null;
Connection conn = null;
try {
conn = MySQL308tube.MySQL308tubeConn().getConnection();
query = conn.prepareStatement("select to_char(sysdate, 'YYYY-MM-DD HH24:MI:SS') DATETIME " + "from sys.dual");
ResultSet rs = query.executeQuery();
while (rs.next()) {
myString = rs.getString("DATETIME");
}
query.close();
returnString = "<p>Database Status</p> "
+ "<Database Date/Time return: " + myString + "</p>";
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (conn != null) conn.close();
}
return returnString;
}
Here is connection class code:
public class MySQL308tube {
private static DataSource MySQL308tube = null;
private static Context context = null;
public static DataSource MySQL308tubeConn() throws Exception {
if(MySQL308tube != null) {
return MySQL308tube;
}
try {
if (context == null) {
context = new InitialContext();
}
MySQL308tube = (DataSource) context.lookup("jdbc/bbytesting");
}
catch (Exception e) {
e.printStackTrace();
}
return MySQL308tube;
}
}
The exception explains it perfectly: That's why you should never, ever have empty catch blocks.
Your JNDI data source lookup is failing. You need to prepend it with "java:/comp/env", like these Tomcat docs tell you to:
https://tomcat.apache.org/tomcat-7.0-doc/jndi-datasource-examples-howto.html
You are using awsurl in the connection URL which needs extra permissions for the user. If your application and database runs on the same server, refer by localhost or 127.0.0.1.
If you would need to make your application access this server by awsurl, go to mysql prompt as mysql root user and execute GRANT:
For global access.
GRANT ALL ON bbytesting.* TO '<user>'#'%' IDENTIFIED BY '<password>'
For access from particular IP address (possibly IP of server where you run your application)
GRANT ALL ON bbytesting.* TO '<user>'#'<ip_address>' IDENTIFIED BY '<password>'
Also, I recommend you to test accessing database from the server you run your application using command:
mysql -u user_name -ppassword -h db_server_ip
No space between switch -p and password
You may need to install mysql-client package to run mysql command.
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()).