Upgrading the project from struts 1 to struts 2 - struts2

I have recently upgraded my code from Struts 1 to Struts 2 and the app is not working after deploying it in my test environment (Linux box). The test env has 3 server instances with different url for each instance. I have deployed my new code(Struts 2) in instance#2 and instance#1 and #3 has old code(Struts 1)
The problem is once i login to the url's of Instance 1 and 3, I am successfully able to login to Instance #2.
But when I login to Instance #2 url directly, struts 2 action is not being invoked and stays in login page itself
web.xml
<!-- Note how the Application Security Team's security filter is listed
FIRST! -->
<filter-name>AppSecSecurityFilter</filter-name>
<filter-class>com.qwest.appsec.TomcatSecurityFilter</filter-class>
<!-- Required. The name for this application -->
<init-param>
<param-name>applicationName</param-name>
<param-value>NATE</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AppSecSecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/does_not_exist_jaasinit.html</form-login-page>
<form-error-page>/appsec/access_denied_en.html</form-error-page>
</form-login-config>
</login-config><filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping><session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
Struts.xml:
<struts><package name="loginPackage" namespace="/" extends="struts-default">
<action name="nateLoginAction" class="com.wireless.nate.actions.LoginAction">
<result name="success">creditNate.jsp</result>
<result name="error">login.jsp </result>
<result name="input">login.jsp</result>
</action>
</package></struts>
LoginAction.java
public class LoginAction extends ActionSupport implements
ServletRequestAware,ServletResponseAware
{
private static final long serialVersionUID = -3510995405804328464L;
private Logger logger = Logger.getLogger(this.getClass());
HttpServletRequest request;
HttpServletResponse response;
LoginActionForm loginActionForm;
ActionContext context;
ActionSupport actionSupport;
public LoginActionForm getLoginActionForm() {
return loginActionForm;
}
public void setLoginActionForm(LoginActionForm loginActionForm) {
this.loginActionForm = loginActionForm;
}
#Override
public void setServletResponse(HttpServletResponse response) {
this.response=response;
}
#Override
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
public String execute() throws Exception
{
System.out.println("inside action execute method");
logger.debug("+execute()");
ValueStack stack = context.getValueStack();
Map<String, Object> context = new HashMap<String, Object>();
// Get the html form fields from the cookies
String salesCode = "";
String loginUserId = "";
javax.servlet.http.Cookie[] cookies = request.getCookies();
javax.servlet.http.Cookie thisCookie = null;
if (null != cookies)
{
for (int i = 0; i < cookies.length; i++)
{
thisCookie = cookies[i];
logger.debug("request.getCookies():");
logger.debug(" cookies[" + i + "].getName()=" + cookies[i].getName());
logger.debug(" cookies[" + i + "].getValue()=" + cookies[i].getValue());
if (thisCookie.getName().equals("salesCode"))
{
salesCode = cookies[i].getValue();
}
else if (thisCookie.getName().equals("user"))
{
loginUserId = cookies[i].getValue();
}
}
}
loginActionForm.setSalesCode(salesCode.toUpperCase());
loginActionForm.setUser(loginUserId);
context.put("loginActionForm", loginActionForm);
stack.push(context);
return SUCCESS;
}
public void validate(){
System.out.println("inside action validate method");
context = ActionContext.getContext();
actionSupport=(ActionSupport)context.getActionInvocation().getAction();
if(loginActionForm.getUser() == null || loginActionForm.getUser().length() == 0){
addFieldError("user.required","User name is required");
}
if(loginActionForm.getPassword() == null || loginActionForm.getPassword().length() ==0){
addFieldError("password.required","Password is required");
}
}
}

Related

Swagger interacting with Resteasy not listing content api

