Well, basically my struts servlet isn’t working right. Please tell me if anything appears wrong below:
Java Resources\src\bo\DisplayCartServlet.java
package action;
import java.io.*;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.struts.action.*;
import bo.*;
import dao.*;
public class DisplayCartServlet extends Action
{
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
String forward = new String("success"); ;
String productCode = request.getParameter("productCode");
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null)
{
cart = new Cart();
session.setAttribute("cart", cart);
}
int quantity = 1;
// Get product from product code
Product product=null;
try {
product = ProductDB.selectProduct(productCode);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.setAttribute("product", product);
// If product exists, add or remove from cart
if (product != null)
{
LineItem lineItem = new LineItem();
lineItem.setProduct(product);
lineItem.setQuantity(quantity);
if (quantity > 0)
cart.addItem(lineItem);
else
cart.removeItem(lineItem);
}
session.setAttribute("cart", cart);
return(mapping.findForward(forward));
}
}
struts.xml
<?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="example" namespace="/example" extends="struts-default">
. . . .
<action name="cart" class="action.DisplayCartServlet" >
<result name="success">/example/cart.jsp</result>
</action>
</package>
</struts>
listProducts.jsp link that activates the struts and servlet
<div id="cartLink"><a href="<s:url action="cart?productCode=XM123456"/>">Add to Cart</a></div>
Your application isn’t working correctly because you have created a Struts 1 Action class but you are trying to configure it with a Struts 2 configuration XML.
Struts 1 and Struts 2 are very different.
Struts 1 Configuration is called
struts-config.xml: http://struts.apache.org/dtds/struts-config_1_3.dtdStruts 2 configuration is called
struts.xml: http://struts.apache.org/dtds/struts-2.0.dtdYou created a Struts 1 Action class (which as @BalusC pointed out, is not a Servlet) so you must configure it using
struts-config.xml…Or,
… you have to create a Struts 2 class to match the
struts.xmlconfiguration.