Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.

Thursday, October 11, 2007

Calling a Servlet From a JSF managed bean

Cases when you simply want to call a servlet for doing tasks like database interactions etc and you do not want to use a framework like ADF-BC, EJB-toplink(may be because your requirements are too small ) you can do it in the following way:

Say there is a bean like:

public class SubscribeBean {
...
.. some code
.....

public void validateConfirmEmailId(FacesContext facesContext,
UIComponent uiComponent, Object object) {

//to call servlet use below code
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest req = (HttpServletRequest)fc.getExternalContext().getRequest();
HttpServletResponse resp=(HttpServletResponse)fc.getExternalContext().getResponse();

try{
Command cmdSub = new DoSubscribe();
cmdSub.execute(req, resp); //this is a servlet defined as below
}catch(Exception e){
System.out.println("exception in SubscriberBean.java");
}

}

Please note that the two lines in the try catch block are specific to your needs. Like here DoSubscribe is another class implementing a servlet execute(request, response).

You can also use following code to call a servlet:
FacesContext fc = FacesContext.getCurrentInstance();
ServletContext sc = (ServletContext) fc.getExternalContext().getContext();
sc.getRequestDispatcher(url);

For further help you can post a comment on this post....


9 comments:

Unknown said...

Hi Vik,

Gr8 Work !

But what i think why you need a sevlet again when you already have your request n response object at faces level.

instead of that i feel you just have to write a mehod in which u can make JDBC connection n follow your normal validation logic.

The sevlet call :
"Command cmdSub = new DoSubscribe();
cmdSub.execute(req, resp); //this is a servlet defined as below"

is not required.

If you have any reason for this , Kindly let us know.

Thanks
Rajeev

Unknown said...

Hie Rajeev:

Well you are right for what you said. You can achieve everything from writing a simple POJO instead of a servlet. But things are much more easy in the database layer when u have a servlet context or application context to read stuff like property files.

Secondly, URL forwarding is another thing which is a bit easier to do from a servlet depending upon ur business logic rather using a plain java class.

Anonymous said...

Hey Vik,
Good to see so many things on yuor blog. And belive me they are very helpful.

To make them more useful, i would like if you post something on requestScope and pageFlowScope.

Many people ask me about this diff.

believe me , such small things are really helpful to people.

What i have given u is just an example.

Unknown said...

hi,
i m try to call servlet but it doesnt work and give msg
Invalid argumentsin call
mycode

public String mySrvlet() {

System.out.println("------------To callServlet");
try {
ExternalContext ectx = FacesContext.getCurrentInstance().getExternalContext();
ServletRequest request = (ServletRequest)ectx.getRequest();
ServletResponse response = (ServletResponse)ectx.getResponse();
//request.setAttribute("test","some value to pass");
RequestDispatcher dispatcher = ((ServletContext)ectx.getContext()).getRequestDispatcher("/pentahoSearch.xhtml");//.getRequestDispatcher("/pentahoSearch.xhtml");


System.out.println("------------in try");

dispatcher.forward(request,response);
System.out.println("--after forward----------in try");
} catch (ServletException e) {
System.out.println(" **************error msg ");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "pentaho";
}

Unknown said...

Well Shweta at which line you are getting this error? try debugging it a bit.. is it a compile time error?

please mail me if u r not able to find the stuff at vik.ceo@gmail.com

Unknown said...

Hi Vivek,

This was very helpful information. Thanks for sharing this :)

Regards,
Shridhar

Anonymous said...

Good Afternoon!!! adfjsf.blogspot.com is one of the best informational websites of its kind. I enjoy reading it every day. adfjsf.blogspot.com rocks!

Unknown said...

hi Vik
this my servlet i use it to read employee picture:
public class getImage extends HttpServlet {

private static final String CONTENT_TYPE =
"image/jpeg; charset=windows-1252";

public void init(ServletConfig config) throws ServletException {
super.init(config);
}

public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType(CONTENT_TYPE);
response.setContentType(CONTENT_TYPE);
String empno = request.getParameter("Empno");
String where = "";
String amDef = "StdPortalPkg.StdPortalAppModuleDataControl";
String config = "StdPortalAppModuleLocal";
OutputStream os = response.getOutputStream();
ApplicationModule am;

HttpSession session = request.getSession();
String user = (String)session.getAttribute(Configuration.DB_USERNAME_PROPERTY);
String pass = (String)session.getAttribute(Configuration.DB_PASSWORD_PROPERTY);
am = Configuration.createRootApplicationModule(amDef, config, new DynamicJDBCEnvInfoProvider(user, pass,null));
.....My Code to read image Configuration.releaseRootApplicationModule(am, false);

}
}

the problem appear in my prepareSession when i call this method :
public void getStdInfo() throws SQLException {

CallableStatement cs = null;
ResultSet rs = null;
try {
cs =
getDBTransaction().createCallableStatement("begin STUDENT_GENERAL.StdMasterInfoWeb(?,?); end;",
0);
cs.setLong(1, OracleTypes.NULL);
cs.registerOutParameter(2, OracleTypes.CURSOR);
cs.execute();

rs = ((OracleCallableStatement)cs).getCursor(2);

if (rs.next()) {
FacesContext ctx = FacesContext.getCurrentInstance();
Map sessionState = ctx.getExternalContext().getSessionMap(); // here error java null pointer exception ???
StudentInfo stdinfo =
new StudentInfo(rs.getInt("STUDENT_NO"), rs.getString("STUDENT_A_NAME"),
rs.getString("COLLEGE_NAME"),
rs.getString("DEPARTMENT_NAME"),
rs.getInt("CURRSMTR"),
rs.getInt("REQUEST_SEMESTER"),
rs.getString("STUDENT_E_NAME"),
rs.getString("STATUS"),
rs.getString("STUDY_PROGRAM"),
rs.getInt("COLLEGE_NO"),
rs.getInt("DEPARTMENT_NO")
);
sessionState.put("stdinfo", stdinfo);
}

} catch (Exception ex) {
ex.printStackTrace();
}

finally {
cs.close();
rs.close();
}
}

thanks
maher

Unknown said...

@Maher

ctx.getExternalContext().getSessionMap()

in this which part is giving you NPE, getExternalContext() or getSessionMap() ?