简体   繁体   English

JSP 将 request.getParameter 转换为实体

[英]JSP Cast request.getParameter to Entity

This is the scenario这是场景

This is the JSP from where I get to the servlet.这是我从那里到达 servlet 的 JSP。 There is an entity called CurrentUser wich holds multiple fields of information about the user.有一个名为CurrentUser的实体,其中包含有关用户的多个信息字段。 I want to pass the servlet all the information about the user in a form of entity.我想以实体的形式将有关用户的所有信息传递给 servlet。

<a href="Controller?action=profile&entity=<%=_currentUser%>"> Information about the current user, like: name, id, profile picture etc... </a>

Inside the servlet:在 servlet 内部:

if(request.getParameter("action").equals("profile")){
        CurrentUser _currentUser= (CurrentUser) request.getParameter("entity");
}

If I do a system.out to see whats inside "entity" parameter i get something like: Package.CurrentUser@abc1235 ... and I cannot cast that, to receive it as an Entity.如果我执行 system.out 以查看“实体”参数中的内容,我会得到如下内容: Package.CurrentUser@abc1235 ...但我无法将其作为实体接收。

incompatible types: String cannot be converted to CurrentUser

Is there any way to get that refference and the info inside those fields?有什么方法可以获取这些字段中的引用和信息?

No, you shouldn't do it.不,你不应该这样做。 Using the reference string representation you can't retrieve object instance.使用引用字符串表示不能检索对象实例。 But you can use String object's ID parameter in the query string.但是您可以在查询字符串中使用 String 对象的 ID 参数。 Then retrieve the object by ID.然后通过 ID 检索对象。

<a href="Controller?action=profile&entity=<%=_currentUser.id%>"> Information about the current user, like: name, id, profile picture etc... </a>
String id = request.getParameter("entity");

Inside the JSP, store your _currentUser entity to the Session as在 JSP 中,将您的_currentUser实体存储到Session作为

<% session.setAttribute("entity", _currentUser); %>
<a href="Controller?action=profile">Information ... </a>

Now, inside the Controller Servlet you can retrieve this entity as现在,在Controller Servlet 中,您可以将这个entity检索为

if(request.getParameter("action").equals("profile")){
    CurrentUser _currentUser= (CurrentUser) session.getAttribute("entity");
}

Note, that storing the current user object into Session should ideally be done by the Servlet that forwarded the request to the JSP first.请注意,将当前用户对象存储到Session理想情况下应该由首先将请求转发到 JSP 的Servlet完成。 Use of Java code scriptlets <% %> inside a JSP is deprecated as JSPs should mostly be used for presentation purposes only.在 JSP 中使用 Java 代码脚本<% %>已被弃用,因为 JSP 主要仅用于演示目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM