I want to upload an image using struts2 using the function copyFile()
but when i use ServletRequestAware not supported yet exception is thrown. please help me to solve this problem.
here is my code
index.jsp
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<s:form action="uploadAction.action" method="post" enctype="multipart/form-data">>
<s:textfield label="caption" name="caption"/>
<input type="file" name="userImage"/>
<s:submit name="submit" label="Submit"/>
</s:form>
</body>
</html>
uploadFile.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="attribute" extends="struts-default">
<action name="uploadAction" class="com.scrolls.fileupload.action.UploadImageAction" method="uploadImage">
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">ImageUploadSuccess.jsp</result>
<result name="input">index.jsp</result>
</action>
</package>
</struts>
UploadImageAction.java
package com.scrolls.fileupload.action;
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
public class UploadImageAction extends ActionSupport implements ServletRequestAware {
private File userImage;
private String userImageContentType;
private String caption;
private HttpServletRequest servletRequest;
public String uploadImage() {
try {
HttpSession session = servletRequest.getSession();
ServletContext context = session.getServletContext();
String filePath = context.getRealPath("/");
System.out.println("Server path:" + filePath);
File fileToCreate = new File(filePath, this.caption);
FileUtils.copyFile(this.userImage, fileToCreate);
}
catch (Exception e) {
System.out.println(e);
return INPUT;
}
return SUCCESS;
}
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
throw new UnsupportedOperationException("Not supported yet.");
}
}
ImageUploadSuccess.jsp
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<h2>Struts2 Image Upload</h2>
<b>Image Uploaded To Folder :</b><s:property value="userImage"/>
<br/>
<b>Content Type:</b> <s:property value="userImageContentType"/>
<br/>
<b>Uploaded Image Name:</b> <s:property value="caption"/>
<br/>
<b>Uploaded Image Preview :</b>
<br/>
<img src="<s:property value="userImageFileName"/>"/>
</body>
</html>
Exception:
SEVERE: Servlet.service() for servlet [default] in context with path [/fileupload] threw exception [java.lang.UnsupportedOperationException: Not supported yet.] with root cause
java.lang.UnsupportedOperationException: Not supported yet.
at com.scrolls.fileupload.action.UploadImageAction.setServletRequest(UploadImageAction.java:81)
at org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:131)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:123)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:268)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
at com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
at com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
at com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
at org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:50)
at org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:504)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:929)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:405)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:964)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:515)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
... You're throwing that exception, precisely where the stack trace tells you you are.
Are you unaware of Java stack traces? Are you unable to read the information it provides?
It's pointing to your code.
First of all defaultStack already includes fileUpload interceptor so you have to configure that interceptor instead of adding it twice to your action interceptors stack.
<action name="uploadAction" class="com.scrolls.fileupload.action.UploadImageAction" method="uploadImage">
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">2097152</param>
<param name="fileUpload.allowedTypes">
image/png,image/gif,image/jpeg,image/pjpeg
</param>
</interceptor-ref>
<result name="success">ImageUploadSuccess.jsp</result>
<result name="input">index.jsp</result>
</action>
Second: in Struts2 you do not need to read submitted file from request. Read about file upload http://struts.apache.org/2.x/docs/file-upload.html.
You can try download example project from this link.
http://javapostsforlearning.blogspot.com/2012/07/file-upload-in-struts-2.html
I have tried it already, it works.(thanks to the tutorial creator)
Related
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 am trying to create a paginated table in Struts 2 using DisplayTag and I can´t make it work.
I have created the following files:
Class's name Profesores.java:
package org.apache.struts.registro.model;
public class Profesores {
private String nombre;
private String nacionalidad;
private String formacion;
private String aniosExperiencia;
private String clasesDomicilio;
private String clasesOnline;
private String correoElectronico;
private String correoElectronicoSeguridad;
private String movil;
private String tituloAnuncio;
private String descripcionAnuncio;
private long precio;
public Profesores(){
}
public Profesores(String nombre,String nacionalidad,String tituloAnuncio){
this.nombre = nombre;
this.nacionalidad = nacionalidad;
this.tituloAnuncio = tituloAnuncio;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getNacionalidad() {
return nacionalidad;
}
public void setNacionalidad(String nacionalidad) {
this.nacionalidad = nacionalidad;
}
public String getFormacion() {
return formacion;
}
public void setFormacion(String formacion) {
this.formacion = formacion;
}
public String getClasesDomicilio() {
return clasesDomicilio;
}
public void setClasesDomicilio(String clasesDomicilio) {
this.clasesDomicilio = clasesDomicilio;
}
public String getClasesOnline() {
return clasesOnline;
}
public void setClasesOnline(String clasesOnline) {
this.clasesOnline = clasesOnline;
}
public String getCorreoElectronico() {
return correoElectronico;
}
public void setCorreoElectronico(String correoElectronico) {
this.correoElectronico = correoElectronico;
}
public String getMovil() {
return movil;
}
public void setMovil(String movil) {
this.movil = movil;
}
public String getTituloAnuncio() {
return tituloAnuncio;
}
public void setTituloAnuncio(String tituloAnuncio) {
this.tituloAnuncio = tituloAnuncio;
}
public String getDescripcionAnuncio() {
return descripcionAnuncio;
}
public void setDescripcionAnuncio(String descripcionAnuncio) {
this.descripcionAnuncio = descripcionAnuncio;
}
public long getPrecio() {
return precio;
}
public void setPrecio(long precio) {
this.precio = precio;
}
public String getCorreoElectronicoSeguridad() {
return correoElectronicoSeguridad;
}
public void setCorreoElectronicoSeguridad(String correoElectronicoSeguridad) {
this.correoElectronicoSeguridad = correoElectronicoSeguridad;
}
public String getAniosExperiencia() {
return aniosExperiencia;
}
public void setAniosExperiencia(String aniosExperiencia) {
this.aniosExperiencia = aniosExperiencia;
}
}
Action's name: ProfesoresAction
package org.apache.struts.registro.action;
import java.util.ArrayList;
import java.util.List;
import org.apache.struts.registro.model.Profesores;
import com.opensymphony.xwork2.ActionSupport;
public class ProfesoresAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private List <Profesores> listaAnunciosProfesores = new ArrayList<Profesores>();
public String execute() throws Exception {
listaAnunciosProfesores.add(new Profesores("Johny","1","B.Tech"));
listaAnunciosProfesores.add(new Profesores("Lourde","2","M.Tech"));
listaAnunciosProfesores.add(new Profesores("Mark Boucher","3","B.Tech"));
listaAnunciosProfesores.add(new Profesores("Sandy","4","B.Tech"));
listaAnunciosProfesores.add(new Profesores("Teena","5","MCA"));
listaAnunciosProfesores.add(new Profesores("Michal Bevan","6","M.Tech"));
listaAnunciosProfesores.add(new Profesores("Saranya","7","MCA"));
listaAnunciosProfesores.add(new Profesores("Rahamat","8","B.Tech"));
listaAnunciosProfesores.add(new Profesores("Rahul","9","M.Tech"));
listaAnunciosProfesores.add(new Profesores("Sugan","10","B.Tech"));
setListaAnunciosProfesores(listaAnunciosProfesores);
return SUCCESS;
}
public List<Profesores> getListaAnunciosProfesores() {
return listaAnunciosProfesores;
}
public void setListaAnunciosProfesores(List<Profesores> listaAnunciosProfesores) {
this.listaAnunciosProfesores = listaAnunciosProfesores;
}
}
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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="basicstruts2" extends="struts-default">
<!-- If no class attribute is specified the framework will assume success and
render the result index.jsp -->
<!-- If no name value for the result node is specified the success value is the default -->
<action name="index">
<result>/index.jsp</result>
</action>
<!-- If the URL is hello.action the call the execute method of class HelloWorldAction.
If the result returned by the execute method is success render the HelloWorld.jsp -->
<action name="hello" class="org.apache.struts.helloworld.action.HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
<action name="register" class="org.apache.struts.registro.action.Register" method="execute">
<result name="success">/thankyou.jsp</result>
<result name="input">/register.jsp</result>
</action>
<action name="registroProfesores" class="org.apache.struts.registro.action.RegistroProfesores" method="execute">
<result name="success">/thankyou.jsp</result>
<result name="input">/registroProfesores.jsp</result>
</action>
<action name="listaProfesores" class="org.apache.struts.registro.action.ProfesoresAction" method="execute">
<result name="success">/ListaProfesores.jsp</result>
</action>
</package>
</struts>
jsp's name: ListaProfesores.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://displaytag.sf.net" prefix="display" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<!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>
<display:table name="listaAnunciosProfesores" requestURI="listaProfesores" pagesize="2" export="false">
<display:column property="nombre" title="Roll" paramId="nombre" sortable="true"/>
<display:column property="nacionalidad" title="Name" sortable="true"/>
<display:column property="tituloAnuncio" title="Course" sortable="true" />
</display:table>
</body>
</html>
I'm facing this error:
may 04, 2013 10:00:12 PM org.apache.jasper.compiler.TldLocationsCache tldScanJar
INFO: Al menos un JAR, que se ha explorado buscando TLDs, aún no contenía TLDs. Activar historial de depuración para este historiador para una completa lista de los JARs que fueron explorados y de los que nos se halló TLDs. Saltarse JARs no necesarios durante la exploración puede dar lugar a una mejora de tiempo significativa en el arranque y compilación de JSP .
may 04, 2013 10:00:12 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: El Servlet.service() para el servlet [jsp] en el contexto con ruta [/Form_Validation_Struts2_Ant] lanzó la excepción [java.lang.NoClassDefFoundError: org/apache/commons/lang/UnhandledException] con causa raíz
java.lang.ClassNotFoundException: org.apache.commons.lang.UnhandledException
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1711)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1556)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.beans.finder.InstanceFinder.instantiate(Unknown Source)
at com.sun.beans.finder.InstanceFinder.find(Unknown Source)
at java.beans.Introspector.findExplicitBeanInfo(Unknown Source)
at java.beans.Introspector.<init>(Unknown Source)
at java.beans.Introspector.getBeanInfo(Unknown Source)
at org.apache.jasper.compiler.Generator$TagHandlerInfo.<init>(Generator.java:3943)
at org.apache.jasper.compiler.Generator$GenerateVisitor.getTagHandlerInfo(Generator.java:2209)
at org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1640)
at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1539)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2428)
at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2434)
at org.apache.jasper.compiler.Node$Root.accept(Node.java:475)
at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2376)
at org.apache.jasper.compiler.Generator.generate(Generator.java:3489)
at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:250)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:373)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:88)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:999)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:565)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Please, could anyone help me?
Check if you have common-lang.jar of version 2.3 (as written by your link here: http://displaytag.sourceforge.net/11/displaytag/dependencies.html) otherwise browse if the jar has this class. If there is no class org.apache.commons.lang.UnhandledException in this jar you should download recommended version (http://commons.apache.org/proper/commons-lang/).
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.
I have written an interceptor to prevent caching but the pages still cache.
Interceptor:
public class ClearCacheInterceptor implements Interceptor {
public String intercept(ActionInvocation invocation)throws Exception{
String result = invocation.invoke();
ActionContext context = (ActionContext) invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
HttpServletResponse response=(HttpServletResponse) context.get(StrutsStatics.HTTP_RESPONSE);
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
return result;
}
public void destroy() {}
public void init() {}
}
Struts.xml
<struts>
<constant name="struts.devMode" value="true"/>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<package name="default" extends="struts-default">
<interceptors>
<interceptor name="caching" class="com.struts.device.interceptor.ClearCacheInterceptor"/>
<interceptor-stack name="cachingStack">
<interceptor-ref name="caching" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
</interceptors>
<action name="Login" class="struts.device.example.LogIn">
<interceptor-ref name="cachingStack"/>
<result>example/Add.jsp</result>
<result name="error">example/Login.jsp</result>
</action>
</package>
</struts>
Application works fine; it executes interceptor but it doesn't prevent caching.
I have solved my problem. Thanks to developer tools for helping me to trace out.
A slight sequence change in my code helped me out: as per the Struts 2 interceptor docs the result is rendered before invocation.invoke() returns. Setting the headers before the result is rendered back to the client sets the headers in the returned result.
i.e.,
public String intercept(ActionInvocation invocation)throws Exception{
HttpServletResponse response = ServletActionContext.getResponse();
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
return invocation.invoke();
}
I am working on Struts2 Interceptors .
I have read that Struts2 Interceptors are just like Filters , which execute before the Action class is executed and one more time after processing the result ( Please correct me if i am wrong ) , that is two times
But when i ran the below code , the interceptors are executed only once .
Please correct me if i made any mistake .
Please see my code below :
This is My Struts.xml file
<struts>
<constant name="struts.devMode" value="true" />
<package name="test" extends="struts-default">
<interceptors>
<interceptor name="loginkiran" class="vaannila.MyLoginInterCeptor" />
</interceptors>
<action name="HelloWorld" class="vaannila.HelloWorld" method="kiran">
<interceptor-ref name="loginkiran" />
<result name="SUCCESS">/success.jsp</result>
</action>
</package>
</struts>
This is my Action class
public class HelloWorld
{
public HelloWorld() {
}
public String kiran() {
System.out.println("iNSIDE THE aCTION CLASS");
return "SUCCESS";
}
}
This is my Interceptor class
public class MyLoginInterCeptor implements Interceptor {
#Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("Destroying Interceptor");
}
#Override
public void init() {
}
#Override
public String intercept(ActionInvocation invocation) throws Exception {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
System.out.println("iNSIDE THE iNTERCEPTOR");
return invocation.invoke();
}
}
This is my JSP File :
<html>
<body>
<%
System.out.println("iNSIde THE jsp");
%>
</body>
</html>
The Output for the above code is this :
iNSIDE THE iNTERCEPTOR
iNSIDE THE aCTION CLASS
iNSIde THE jsp
Interceptors are not executed twice (nor are filters): interceptors (and filters) wrap the action (or servlet/etc.)
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("Before action invocation...");
return invocation.invoke();
System.out.println("After action invocation...");
}