This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Struts and the fly likes migration to Struts2 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "migration to Struts2" Watch "migration to Struts2" New topic
Author

migration to Struts2

sridhar gandikota
Ranch Hand

Joined: Jul 09, 2008
Posts: 31
Hi Ranchers,

I finding a big problem with Struts2. Is there any way that we can do migration of basic servlet application to struts2
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8836
    
    7

Exactly what problems are you having? You need to Tell The Details. The more detailed a question you ask, the better response we can give.
It appears that you are very new at Struts 2. There is no substitute to rolling up your sleeves and working with the API. Here are some links to get you going.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
sridhar gandikota
Ranch Hand

Joined: Jul 09, 2008
Posts: 31
Ya you are right I am new to this Struts2.

Basic Problem is that.

I have maping done in web.xml. The
sridhar gandikota
Ranch Hand

Joined: Jul 09, 2008
Posts: 31
Sorry by mistake the submit was done.

Rest of the message is..

basically i have mapping done in web.xml and now i migrated all the servlet code everything in struts2.

*/
public final void populateReqRespMappingHashMap(
final String strWebXmlFilePath)
throws ServletException {
XMLParser xMLParser = XMLParser.getInstance();
try {
modeObjReqMapperHashMap = xMLParser
.getRequestMapperHashMap(strWebXmlFilePath);

} catch (SAXParseException saxException) {
if (LOGGER.isErrorOn()) {
LOGGER.error("Got the SAXException in "
+ "populateReqRespMappingHashMap",
saxException);
}
throw new ServletException(saxException.getMessage());
} catch (IOException iOException) {
if (LOGGER.isErrorOn()) {
LOGGER.error(
"Got the IOException in populateReqRespMappingHashMap",
iOException);
}
throw new ServletException(iOException.getMessage());
} catch (Exception exception) {
if (LOGGER.isErrorOn()) {
LOGGER.error("Got the Generic Exception in "
+ "populateReqRespMappingHashMap",
exception);
}
throw new ServletException(exception.getMessage());
}
}

this is the method that fetches the mapping.

this mapping i have done in struts.xml

Even then the mapping always refers to the web.xml because when i replace the original web.xml it will run.

Hope i am clear in explanation
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8836
    
    7

Originally posted by sridhar gandikota:
Hope i am clear in explanation


Exactly what did you do to convert your servlet application to a Struts application? Just copy your servlet declarations from web.xml to struts.xml? That's not going to work.
sridhar gandikota
Ranch Hand

Joined: Jul 09, 2008
Posts: 31
Hi Joe,

the web.xml goes like this originally :-

<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>
cca.servlet.ControllerServlet
</servlet-class>
</servlet>
<servlet>
<servlet-name>HostServlet</servlet-name>
<servlet-class>
cca.servlet.HostServlet
</servlet-class>
</servlet>

<servlet>
<servlet-name>TaskServlet</servlet-name>
<servlet-class>
cca.servlet.TaskServlet
</servlet-class>
</servlet>

<servlet>
<servlet-name>ReferenceListServlet</servlet-name>
<servlet-class>
cca.servlet.ReferenceListServlet
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/servlet/ControllerServlet</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>HostServlet</servlet-name>
<url-pattern>/servlet/HostServlet</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>TaskServlet</servlet-name>
<url-pattern>/servlet/TaskServlet</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>ReferenceListServlet</servlet-name>
<url-pattern>/servlet/ReferenceListServlet</url-pattern>
</servlet-mapping>

<request-mapper>



<Request>
<request-page>cleanUpAgentReq</request-page>
<servlet-name>/servlet/HostServlet</servlet-name>
</Request>

<Request>
<request-page>taskReq</request-page>
<servlet-name>/servlet/TaskServlet</servlet-name>
</Request>


<Request>
<request-page>referenceReq</request-page>
<servlet-name>/servlet/ReferenceListServlet</servlet-name>
</Request>

</request-mapper>

<response-mapper>

<Response>
<request-page>cleanUpAgentReq</request-page>
<next-screen>configuration.html</next-screen>
</Response>

<Response>
<request-page>taskReq</request-page>
<next-screen>configuration.html</next-screen>
</Response>

<Response>
<request-page>referenceReq</request-page>
<next-screen>configuration.html</next-screen>
</Response>

</response-mapper>

</web-app>



And the one which i have done this in Struts2 in struts.xml is


<?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="false" />

<package name="cca.servlet" extends="struts-default">

<action name="ControllerServlet" class="cca.servlet.ControllerServlet">
<result name= "fullrequest" type="redirect">${strTargetUrl}</result>
<result name="servletname" type="redirect">
<param name="actionName">${strFinalPage}</param>
</result>
</action>

<action name="HostServlet" class="cca.servlet.HostServlet" >
<result type=""></result>
</action>

