Consider a simply servlet:
// MyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
UtilClass.doSomething(getServletContext().getRealPath(SOME_FILE));
}
And the utility class does something with the file:
// UtilClass.java
public String doSomething(String filePath)
{
File f = new File(filePath);
String s = readWhateverFrom(f);
return s;
}
I am now porting the doSomething() function to a web service running under Tomcat and Axis2. How would I port it so that I can still access the context and get access to a file under the servlet?
You should get ahold of your (jax-ws) MessageContext. This would depend on your configuration, but perhaps using
#Resource
private WebServiceContext wsCtx;
and in your method:
MessageContext messageContext = wsCtx.getMessageContext()
ServletContext ctx = (ServletContext)
messageContext.getProperty(MessageContext.SERVLET_CONTEXT);
Edit: Seems like Axis2 (as well as Axis) support the following:
HttpServlet servlet = (HttpServlet)
MessageContext.getCurrentContext().getProperty(HTTPConstants.MC_HTTP_SERVLET);
ServletContext ctx = servlet.getServletContext();
With the following imports:
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
Sounds like a job for a Servlet Filter and a ThreadLocal. Axis is running within a Servlet Context, too. So all you have to do is to implement a custom javax.servlet.Filter, stuffing in the ServletRequest into a ThreadLocal where you can access it from within your utility class. You can get the ServletContext from the FilterConfig.
Related
I'm just starting out learning some JSP and servlets today and was wondering if it's possible to get the session's ServletContext as a variable and pass it to a plain Java class? If so, how may I do that?
My simple servlet:
public class myServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(true);
//How do I receive the servlet context below in a plain Java class?
ServletContext sc = session.getServletContext();
request.setAttribute("sc", sc);
}
}
My Java class is just a plain one:
public class myClass extends HttpServlet {
//I want to be able to use the ServletContext as a variable that is passed from myServlet class into this one.
}
In myClass I want to be able to use it to get the real path file of a file within my project:
ServletContext sc
String path = sc.getRealPath(...)
EDIT: Can I do something like this in myServlet servlet?:
String realPath = sc.getRealPath("/WEB-INF/myFile");
But then how do I pass this realPath variable into myClass so I can use it there instead of in myServlet?
create a class
public class MyClass {....}
Have a variable of type ServletContext
private ServletContext myContext;
Set value through Constructor or setter
void setContext (ServletContext sc) {myContext = sc;}
Use it
myContext.get....("xxx");
Edit
You can use this class from your servlet as
doPost (....) {
....
ServletContext sc = session.getServletContext();
MyClass mc = new MyClass ();
mc.setContext (sc);
// now the context is **in** the MyClass instance - how you use it is up to you.
In Java EE, we often use ActionContext,ServletContext and ServletActionContext, they have similar name, but I don't know the difference between them.
I only know the ServletActionContext inherit the ActionContext.
Someone can explain them?
There have many difference between them.
ServletContext
From the ServletContext's package(javax.servlet.ServletContext) we can know it is standard JavaEE WebApplication class library.
ServletContext provides the standard Servlet run-time environment. Actually is some methods of servlet communicate with web container.
public interface ServletContext {
// Returns the URL prefix for the ServletContext.
public String getServletContextName();
//Returns the context-path for the web-application.
public String getContextPath();
//Returns the ServletContext for the uri.
public ServletContext getContext(String uri);
//Returns the real file path for the given uri.
public String getRealPath(String uri);
public RequestDispatcher getNamedDispatcher(String servletName);
public RequestDispatcher getRequestDispatcher(String uri);
ServletContext is included in the ServletConfig, and ServletConfig often read from servlet or filter's init() method:
servletConfig.getServletContext()
filterConfig.getServletContext()
ActionContext
Comes from Struts, but at first comes from Struts1 and Struts2 they are different.
From Struts1:
A servlet (servlet org.apache.struts.action.ActionServlet) handle all the *.do action.
From Struts2:
The filter(org.apache.struts2.dispatcher.FilterDispatcher) handle all the request.
Because struts1 belongs to servlet scope. struts1 action's essentially is servlet.
struts2 action is normal Java bean, out of the servlet limitations.
The ActionContext makes up the lost WEB environment after the strtus2 action out of the stand servlet framework.
The ActionContext main function:
Provide the WEB context.
Solve the thread security issue.
Solve the incompatibility problem with other Framework(such as: webLogic))
ServletActionContext
As you say, ServletActionContext is ActionContext's subclass.
Its functions is starting at ActionContext, and encapsulate the methods, make it more simple and intuitive.
We can also study its source code:
public class ServletActionContext extends ActionContext implements StrutsStatics {
//HTTP servlet request
public static void setRequest(HttpServletRequest request) {
ActionContext.getContext().put(HTTP_REQUEST, request);
}
public static HttpServletRequest getRequest() {
return (HttpServletRequest) ActionContext.getContext().get(HTTP_REQUEST);
}
//HTTP servlet response
public static void setResponse(HttpServletResponse response) {
ActionContext.getContext().put(HTTP_RESPONSE, response);
}
public static HttpServletResponse getResponse() {
return (HttpServletResponse) ActionContext.getContext().get(HTTP_RESPONSE);
}
//servlet context.
public static ServletContext getServletContext() {
return (ServletContext) ActionContext.getContext().get(SERVLET_CONTEXT);
}
public static void setServletContext(ServletContext servletContext) {
ActionContext.getContext().put(SERVLET_CONTEXT, servletContext);
}
From above we can know the ServletActionContext extends ActionContext.
I have a java Rest WebService URL http://localhost:8080/WebServiceEx/rest/hello/dgdg
When i execute the URL ,the WebService Method Returns a String
My Requirement is to call the above WebService URL inside a Servlet ,Could any one Help?
ServletCode:
public Class StoreServlet extends HttpServlet{
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
//Invoke WebService and Get Response String Here
}
WebService Code:
public class HelloWorldService {
#Context
private ServletContext context;
#GET
#Path("/{param}")
public Response getMsg(#PathParam("param") String msg) {
return Response.status(200).entity(msg).build();
}
}
Take a look at Apache CXF JAX-RS client:
http://cxf.apache.org/docs/jax-rs-client-api.html
e.g.
BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getBook();
Or, if you use JAX-RS 2.0, it has a client API
e.g.
Client client = ClientFactory.newClient();
String bal = client.target("http://.../atm/balance")
.queryParam("card", "111122223333")
.queryParam("pin", "9876")
.request("text/plain").get(String.class);
Or you can do it the "core" way using just plain Java: http://www.mkyong.com/webservices/jax-rs/restfull-java-client-with-java-net-url/
One possibility is to generate a webservice client using jaxws(for this purposes - look up for a tutorial on the internet). Thus you get some Java classes you can use as usually inside your servlet.
I have an email utility class that is shared by all my intranet web apps which emails an employee their forgotten password (well the class is copied into each webapp). I need to brand the email with appropriate Subject Line, ReplyTo Point Of Contact, Application Name, etc that matches the app that is calling it.
I'm able to pass these as parameters but the way I do it is by including an initialize.jsp in my header on the login webpage.
<% request.setAttribute("siteEmail", "Commitment#<domain>.com");
request.setAttribute("siteName", "Commitment Report Database");
request.setAttribute("sitePOCEmail", "smith#<domain>.com");
%>
These request parameter are then stored into a DTO by a Struts similar Action
public class STKRequestPasswordAction implements ControllerAction {
public STKRequestPasswordAction() {}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ApplicationConfig ac = new ApplicationConfig();
ac.setAppEmail(request.getAttribute("siteEmail").toString());
ac.setAppName(request.getAttribute("siteName").toString());
ac.setPocEmail(request.getAttribute("sitePOCEmail").toString());
request.setAttribute("ac", ac);
userForm.requestPassword(LoginUser, ac);
The userForm.requestPassword method
public void requestPassword(STKUser loginUser, ApplicationConfig ac) {
validates the inputed userID requesting the password, builds the StringBuffer message, and then calls the Email Utility class.
EmailUtils.sendEMailByBadge(loginUser.getBadge(), strFrom, strReplyTo, strSubject, emailBody.toString(), strSMTP, true);
I'd like to refactor my initializing parameters out of the included jsp and put them into the web.xml, but I am not sure where I should be reading the values. I tried this in the POJO
String strFrom = getServletContext().getInitParameter("siteEmail");
but there is no servletContext in the POJO. I would imagine it could go in my servlet but my servlet uses a mapping as follows:
actionMap.put(null, new STKLoginSubmitAction());
actionMap.put("chkpass", new STKLoginSubmitAction());
actionMap.put("sqlReset", new STKRequestPasswordAction());
String op = request.getParameter("method");
ControllerAction action = (ControllerAction) actionMap.get(op);
I plan to move ApplicationConfig ac to the servlet and change the method signature for STKRequestPasswordAction to pass `ac'. Is this the best approach or am I missing the picture?
In your web.xml:
<env-entry>
<env-entry-name>myEntryName</env-entry-name>
<env-entry-type>java.lang.String</env-entry-type>
<env-entry-value>myEntryValue</env-entry-value>
</env-entry>
In your Java code:
// Do once
Context env = (Context) new InitialContext().lookup("java:comp/env");
// Do for every entry
String entryValue = (String) env.lookup("myEntryName");
Using JNDI you can read your settings every where in your webapp and also keep your configs out of your web.xml if you need, in context.xml for Tomcat or jetty-env.xml for Jetty for example (though format is different).
If we are coding a JSP file, we just need to use the embedded "application" object. But how to use it in a Servlet?
The application object in JSP is called the ServletContext object in a servlet. This is available by the inherited GenericServlet#getServletContext() method. You can call this anywhere in your servlet except of the init(ServletConfig) method.
public class YourServlet extends HttpServlet {
#Override
public void init() throws ServletException {
ServletContext ctx = getServletContext();
// ...
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext ctx = getServletContext();
// ...
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
ServletContext ctx = getServletContext();
// ...
}
}
See also Different ways to get Servlet Context.
The application object references javax.servlet.ServletContext and you should be able to reference that in your servlets.
To reference the ServletContext you will need to do the following:
// Get the ServletContext
ServletConfig config = getServletConfig();
ServletContext sc = config.getServletContext();
From then on you would use the sc object in the same way you would use the application object in your JSPs.
Try this:
ServletContext application = getServletConfig().getServletContext();
In a Java web application you often have the request object. So you can get the "application" object like this:
request.getServletContext().getServerInfo()