We're trying to have Swagger interact with our resteasy app so that the api will list out on the swagger page. We're using annotations in the Java resources and not a yaml/json file. We want the content to be 'dynamic' or come directly from the resource pages.
When we bring up the swagger page, we get the message 'fetching resource list: //10.155.63.136/nodeMgmt'. When I render the page using firebug, I see that the page itself (index.html) is being 'fed in' to the content.
I think I'm pretty close but am missing one or two small things. I used the example as a guide to what I did: https://github.com/mrj365/RestEasy-3.09-Spring-3.2.5-Swagger2.0
Again, the issue is that the content from the resteasy api is not being fed into the swagger ui. The url in my case is https://10.155.63.92/nodeMgmt/index.html
We're using JBoss 6.4, NO Spring, Resteasy 3.0.7, Swagger jaxrs 1.5.9.
Any help is really appreciated.
Index.html
<script type="text/javascript">
$(function () {
window.swaggerUi = new SwaggerUi({
url: "/nodeMgmt",
dom_id: "swagger-ui-container",
supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
onComplete: function(swaggerApi, swaggerUi){
log("Loaded SwaggerUI");
$('pre code').each(function(i, e) {
hljs.highlightBlock(e)
});
},
onFailure: function(data) {
log("Unable to Load SwaggerUI");
},
docExpansion: "none"
});
web.xml
<!-- Auto scan REST service -->
<context-param>
<param-name>resteasy.scan</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>resteasy.servlet.mapping.prefix</param-name>
<param-value>/nodes</param-value>
</context-param>
<filter>
<filter-name>ApiOriginFilter</filter-name>
<filter-class>com.sonus.unity.sonusbaserestservice.utils.ApiOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ApiOriginFilter</filter-name>
<url-pattern>/index.html</url-pattern>
</filter-mapping>
<!-- if you are using Spring, Seam or EJB as your component model, remove the ResourceMethodSecurityInterceptor -->
<context-param>
<param-name>resteasy.resource.method-interceptors</param-name>
<param-value>
org.jboss.resteasy.core.ResourceMethodSecurityInterceptor
</param-value>
</context-param>
<listener>
<listener-class>org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
</listener>
<servlet>
<servlet-name>Resteasy</servlet-name>
<servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.sonus.ems.nodemgmt.web.NodeMgmtApplication</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Resteasy</servlet-name>
<url-pattern>/nodes/*</url-pattern>
</servlet-mapping>
application.java
#ApplicationPath("")
public class NodeMgmtApplication extends SonusBaseRestApplication {
private static final Logger log = Logger.getLogger(NodeMgmtApplication.class);
/**
* Constructor
*/
public NodeMgmtApplication() {
super();
try {
//TODO Swagger
// Used for defining swagger
BeanConfig beanConfig = new BeanConfig();
beanConfig.setSchemes(new String[]{"http"});
beanConfig.setHost("localhost:8080");
beanConfig.setVersion("1.5.9");
beanConfig.setBasePath("/nodeMgmt");
beanConfig.setResourcePackage("com.sonus.ems.nodemgmt.web");
//beanConfig.setPrettyPrint(true);
beanConfig.setScan(true);
addService(new NodeMgmtAuthorizationFilter());
addService(new NodeMgmtRestService());
// Swagger
addService(new ApiListingResource());
addService(new SwaggerSerializers());
} catch (Exception e) {
log.error("NodeAdminApplication: Could not instantiate singletons " + e);
}
}
resource.java
#Path("/")
#Api(value = "/", description = "Node operations", produces = MediaType.APPLICATION_JSON, consumes = MediaType.APPLICATION_JSON)
public class NodeMgmtRestService {
private static final Logger log = Logger.getLogger(NodeMgmtRestService.class);
private static final String NODES = "nodes";
private static final String ID = "id";
NodeMgmtServiceProvider nodeMgmtServiceProvider = new NodeMgmtServiceProvider();
Service nodeMgmtService;
#GET
#Path("/{version}")
#Produces(MediaType.APPLICATION_JSON)
#ApiOperation(value = "Get all nodes", notes = "Returns a list of node", response = String.class, responseContainer="List")
public Response getNodes(
#ApiParam(value = "Version of api (1.0)", required = true) #PathParam("version") String version,
#ApiParam(value = "Filter by ", required = true) #QueryParam("filterParam") String filterParam,
#ApiParam(value = "Filter value ", required = true) #QueryParam("filterValue") String filterValue) {
List<Node> nodeList = new ArrayList<Node>();
List<Object> nodeJsonList = new ArrayList<Object>();
Map<String, List<Object>> nodeJsonMap = new HashMap<String, List<Object>>();
ObjectMapper objectMapper = new ObjectMapper();
Map<String, String> responseId = new HashMap<String, String>();
JsonNodeDao jsonNodeDao = new JsonNodeDao();
Swagger API key
public class ApiOriginFilter implements Filter {
#Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
// Add access to the header
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, OPTIONS");
res.addHeader("Access-Control-Allow-Headers", "Content-Type, api_key, Authorization");
//res.addHeader("Access-Control-Allow-Headers", "Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, api_key, Authorization, X-Atmosphere-Transport, x-requested-with, Total-Count, Total-Pages, Error-Message, *");
//res.addHeader("Access-Control-Request-Headers", "Origin, X-Atmosphere-tracking-id, X-Atmosphere-Framework, X-Cache-Date, Content-Type, api_key, Authorization, X-Atmosphere-Transport, x-requested-with, Total-Count, Total-Pages, Error-Message, *");
chain.doFilter(request, response);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}

How to call struts action from doFilter method

My struts.xml has two actions as follows
<action name="dologincheck" class="com.platinum.uac.biz.LoginAction" method="doLogin">
<result name="success" type="tiles">Homepage</result>
<!-- <result name="success">/Profile/view/ViewProfile1.jsp</result>-->
<result name="none">/Profile/add/Failure.jsp</result>
<result name="mail">/Profile/add/EmailAuthentication.jsp</result>
</action>
<action name="newuseraction" class="com.platinum.uac.biz.NewUserAction" method="newuser">
<result name="success" >/Profile/add/ProfileDetails.jsp</result>
<result name="error" >/index.jsp</result>
</action>
I need to call an action(dologincheck) from doFilter method. I am stuck here because I do not know how to call an action from doFilter method
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws
IOException, ServletException {
try {
System.out.println("this is do filter before the jsp page");
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = ((HttpServletResponse) res);
HttpSession session = request.getSession(true);
String username, password;
Cookie[] cookies;
LoginPojo user = (LoginPojo) session.getAttribute("username");
if (user == null) {
cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
username = getCookieValue(cookies, "username");
password = getCookieValue(cookies, "password");
System.out.println(username);
System.out.println(password);
if (username != null && password != null) {
LoginPojo pojo = new LoginPojo(username, password);
results = dao.Login(pojo);
session.setAttribute("userName", user); // usersession?
request.getRequestDispatcher("dologincheck").forward(request,
response);
} else {
request.getRequestDispatcher("/index.jsp").forward(request,
response);
}
} else {
request.getRequestDispatcher("/index.jsp").forward(request,
response);
}
}
} catch (Exception e) {
}
chain.doFilter(req, res);
//throw new UnsupportedOperationException("Not supported yet.");
}
My Filter part of web.xml is
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>AutomaticLogin</filter-name>
<filter-class>com.platinum.uac.biz.AutomaticLogin</filter-class>
</filter>
<filter-mapping>
<filter-name>AutomaticLogin</filter-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.action</url-pattern>
<servlet-name>action</servlet-name>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
After searching in net I got the answer.
Use
response.sendRedirect("dologincheck");
instead of
request.getRequestDispatcher("dologincheck").forward(request, response);

Web application load failed

I'm using Netbeans 7.2.1 and GlassFish 3.1.
I created web application using JSF, ejb classes and JDBC data source.
xhtml pages reference backing managed beans, which call local interface functions on ejb classes which run queries through the data source, directly getting connection and executing queries.
The project builds successfully, but when I run the project, browser shows error "No data received", and browser tab title says failed to load. I think maybe I have some missing configurations, cause when I run same project with no reference to managed beans (and hence not to ejb's and database) , there's no such message.
Frankly I got lost in what configuration files are needed for such a project, and what is needed to configure there. I saw numerous explanations, each saying something else, and I'm not clear which one is relevant here. If you could point me to some clear relevant explanation, I'd be grateful.
Do I need to configure for this project somewhere data source? ejb classes? anything else?
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
beans.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
index.xhtml :
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Movie Tickets Order </title>
</h:head>
<h:body>
<h:panelGrid columns="2" rendered="#{!UserBean.loggedIn}">
<h:outputLabel for="username" value="Username:"></h:outputLabel>
<h:inputText id="username" value="#{UserBean.username}"/>
<h:outputLabel for="password" value="Password: "></h:outputLabel>
<h:inputSecret id="password" value="#{UserBean.password}"/>
</h:panelGrid>
<h:commandButton value="Login" action="#{UserBean.login}" rendered="#{!UserBean.loggedIn}"/>
<h:commandButton value="Logout" action="#{UserBean.logout}" rendered="#{UserBean.loggedIn}"/>
<h:outputLink value="EditMovie" rendered="#{UserBean.isAdmin}"> Add/Edit Movie </h:outputLink>
</h:body>
UserBean
import TicketsEJB.UserejbLocal;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
#Named(value = "UserBean")
#SessionScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 20130908L;
private String username;
private String password;
private String status;
private boolean exist = false;
private boolean loggedIn = false;
private final String statusAdmin = "admin";
private final String statusUser = "user";
#EJB
UserejbLocal userejb;
public boolean isAdmin() {
return status.equals(statusAdmin);
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void login() {
status = userejb.getUser(username, password);
exist = (status == null) ? false : true;
if (exist) {
//render "Hello user"
if (status.equals(statusAdmin)) {
loggedIn=true;
//render admin part:
}
} else {
//render "Sorry, wrong credentials"
}
password = null;
}
....
Userejb class:
#Stateful
#Local(UserejbLocal.class)
public class Userejb implements UserejbLocal {
private Connection connection = null;
private PreparedStatement getUser = null;
private PreparedStatement addUser = null;
private PreparedStatement getUserSalt = null;
private boolean exist;
private String status;
#Resource( name = "jdbc/Movies")
DataSource dataSource;
#PostConstruct
#Override
public void prepareStatements() {
try {
if (dataSource == null) {
throw new SQLException("Unable to obtain DataSource");
}
connection = dataSource.getConnection();
if (connection == null) {
throw new SQLException("Unable to connect to DataSource");
}
try {
getUser = connection.prepareStatement(
"SELECT STATUS "
+ "FROM Users"
+ "WHERE NAMEU= ? and HASHP=?");
addUser = connection.prepareStatement(
"insert into Users values ('?','?','?','?')");
getUserSalt = connection.prepareStatement(
"SELECT SALTP "
+ "FROM Users"
+ "WHERE NAMEU= ? ");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.exit(1);
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.exit(1);
}
}
#Override
public void addUser(String name, String password, String status) {
String salt = Security.salt();
try {
addUser.setString(1, name);
addUser.setString(2, Security.hash(password + salt));
addUser.setString(3, salt);
addUser.setString(4, status);
addUser.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Userejb.class.getName()).log(Level.SEVERE, null, ex);
}
}
....
UserejbLocal interface :
public interface UserejbLocal {
void prepareStatements();
void addUser(String name, String password, String status);
public java.lang.String getUser(java.lang.String name, java.lang.String password);
}
Thanks for the help!
The problem was SQLSyntaxErrorException. Just needed to look at server log (output tab , glassfish server tab) to see what was the problem. Fixing SQL syntax rendered the page correctly.
You are missing a space between Users and WHERE in your query. This is causing the query to be parsed as:
SELECT STATUS FROM UsersWHERE NAMEU ...............

struts2 url rewrite action error

i got problem when using rewrite url mod
my problem is when using it, i move to login form for admincp
after enter username and password it appear HTTP 500 Status, but no stacktrace got in tomcat log???
my code
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="admincp" namespace="/admincp" extends="struts-default">
<interceptors>
<interceptor name="login" class="org.dejavu.software.interceptor.LoginInterceptor" />
<interceptor-stack name="stack-with-login">
<interceptor-ref name="login"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="stack-with-login"/>
<global-results>
<result name="login">login.jsp</result>
</global-results>
<action name="logincp" class="org.dejavu.software.view.AdminLoginAction">
<interceptor-ref name="defaultStack" />
<result name="success">dashboard.jsp</result>
<result name="input">login.jsp</result>
<result name="error">login.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>dejavuSoft</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>UrlRewriteFilter</filter-name>
<filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
<init-param>
<param-name>logLevel</param-name>
<param-value>WARN</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>UrlRewriteFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
</web-app>
Login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<title>Deja vu! | Login - Admin Control Panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/login.css" />
</head>
<body>
<img src="img/loginLogo.png" id="logo"/>
<s:actionerror/>
<s:form action="logincp">
<s:textfield name="username" value="username..." id="txtusername" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;"/>
<s:password name="password" value="password..." id="txtpassword" onfocus="if(this.value==this.defaultValue) this.value='';" onblur="if(this.value=='') this.value=this.defaultValue;"/><br/>
<s:submit value="Enter Admin Panel" id="btLogin"/>
</s:form>
<img src="img/dejavu.png" id="icon"/>
<div id="forget">
Forget Password | Forget Username
</div>
</body>
<footer>
Footer
</footer>
</html>
Login Action
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.dejavu.software.view;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.dejavu.software.dao.UserDAO;
import org.dejavu.software.model.GroupMember;
import org.dejavu.software.model.User;
/**
*
* #author Administrator
*/
public class AdminLoginAction extends ActionSupport {
private static final long serialVersionUID = -1457633455929689099L;
private User user;
private String username, password;
private String role;
private UserDAO userDAO;
private GroupMember group;
public AdminLoginAction() {
userDAO = new UserDAO();
}
#Override
public String execute() {
String result = null;
if (getUsername().length() != 0 && getPassword().length() != 0) {
setUser(userDAO.checkUsernamePassword(getUsername(), getPassword()));
if (getUser() != null) {
for (GroupMember g : getUser().getGroups()) {
boolean admincp = g.getAdminpermission().contains("1");
if (admincp == true) {
Map session = ActionContext.getContext().getSession();
session.put("userLogged", getUsername());
session.put("passwordLogged", getPassword());
result = "success";
} else {
result = "error";
}
}
}
}
return result;
}
#Override
public void validate() {
if (getUsername().length() == 0) {
addFieldError("username", "Username is required");
}
if (getPassword().length() == 0) {
addFieldError("password", getText("Password is required"));
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public GroupMember getGroup() {
return group;
}
public void setGroup(GroupMember group) {
this.group = group;
}
}
web error :
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)
com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:185)
org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:63)
org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39)
com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:501)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:432)
org.tuckey.web.filters.urlrewrite.NormalRewrittenUrl.doRewrite(NormalRewrittenUrl.java:213)
org.tuckey.web.filters.urlrewrite.RuleChain.handleRewrite(RuleChain.java:171)
org.tuckey.web.filters.urlrewrite.RuleChain.doRules(RuleChain.java:145)
org.tuckey.web.filters.urlrewrite.UrlRewriter.processRequest(UrlRewriter.java:92)
org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:394)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.22 logs.

JSF 2.0 + Spring Security 2.x

I using JSF 2.0 + Icefaces 2.0 and try to implement spring security 2.06 (not 3.x due to compatible problems with Icefaces 2.0).
I follow this guide (I think it is for JSF 1.x and Icefaces 1.8):
http://facestutorials.icefaces.org/tutorial/spring-security-basic.html
But I have problem to integrate the spring framework. I have added these lines to web.xml:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring Security -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Then I have a file, applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-2.0.2.xsd">
<security:http auto-config="true" access-denied-page="/pages/accessDenied.xhtml">
<security:intercept-url pattern="/secured/**" access="ROLE_ALLACCESS, ROLE_URLACCESS"/>
<security:form-login login-page="/pages/springSecurityLogin.xhtml"
default-target-url="/secured/welcome.xhtml"/>
<security:logout logout-success-url="/pages/logoutSuccess.xhtml"/>
</security:http>
<security:authentication-provider user-service-ref="userDetailsService"/>
<bean id="userDetailsService" class="security.UserDetailsServiceImpl">
<constructor-arg ref="userRepository"/>
</bean>
<bean id="userRepository" class="security.UserDaoImpl"/>
</beans>
The userDetailsService class is implemented according to:
package security;
import org.springframework.dao.DataAccessException;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.userdetails.UserDetails;
import org.springframework.security.userdetails.UserDetailsService;
import org.springframework.security.userdetails.UsernameNotFoundException;
public class UserDetailsServiceImpl implements UserDetailsService {
private UserDAO userDAO;
public UserDetailsServiceImpl(UserDAO userDAO) {
this.userDAO = userDAO;
}
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
AppUser user = userDAO.findUser(username);
if (user == null)
throw new UsernameNotFoundException("User not found: " + username);
else {
return makeUser(user);
}
}
private org.springframework.security.userdetails.User makeUser(AppUser user) {
return new org.springframework.security.userdetails.User(user.getLogin(), user
.getPassword(), true, true, true, true,
makeGrantedAuthorities(user));
}
private GrantedAuthority[] makeGrantedAuthorities(AppUser user) {
GrantedAuthority[] result = new GrantedAuthority[user.getRoles().size()];
int i = 0;
for (String role : user.getRoles()) {
result[i++] = new GrantedAuthorityImpl(role);
}
return result;
}
}
I also has a login bean:
package web.bean.security;
import org.springframework.security.ui.AbstractProcessingFilter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
#ManagedBean(name="login")
public class Login {
// properties
private String userId;
private String password;
/**
* default empty constructor
*/
public Login() {
Exception ex = (Exception) FacesContext
.getCurrentInstance()
.getExternalContext()
.getSessionMap()
.get(AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
if (ex != null)
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex
.getMessage(), ex.getMessage()));
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void login(ActionEvent e) throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("/spring-authentication/j_spring_security_check?j_username=" + userId + "&j_password=" + password);
}
}
The problem is when I running a jsf file which using the login bean:
The requested resource () is not available.
I'm using Tomcat 7.
Can you please help me?
Best Regards /kungcc
I think you need to add the webapplication name before the /j_spring_security_check
like /WebAppName/j_spring_security_check that will aply the spring on all what comes after /webAppName
Does omitting /spring-authentication in the login() method of login bean help?
public void login(ActionEvent e) throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect("/j_spring_security_check?j_username=" + userId + "&j_password=" + password);
}

Resources