开发者

Struts2 request as null

Very strange error I have, I am getting request as null when I try to access it. I always used the same method to get it, but now I am having this error.

My Action look like this:

package com.deveto.struts.actions;

import com.deveto.hibernate.mappings.Slider;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.util.ServletContextAware;


/**
 *
 * @author denis
 */
public class ContentAction extends ActionSupport implements ServletContextAware {

HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
ActionContext ac = ActionContext.getContext();
ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);

@Overri开发者_StackOverflowde
public String execute() throws Exception {

    System.out.println("request: " + request);

    return SUCCESS;
}

public ActionContext getAc() {
    return ac;
}

public void setAc(ActionContext ac) {
    this.ac = ac;
}

public HttpServletRequest getRequest() {
    return request;
}

public void setRequest(HttpServletRequest request) {
    this.request = request;
}

public HttpServletResponse getResponse() {
    return response;
}

public void setResponse(HttpServletResponse response) {
    this.response = response;
}

public ServletContext getSc() {
    return sc;
}

public void setSc(ServletContext sc) {
    this.sc = sc;
}

public void setServletContext(ServletContext sc) {
    this.sc = sc;
}
}

And now I can't do nothing, the request is always null

 request: null


Implement the ServletRequestAware Interface and set your request variable there instead of doing that during construction.

But normally you don't need access to the request as the params interceptor of struts does all the work the request object is needed for.

From the documentation of the ServletRequestAware-Interface:

All Actions that want to have access to the servlet request object must implement this interface.

This interface is only relevant if the Action is used in a servlet environment.

Note that using this interface makes the Action tied to a servlet environment, so it should be avoided if possible since things like unit testing will become more difficult.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