小服务程序映射
我是 java ee 6 的新手。我正在尝试获取 servlet 请求。除 /category 映射外,其他所有映射都可以正常工作。这是我的 ControllerServlet 类。我使用 @webServlet 注释进行映射。我尝试在 web.xml 中进行映射,但没有运气。使用 netbeans IDE 7.2,Server Glassfish 开源。
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ControllerServlet",
loadOnStartup = 1,
urlPatterns = {
"/addToCart",
"/viewCart",
"/updateCart",
"/checkout",
"/purchase",
"/chooseLanguage",
"/category"})
public class ControllerServlet extends HttpServlet {
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if cart page is requested
if (userPath.equals("/viewCart")) {
userPath = "/cart";
}
//if category page is requested
else if (userPath.equals("/category")) {
}
// if ckeckout page is requested
else if (userPath.equals("/checkout")){
// System.out.println("check");
}
// if user switches language
else if (userPath.equals("/chooseLanguage")){
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/View" + userPath + ".jsp";
System.out.print(url);
try{
request.getRequestDispatcher(url).forward(request, response);
}catch(Exception ex){
ex.printStackTrace();
}
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if addToCart action is called
if (userPath.equals("/addToCart")) {
// TODO: Implement add product to cart action
// if updateCart action is called
} else if (userPath.equals("/updateCart")) {
// TODO: Implement update cart action
// if purchase action is called
} else if (userPath.equals("/purchase")) {
// TODO: Implement purchase action
userPath = "/confirmation";
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}