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.
Related
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");
}
}
}
I am trying to learn Struts2, I have used a view page that hits action , the action class is using a bean where getter setter methods are written and the action is also using a dao where the connection is written.I want to mention that I am using jboss v5.0 and eclipse, I have added all the jar files.
Now , when I am trying to run this application the welcome jsp page is hitting properly then on clicking submit button the below error is showing:
There is no Action mapped for namespace /controller and action name
I am placing my code and directory structure. I have tried the using namespace="/"
<result name="SUCCESS">/success.jsp</result>, still its is not working
passing
+JAX-WS Web Services
+Deployment Descriptor:Passing
-Java Resources
-src
-controller
-TestAction.java
-TestAction
-execute(HttpServletRequest request , HttpServletResponse response) : String
-model
-TestBean.java
-TestBean
-age
-ocation
-name
-getAge() :String
-getName() :String
-getLocation() :String
-setAge(String) : void
-setName(String) : void
-getlocation(String) : void
-UserDao.java
- UserDao
-Logincheck() :Connection
registration.jsp
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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Passing</display-name>
<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>
</filter-mapping>
<welcome-file-list>
<welcome-file>registration.jsp</welcome-file>
</welcome-file-list>
</web-app>
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="default" extends="sturts-default">
<action name="TestAction" class="controller.TestAction">
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>
success.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center> Welcome, Data successfully inserted</center>
</body>
</html>
registration.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%# taglib uri="/struts-tags" prefix="s"/%>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="TestAction" method="post" >
<s:textfield name="Name" label="Name"/>
<s:textfield name="Age" label="Age"/>
<s:textfield name="Location" label="Location"/>
<s:submit label="Submit"></s:submit>
</s:form>
</body>
</html>
TestAction.java
package controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import com.opensymphony.xwork2.ActionSupport;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.TestBean;
import model.UserDao;
import org.apache.struts2.ServletActionContext;
public class TestAction extends ActionSupport{
public String execute(HttpServletRequest request , HttpServletResponse response) throws Exception
{
String Name = request.getParameter("Name");
String Age = request.getParameter("Age");
String Location = request.getParameter("Location");
TestBean bean = new TestBean();
bean.setName(Name);
bean.setAge(Age);
bean.setLocation(Location);
UserDao obj = new UserDao();
Connection x= obj.Logincheck();
if(x!=null)
{
PreparedStatement ps= x.prepareStatement("insert into Registration values(?,?,?)");
ps.setString(1, bean.getName());
ps.setString(2, bean.getAge());
ps.setString(3, bean.getLocation());
int i = ps.executeUpdate();
System.out.println("The value of i =" +i);
if(i>0)
{
return SUCCESS;
}
}
return null;
}
}
TestBean.java
package model;
public class TestBean {
String name;
String age;
String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}
UserDao.java
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class UserDao {
public Connection Logincheck()
{
Connection con=null;
try
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
con= DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "username", "password");
if(con!=null)
{
return con;
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
that's all.
This error
There is no Action mapped for namespace /controller and action name
generally means Struts can't find the action specified in a namespace specified (/controller in this case). BTW in your case you've not specified /controller anywhere and the action name is missing in the error message, so this error could be probably generated by the bunch of other errors you have in your action / JSP / configuration.
you also have two typos, preventing anything to work:
sturts-default instead of struts-default:
<package name="default" extends="struts-default">
"SUCCESS" instead of "success", that is the result mapped to the constant SUCCESS that you are returning from the Action method.
<result name="success">/success.jsp</result>
If using Struts version newer than or equals to 2.1.3, you need the new filter, StrutsPrepareAndExecuteFilter instead of the deprecated FilterDispatcher;
The action method must be a public String something() with no parameters. This:
public String execute(HttpServletRequest request , HttpServletResponse response) throws Exception
is simply wrong, and should be:
public String execute(){}
Here
String Name = request.getParameter("Name");
String Age = request.getParameter("Age");
String Location = request.getParameter("Location");
TestBean bean = new TestBean();
bean.setName(Name);
bean.setAge(Age);
bean.setLocation(Location);
you are reinventing the wheel really badly. Attributes must be private, at class level, with getters and setters, and they'll be populated automatically, with no need to access the request. In your case:
private TestBean bean;
/* GETTER AND SETTER */
public String execute(){
System.out.println(bean.getName());
// ...
}
Unrelated, but Java naming conventions use lower-case names for local variables and instance properties.
In JSP page, you need to access the getter with a starting lowercase character:
<s:textfield name="Name" label="Name"/>
must be
<s:textfield name="name" label="Name"/>
and so the other fields. Also if you point to an object like TestBean, you need to do like this:
<s:textfield name="bean.name" label="Name"/>
This are the main problems... BTW consider start coding after having read a book, or some good tutorial. Starting in the dark like this is not the right way, IMHO.
Following are points which you should notice,
If you are using TestBean class as data carrier, you have to implement ModelDriven Interface.
TestAction.java should present in "Controller" package.
If you want HttpServletRequest and HttpServletResponse in your execute() method, then the simplest way you can get that is to implement ServletRequestAware and ServletResponseAware interfaces and implement respective methods.
And most important if your success.jsp is in Web Content folder, then you dont need to specify
<result name="SUCCESS">/success.jsp</result>
Just make it like
<result name="SUCCESS">success.jsp</result>
And if you have any folder suppose, "Folder1" in Web Content, Then specify like
<result name="SUCCESS">Folder1/success.jsp</result>
Registration.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center>
<%# taglib uri="/struts-tags" prefix="s"%>
<s:form action="getRegistered.action" method="post" validate="true">
<div>
<table>
<s:textfield label="First Name" key="firstname" />
<s:textfield label="Last Name" key="lastname" />
<s:password label="Create your password" key="regpassword" />
<s:password label="Confirm your password" key="conpassword" />
<s:textfield label="Email" key="regemail1" />
<s:textfield label="Re-Type Email" key="conemail" />
<s:textfield label="Phone" key="phone" />
<tr>
<td><s:submit value="Register" theme="simple"/></td>
<td><s:submit value="Cancel" theme="simple" onclick="document.forms[0].action='login.jsp';" /></td>
</tr>
</table>
</div>
</s:form>
</center>
</body>
</html>
I'm passing the register input values to Action class.
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="default" extends="struts-default">
<action name="getLogin" class="login.action.LoginAction"
method="login">
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
<action name="getRegistered" class="login.action.LoginAction"
method="register">
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
This is the struts xml
LoginAction.java:
package login.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import login.service.LoginDao;
import login.service.RegisterDao;
#SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
private String username;
private String password;
private HttpServletRequest httpServletRequest;
private String firstname;
private String lastname;
private String regpassword;
private String conpassword;
private String regemail;
private String conemail;
private String phone;
public String register(){
RegisterDao rdao = new RegisterDao();
System.out.println("firstname action::: "+firstname);
rdao.registerdao(firstname,lastname,regpassword,conpassword,regemail,conemail,phone);
return SUCCESS;
}
public String login() {
httpServletRequest.getSession().setAttribute("key", username);
httpServletRequest.getSession().setAttribute("key", password);
LoginDao db = new LoginDao();
Boolean validate = db.loginresult(username, password);
if (validate == true) {
return SUCCESS;
} else {
return INPUT;
}
}
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getRegpassword() {
return regpassword;
}
public void setRegpassword(String regpassword) {
this.regpassword = regpassword;
}
public String getConpassword() {
return conpassword;
}
public void setConpassword(String conpassword) {
this.conpassword = conpassword;
}
public String getRegemail() {
return regemail;
}
public void setRegemail(String regemail) {
this.regemail = regemail;
}
public String getConemail() {
return conemail;
}
public void setConemail(String conemail) {
this.conemail = conemail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setServletRequest(HttpServletRequest request) {
this.httpServletRequest = request;
}
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;
}
#Override
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
}
}
When i submit the registration form , the input values pass to Action class is null. How can i access the registration values in action class under register() method.
The above issue is resolved .
Now i'm facing another strange issue .. When i submit the form action = getLogin.action , its always returning INPUT from the interceptor . I dont wish to exclude the method login from the validator.
How could i resolve it ?
When i change the struts xml like below , its redirecting to success jsp . But i dont want to exclude the login method from validation
<action name="getLogin" class="login.action.LoginAction"
method="login">
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">login</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
You are using only one Interceptor, you need to use the whole Stack:
Change this:
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
to this
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">register</param>
</interceptor-ref>
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 ...............
I am new to Struts2. I was trying to execute a simple Struts2 program.
Apparently my struts.xml is not invoking the action.
It shows a warning Server returned http response code 407 for url: "http://struts.apache.org/dtds/struts-2.1.7.dtd in my struts.xml.
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="hello" class="com.FirstStruts.ExampleStruts" method="execute">
<result name="success">/Helloworld.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>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
Action:
package com.FirstStruts;
public class ExampleStruts {
private String f_name;
private String l_name;
public String execute() throws Exception {
System.out.println("Hello. in execeute");
return "success";
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
}
When I try to execute, I am getting the error There is no Action mapped for namespace / and action name ExampleStruts.
I am using the jars mentioned in http://www.nabisoft.com/tutorials/struts2/basic-struts2-project-setup
Could you please help me with it?
Your action is called hello, no ExampleStruts, so it won't find it. Change your struts.xml file:
<action name="ExampleStruts" class="com.FirstStruts.ExampleStruts">
<result>/Helloworld.jsp</result>
</action>
or invoke the action correctly in your index.jsp.
Also, you need to extend your action from ActionSupport, so it will be recognized as an action.