<action name="TaskServlet" class="cca.servlet.TaskServlet" >
<result type=""></result>
</action>

<action name="ReferenceListServlet" class="cca.servlet.ReferenceListServlet" >
<result type=""></result>
</action>

<action name="BaseServlet" class="cca.servlet.BaseServlet" >
<result name="Success">configuration.jsp</result>
</action>

<action name="TaskByTypeServlet" class="cca.servlet.TaskByTypeServlet" >
<result type=""></result>
</action>


</package>




</struts>


Here is my BaseServlet

public class BaseServlet implements WebConstants {

/** The Constant serialVersionUID. */
private static final long serialVersionUID = 5976880513552505240L;

/** The Constant LOGGER. */
private static final ESPLogger LOGGER = LogManager.getDefaultLogger();

/** The Constant JSP_ROOT_DIR. */
protected static final String JSP_ROOT_DIR = "/jsp";

/** The Constant FILE_SEPARATOR. */
protected static final String FILE_SEPARATOR = "/";

String strResponse = null;

HttpServletRequest httpServletRequest;
HttpServletResponse httpServletResponse;

private ServletContext sc;




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


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


public String getStrResponse()
{
return strResponse;
}


public void setStrResponse(String strResponse)
{
this.strResponse=strResponse;
}


public String execute()throws IOException,
ServletException, CCARunTimeException
{
doProcess();
return "NONE";
}



public final void doProcess()
throws IOException, ServletException {
boolean hasError = false;
PrintWriter printWriter = null;
String strResponse = null;
OutputFormatter outputFormatter = null;

try {

// set the content type
httpServletResponse.setContentType("text/plain");

httpServletRequest.setCharacterEncoding(GenUtil.UTF8ENCODING);

printWriter = httpServletResponse.getWriter();

DbConnMgr.setAutoCommit(false);

strResponse = getStrResponse();


} catch (CCARunTimeException cCRunTimeException) {
LOGGER.error(
"BaseServlet.doProcess:: "
+ "Got the CCRunTimeException Exception ->"
+ cCRunTimeException, cCRunTimeException);

hasError = true;
outputFormatter = getOutputFormatterObject(httpServletRequest);

// Get the Error Message from the Error Code
final int errorCode = cCRunTimeException.getErrorCode();
String strErrorMessage = GenUtils.getMessage(errorCode);

// Get the Error Message from the Exception.
strResponse = getErrorMessage(outputFormatter, strErrorMessage);
} catch (Throwable th) {

LOGGER.error(
"BaseServlet.doProcess:: Got the Throwable Exception ->"
+ th, th);
hasError = true;

outputFormatter = getOutputFormatterObject(httpServletRequest);

// Get the Error Message from the Exception.
strResponse = getErrorMessage(outputFormatter, th.getMessage());

} finally {
if (!hasError) {
try {
DbConnMgr.commit();
} catch (Exception e) {
LOGGER.error("BaseServlet.prcsPrivate::"
+ "DB Roll back error->" + e, e);
}
} else if (hasError) {
try {
DbConnMgr.rollback();
} catch (Exception e) {
LOGGER.error("BaseServlet.prcsPrivate::"
+ "DB Roll back error-> " + e, e);
}
}

}

// write the response to the Client
printWriter.println(strResponse);
printWriter.flush();
}



protected final void ccaServletSendRedirect(
final HttpServletRequest request,
final HttpServletResponse response,
final String strTargetUrl)
throws IOException, ServletException {

response.setContentType("text/html");

if (strTargetUrl == null) {
//log the error message
return;
}

ServletContext sc = getServletContext();
if (sc == null) {
if (LOGGER.isDebugOn()) {
LOGGER.debug("Null Servlet Context");
}
}

if (strTargetUrl.startsWith("http:")
|| strTargetUrl.startsWith("https:")) {
// URL has the complete path that
// includes http://hostname ort/<path>
// so redirect to the resource directly
// using response.sendRedirect();
response.sendRedirect(strTargetUrl);
return;
}

int nPos = strTargetUrl.toLowerCase().indexOf("/servlet");
String strFinalPage = strTargetUrl;

if (nPos != -1) {
strFinalPage = strTargetUrl.substring(nPos);
}

RequestDispatcher rd = sc.getRequestDispatcher(strFinalPage);
if (rd == null) {
if (LOGGER.isDebugOn()) {
LOGGER.debug("Null RequestDispatcher");
}
} else {
rd.include(request, response);
}

}

*/



protected final Long getAppIdFromRequest(
final HttpServletRequest httpServletRequest) {

Long userId = GenUtil.getLongObjectForString(ccaGetRequestParameter(
httpServletRequest, PRS_ID));
return userId;
}


protected final void ccaSendRedirect(
final HttpServletRequest request,
final HttpServletResponse response,
final String url)
throws IOException, ServletException {

ServletContext sc = getServletContext();
if (sc == null) {

if (LOGGER.isDebugOn()) {
LOGGER.debug("Null Servlet Context");
}

}

response.setContentType("text/html");
if (url.startsWith("http:") || url.startsWith("https:")) {
// URL has the complete path that
// includes http://hostname ort/<path>
// so redirect to the resource
//directly using response.sendRedirect();
response.sendRedirect(url);
return;
}

String strUrl = JSP_ROOT_DIR + FILE_SEPARATOR + url;

RequestDispatcher rd = sc.getRequestDispatcher(strUrl);
if (rd == null) {
if (LOGGER.isDebugOn()) {
LOGGER.debug("Null RequestDispatcher");
}
} else {
rd.include(request, response);
}

}


protected final String getAppPath() {
return this.getServletContext().getRealPath("/");
}


protected final boolean createCookie(
final HttpServletResponse httpServletResponse,
final String strCookieName,
final String strCookieValue) {

Cookie cookie = new Cookie(strCookieName, strCookieValue);
cookie.setMaxAge(60 * 1000);
cookie.setDomain(".myapp.com");
cookie.setPath("/");

if (LOGGER.isDebugOn()) {

LOGGER.debug("Cookies Name::" + cookie.getName() + ", data ->"
+ cookie.getValue());
}

httpServletResponse.addCookie(cookie);

return true;
}


protected final String getKookieValue(
final HttpServletRequest request,
final String cookieName) {
String strCookieValue = null;
Cookie cookie = getKookie(request, cookieName);

if (cookie == null) {
return strCookieValue;
}

strCookieValue = cookie.getValue();

return strCookieValue;
}


public final Cookie getKookie(
final HttpServletRequest request,
final String ckName) {
Cookie[] cookieArray = request.getKookies();
String name = null;
Cookie ckData = null;

if (cookieArray != null) {
for (int i = 0; i < cookieArray.length; i++) {
name = cookieArray[i].getName();

if (LOGGER.isDebugOn()) {
LOGGER.debug("AuthFilter.getKookie::name " + name
+ " rckName " + ckName);
}

if (ckName.equals(name)) {
ckData = cookieArray[i];
break;
}
}
}

return ckData;
}

/**
* Cca get request parameter.
*
* @param httpServletRequest the http servlet request
* @param strParam the str param
*
* @return the string
*/
protected final String ccaGetRequestParameter(
final HttpServletRequest httpServletRequest,
final String strParam) {

String strParamVal = httpServletRequest.getParameter(strParam);
return strParamVal;
}



/**
* Gets the user id from request.
*
* @param httpServletRequest the http servlet request
*
* @return the user id from request
*/
protected final Long getUserIdFromRequest(
final HttpServletRequest httpServletRequest) {

Long userId = GenUtil.getLongObjectForString(ccaGetRequestParameter(
httpServletRequest, PRS_ID));
return userId;
}



protected final String getErrorMessage(
final OutputFormatter outputFormatter,
final String strErrMessage) {
String errorMessage = null;

// Create the Response Object with the Error Message
// we got the exception object.
if (strErrMessage != null && outputFormatter != null) {
errorMessage = outputFormatter.getErrorMessage(strErrMessage);
}

return errorMessage;
}


protected final OutputFormatter getOutputFormatterObject(
final HttpServletRequest httpServletRequest) {
// as of now we are passing the output formatter type as JSON.
// later we can modify the code to read it from the request object
// if the application is expected to suppport in more
// than one form like JSON, XML etc
return FormatterFactory.getFormatter(FormatterFactory.FORMAT_JSON);
}

}

