gpt4 book ai didi

java - Spring MVC - POJO 抛出无效 spring 的异常 :form information how to how to catch in controller

转载 作者:太空宇宙 更新时间:2023-11-04 12:22:46 26 4
gpt4 key购买 nike

我创建了 POJO,它验证产品名称不得少于 3 个字符。在 JSP 中使用 spring:form 在提交时创建对象。当我发送空白表单“名称”POJO 时抛出异常。 Controller 在 POST 方法中有 @Modelattribute 产品,但未创建产品对象,并且 APP 因 POJO 异常而崩溃。我想捕获此异常并将其作为错误消息添加回给用户。我做错了什么。

POJO代码:

public class Product {
private int id;
private String name;
private Department deparment;

public Product() {
}

// Create product from DB
public Product(int id, String name, Department deparment) {
this.id = id;
try {
setName(name);
setDeparment(deparment);
} catch (ProductException | DeparmentException e) {
e.getMessage();
e.printStackTrace();
}
}

// Create new product in DB
public Product(String name, Department deparment) {
try {
setName(name);
setDeparment(deparment);
} catch (ProductException | DeparmentException e) {
e.getMessage();
e.printStackTrace();
}
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public void setName(String name) throws ProductException {
if (name.length() > 3) {
this.name = name;
} else {
throw new ProductException("Invalid name for product");
}
}

public Department getDeparment() {
return deparment;
}

public void setDeparment(Department deparment) throws DeparmentException {
if (deparment != null) {
this.deparment = deparment;
} else {
throw new DeparmentException("Invalid deparment for product");
}

}

JSP代码:

    <c:if test="${not empty error}">
<p style="color: red">Error: ${error}</p>
</c:if>
<c:if test="${not empty success}">
<p style="color: green">${success}</p>
</c:if>

<springForm:form action="product" method="post" commandName="product">

<springForm:input type="text" placeholder="Име на продукта"
path="name" pattern=".{3,}" />
<br>
<br>

<select id="department" name="department">
<option value="0">Department</option>
<!-- Var mi e promenlivata items e masiva-->

<c:forEach var="department" items="${departments}">
<option value="${department.id}">${department.name}</option>
</c:forEach>
</select>
<button>Create</button>
</springForm:form>

Controller 代码:

public class ProductController {

@RequestMapping(method = RequestMethod.GET, value = "/product")
public String showProductForm(Model viewModel) {
DepartmentDAO deparmentDAO = new DepartmentDAO();
List<Department> departments = new ArrayList<Department>();
try {
departments = deparmentDAO.selectAllDeparments();
} catch (DeparmentException e) {
e.printStackTrace();
}
viewModel.addAttribute("departments", departments);
viewModel.addAttribute("product", new Product());

return "product";
}

@RequestMapping(method = RequestMethod.POST, value = "/product")
public String addNewProduct(@ModelAttribute Product product, Model viewModel,@ModelAttribute("department") int departmentId, BindingResult result) {
DepartmentDAO departmentDAO = new DepartmentDAO();
ProductDAO productDAO = new ProductDAO();

if (departmentId == 0) {
viewModel.addAttribute("error", "Department is not selected.");
return showProductForm(viewModel);
}

try {
Department department = departmentDAO.getDepartmentById(departmentId);
product.setDeparment(department);
productDAO.addProduct(product);
} catch (ProductException | DeparmentException e) {
viewModel.addAttribute("error", e.getMessage());
e.printStackTrace();
return showProductForm(viewModel);
}
viewModel.addAttribute("success", "Въведохте успешно Продукта: <br>" + product.getName());

return showProductForm(viewModel);
}

最佳答案

您不应该从 setter 中抛出异常;如果您这样做,Spring 将无法填充模型以将其传递给 Controller ​​。您应该为此使用验证;要么推出一个自定义的,这可能会引发您可以捕获的异常:

public void validate (Product p) throws ProductException() {...}

或者使用 Spring 的标准验证支持:

@RequestMapping(method = RequestMethod.POST, value = "/product")
public String addNewProduct(@ModelAttribute @Valid Product product, BindingResult result, Model viewModel,@ModelAttribute("department") int departmentId, BindingResult result) {...

请参阅 spring 文档以获取更多信息;我建议这个,这是标准方式

关于java - Spring MVC - POJO 抛出无效 spring 的异常 :form information how to how to catch in controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38659898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com