package ex02;
import java.io.IOException;
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("/purchaseCar")
public class CarPurchaseServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String model = req.getParameter("model");
String quantityStr = req.getParameter("quantity");
int quantity;
try {
quantity = Integer.parseInt(quantityStr);
} catch (NumberFormatException e) {
quantity = 0;
System.out.println(quantity);
}
if(model == null || model.isEmpty() || quantity == 0) {
model = "Tesla Model S";
quantity = 3;
}
String message = quantity + "대의 " + model + "를 구매하셨습니다!";
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("<h2>" + message + "</h2>");
}
}
🌟 결과
😥 트러블슈팅
- java.lang.NumberFormatException 에러 발생
- 서칭을 해보니 null인 문자형을 숫자형으로 변환하려고 할 때 발생하는 에러였다.
- 따라서, try-catch문으로 예외처리를 해주었다.
⬇️ 수정 전
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String model = req.getParameter("model");
String quantityStr = req.getParameter("quantity");
int quantity = Integer.parseInt(quantityStr);
if(model == null || model.isEmpty() || quantity == 0) {
model = "Tesla Model S";
quantity = 3;
}
String message = quantity + "대의 " + model + "를 구매하셨습니다!";
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("<h2>" + message + "</h2>");
}
⬇️ 수정 후
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String model = req.getParameter("model");
String quantityStr = req.getParameter("quantity");
int quantity;
try {
quantity = Integer.parseInt(quantityStr);
} catch (NumberFormatException e) {
quantity = 0;
System.out.println(quantity);
}
if(model == null || model.isEmpty() || quantity == 0) {
model = "Tesla Model S";
quantity = 3;
}
String message = quantity + "대의 " + model + "를 구매하셨습니다!";
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("<h2>" + message + "</h2>");
}
📌 참고 자료
'JSP > STUDY' 카테고리의 다른 글
[JSP] JSP 실습예제 - 4 (0) | 2024.08.30 |
---|---|
[JSP] JSP 실습예제 - 3 (0) | 2024.08.30 |
[JSP] JSP 실습예제 - 1 (0) | 2024.08.29 |
[JSP] request.getParameter() (0) | 2024.05.20 |
[JSP] PrintWriter out = response.getWriter(); (0) | 2024.05.20 |