here is my controller servlet

public class ControllerServlet extends BaseServlet implements WebConstants {

/**
* versionID.
*/
private static final long serialVersionUID = 2608625099780183919L;

/**
* Instatiate a logger object.
*/
private static final ESPLogger LOGGER = LogManager.getDefaultLogger();

/**
* Declare a hashmap for request response mapping.
*/
private static HashMap<String, String> modeObjReqMapperHashMap =
new HashMap<String, String>();


HttpServletRequest request;


HttpServletResponse response;

private ServletContext sc;

public String completeURL=null;

public String strTargetUrl=null;

public String strFinalPage=null;

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

public void setServletResponse(HttpServletReponse response){
this.response = response;
}




/**
* Method process the request and redirects to the corresponding servlet
* based on the request type.
*
* @param request
* javax.servlet.http.HttpServletRequest
* @param response
* javax.servlet.http.HttpServletResponse
*
* @exception IOException
* if an input/output error occurs
* @exception ServletException
* if a servlet exception occurs
* @return Return ""
*/

public String getCompleteURL()
{
return completeURL;
}

public String setCompleteURL(String completeURL)
{
this.completeURL=completeURL;
}

public void setStrFinalPage(String strFinalPage)
{
this.strFinalPage=strFinalPage;
}

public String getStrFinalPage()
{
return strFinalPage;
}

public String execute()
throws IOException,
ServletException {

CCAProperties ccaProp = new CCAProperties("cbm.properties");

String strRequestPage = ccaGetRequestParameter(request,
REQUEST_PAGE);

// Get the Servlet Name for the given Request Page

/* Added the code from init method*/
String strXMLFilePath = config.getServletContext().getRealPath("/")
+ "WEB-INF/Mapping.xml";
populateReqRespMappingHashMap(strXMLFilePath);

/*End of: Added the code from init method*/

String strServletName = modeObjReqMapperHashMap.get(strRequestPage);


if (LOGGER.isDebugOn()) {
LOGGER.debug("ControllerServlet :: processRequest :: "
+ "Redirect request to = " + strServletName);
}






strServletName= strTargetUrl;

if (strTargetUrl.startsWith("http:")
|| strTargetUrl.startsWith("https:")) {
// URL has the complete path that
// includes http://hostname ort/<path>
// so redirect to the resource directly
// using response.sendRedirect();
setCompleteURL(strTargetUrl);

return "fullrequest";
}

int nPos = strTargetUrl.toLowerCase().indexOf("/servlet");
strFinalPage = strTargetUrl;

if (nPos != -1) {
strFinalPage = strTargetUrl.substring(nPos);
}


/* Commented because the below request looks for the web.xml
this is not available in the struts2. Everything moved to struts.xml



request.getRequestDispatcher("/login.action").forward(request,
response);




RequestDispatcher rd = sc.getRequestDispatcher(strFinalPage);
if (rd == null) {
if (LOGGER.isDebugOn()) {
LOGGER.debug("Null RequestDispatcher");
}
} else {
rd.include(request, response);
}
*/

setStrFinalPage(strFinalPage);

return "servletname";


/*End of: Code taken from BaseServlet and put here*/

}

/**
* Populates the request response mapping hash map.
*
* @param strWebXmlFilePath - Path to web.xml
* @throws ServletException - Handling servlet exceptions
*/
public final void populateReqRespMappingHashMap(
final String strWebXmlFilePath)
throws ServletException {
XMLParser xMLParser = XMLParser.getInstance();
try {
modeObjReqMapperHashMap = xMLParser
.getRequestMapperHashMap(strWebXmlFilePath);

} catch (SAXParseException saxException) {
if (LOGGER.isErrorOn()) {
LOGGER.error("Got the SAXException in "
+ "populateReqRespMappingHashMap",
saxException);
}
throw new ServletException(saxException.getMessage());
} catch (IOException iOException) {
if (LOGGER.isErrorOn()) {
LOGGER.error(
"Got the IOException in populateReqRespMappingHashMap",
iOException);
}
throw new ServletException(iOException.getMessage());
} catch (Exception exception) {
if (LOGGER.isErrorOn()) {
LOGGER.error("Got the Generic Exception in "
+ "populateReqRespMappingHashMap",
exception);
}
throw new ServletException(exception.getMessage());
}
}

}


