I encountered various exceptions when I a wrote a HttpUnit test to call a servlet which dispatches the request to another JSP. I downloaded the required jars and updated the build path, then it worked. Below are list of jars I used:
- el-api.jar
- httpunit.jar
- jasper-el.jar
- jasper-jdt.jar
- jasper.jar
- js.jar
- jsp-api.jar
- junit-4.10.jar
- nekohtml.jar
- tomcat-6.0.33-tomcat-juli.jar
- xercesImpl-2.6.2.jar
Example Servlet:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.RequestDispatcher;
public class TestServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
RequestDispatcher rd = request.getRequestDispatcher("jsp/index2.jsp");
request.setAttribute("test","mymessage");
try{
rd.forward(request,response);
}catch (Exception e){
e.printStackTrace();
}
}
}
JSP: (present in "jsp" folder)
<% out.println("Forwarded JSP output");
out.println(request.getAttribute("test"));
%>
Web.xml:
<web-app id="WebApp">
<servlet>
<servlet-class>TestServlet</servlet-class>
<servlet-name>WebStandard</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>WebStandard</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
<servlet>
<servlet-class>TestServlet</servlet-class>
<servlet-name>WebStandard</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>WebStandard</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>
Example test:
@Test
public void testJSP() throws IOException, SAXException{
ServletRunner runner = new ServletRunner(new File(getClass().getResource("web.xml").getFile()));
ServletUnitClient client = runner.newClient();
WebConversation wc = new WebConversation();
System.out.println(client.getResponse("http://localhost/test").getText());
}
Output of Test:
Forwarded JSP output
mymessage
No comments:
Post a Comment