I have this controller and in Get method I use request dispatcher and in Post I use redirect.
@WebServlet(name = "ControllerOrder", value = "/User/Order")
public class ControllerOrder extends HttpServlet {
private static final Logger LOGGER = Logger.getLogger(ControllerOrder.class);
private MySQLCarCategoryDao categoryDao;
@Override
public void init() throws ServletException {
super.init();
MySQLDAOFactory dao = (MySQLDAOFactory) getServletContext().getAttribute("MySQLFactory");
categoryDao = (MySQLCarCategoryDao) dao.getCarCategoryDao();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ImageManager manager = ImageManager.getInstance();
List<CarCategory> carCategories = categoryDao.findExistingCarC();
List<ToggleButton> buttons = IntStream.range(0, carCategories.size())
.mapToObj(i -> {
ToggleButton button = new ToggleButton();
button.setIcon("img:data:image/png;base64," + manager.getBase64String(manager.imageToByte(carCategories.get(i).getCarCategoryImage())));
button.setValue(carCategories.get(i).getCarCategory());
button.setSlot(i+1+"");
return button;
})
.collect(Collectors.toList());
ObjectMapper mapper = new ObjectMapper();
try {
request.setAttribute("CarCategories",carCategories);
request.setAttribute("CarCategoriesButtons",mapper.writeValueAsString(buttons));
} catch (JsonProcessingException e) {
LOGGER.error(e);
}
request.getRequestDispatcher("/WEB-INF/view/order.jsp").forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String login = (String) session.getAttribute("Login");
String userAddress = request.getParameter("userAddress");
String userDestination = request.getParameter("userDestination");
String[] stingNumbers = request.getParameterValues("numOfPas");
String[] categories = request.getParameterValues("categories");
if(stingNumbers != null && stingNumbers.length > 0&&categories != null && categories.length > 0) {
OrdersMaker maker = new OrdersMaker();
String message = maker.makeOrder(stingNumbers,categories,userAddress,userDestination,login);
if(message.startsWith("false")){
response.sendRedirect(request.getContextPath() + "/User/Order?NotAvailable=" + message);
return;
}
response.sendRedirect(request.getContextPath() + "/User/Order?takenTime=" + message);
}
}
}
I know you could say this pattern is easily understand but I want to know that I'm doing all right. Thanks for answering.
Aucun commentaire:
Enregistrer un commentaire