My appl flow goes like this

First the there is a jsp that makes a call to controller servlet that will check for the type of the request and this request will be mapped to a perticular servlet that will be coming from web.xml and redirecting it name accordingly. I have done that redirection in struts.xml with actionName as the parameter. But still no result.

My questions are.

1) is it possible to migrate the basic servlet application by changes without touching the view and DAO part.
2) As I said in the above code all servlet extend baseservlet and finally the childservlet return a string and that inturn captured in base servlet and that put as reponse string to the client. Is there a posssiblity of extending BaseAction in childActions in struts2?
3) if child action returns a response string how it can be sent to baseAction.

With Regards,
Sridhar
Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8836
    
    7

I'm sorry, but I really don't have time to sort out the 700 lines you've posted. It would be nice if you could isolate the problem, perhaps by migrating just a portion of your application at a time. You would also do well to read up on how Struts 2 works so you have a better chance at success.

First the there is a jsp that makes a call to controller servlet that will check for the type of the request and this request will be mapped to a perticular servlet that will be coming from web.xml and redirecting it name accordingly.

This sure sounds like you are duplicating the functionality of Struts. You could probably do away with your controller servlet and use Struts directly.
sridhar gandikota
Ranch Hand

Joined: Jul 09, 2008
Posts: 31
Thanks Joe,

I will once again go through the code and probably if I have doubts I will get back to you
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: migration to Struts2
 
Similar Threads
Abt Struts2?
Struts2 doubt regarding method
migrating from struts 1 to struts2
struts1 & struts2
is STRUTS2 is used