gpt4 book ai didi

java - 如何从 Servlet 获取对象作为参数

转载 作者:行者123 更新时间:2023-11-30 02:11:41 25 4
gpt4 key购买 nike

我无法理解如何将 getParameter() 与对象一起使用,因为我知道这是不可能的。而我应该做什么呢?

货币currency = req.getParameter("currencies");-它不起作用。

我的servlet:

public class AddPurseServlet extends HttpServlet {
private PurseDao purseDao;
private CurrencyDao currencyDao;

@Override
public void init() throws ServletException {
purseDao = (PurseDao) getServletContext().getAttribute("purseDao");
currencyDao = (CurrencyDao) getServletContext().getAttribute("currencyDao");
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Currency> currencies = currencyDao.getAll();

req.setAttribute("currencies", currencies);

req.getRequestDispatcher("WEB-INF/view/addPurse.jsp").forward(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
User user = (User) session.getAttribute("user");
String amount = req.getParameter("amount");
Currency currency = req.getParameter("currencies");

Purse purse = new Purse(user, currency, new BigDecimal(amount), new Timestamp(System.currentTimeMillis()));

purseDao.insert(purse);

resp.sendRedirect("userPage");
}
}

我的 jsp 页面需要货币和金额参数:

<html>
<head>
<title>Title</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Hello USER!</h1>
<div class="container">
<h1>Save User</h1>
<form method="post" action="addPurse">
<div class="form-group">
<label>Currency</label>
<select>
<c:forEach var="currency" items="${currencies}">
<option value="${currency.id}">${currency.name}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label>Amount</label>
<input class="form-control" name="amount" placeholder="Amount">
</div>
<input class="btn btn-default btn-xs" type="submit" value="Save">
<a class="btn btn-default btn-xs" href="usersList" role="button">cancel</a>
</form>
</div>
</body>
</html>

最佳答案

参数是字符串。

如果您的货币是枚举

final String currencyStr = request.getParameter("currency");
final Currency currency = Stream.of(Currency.values()).filter(currency -> currency.code.equals(currencyStr)).findFirst().orElse(null));

关于java - 如何从 Servlet 获取对象作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49871943/

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