简体   繁体   English

无法将JSP中的对象转换为Java对象

[英]can not cast object in jsp to java object

I can not get this working and I dont know why... 我无法正常工作,我也不知道为什么...

  • Inside my .jsp I want to check if the executing user has suffient rights to do so. 在我的.jsp内部,我想检查执行用户是否具有足够的权限。
  • the user object from the class user is one of the session attributes 来自类用户的用户对象是会话属性之一
  • inside my .jsp file I get the Object from the session 在我的.jsp文件中,我从会话中获取对象
  • I then cast it into user 然后将其投放给用户
  • then I can access its stored values (which is an array list) 然后我可以访问其存储的值(这是一个数组列表)

  • Then when I go and test my code I get the error listed below. 然后,当我去测试我的代码时,出现以下错误。

Any Idea how to solve this Problem?? 任何想法如何解决这个问题?

user_management.jsp user_management.jsp

<% 
    User user = (User) session.getAttribute("obj_user");
    boolean test = user.oe_fac_role_right.get(2).get(0).equals(1);
    if (test) { 
%>
- some html code will be displayed here is the user is allowed to see it
<%  }  %>

User class 用户类别

public class User {
    int user_id;
    String username;
    List<List<Integer>> oe_fac_role_right = new ArrayList<List<Integer>>(4);

    public User(){}

    ....
    ....
}

Creation of User Object in login class: 在登录类中创建用户对象:

User user = new User(user_id, username, user_rights);

Passing User Object to session: 将用户对象传递给会话:

session.setAttribute("obj_user", user);

Error message from Netbeans 来自Netbeans的错误消息

 An error occurred at line: 14 in the jsp file: /user_management.jsp
 user cannot be resolved to a type

 Line 14 in this case is: User user = (User) session.getAttribute("obj_user");

Your line is having user starting with small letter but class name is User starting with capital letter. 您的行有以小写字母开头的用户 ,但类名是以大写字母开头的用户

change 更改

user user = (user) session.getAttribute("obj_user");

to

User user = (user) session.getAttribute("obj_user");

Also make your class public and import your class in jsp as below 也将您的班级公开,并按以下方式在jsp中导入班级

<%@ page import="yourPackage.User%>

if this is not working, let me know. 如果这不起作用,请告诉我。

it does not have any imports as the classes are all in the default package, so they should be accessable 它没有任何导入,因为所有类都在默认软件包中,因此它们应该可以访问

Incorrect . 不正确 The unnamed package is not accessible from another package, and the unnamed package cannot be imported. 无法从另一个程序包访问未命名的程序包,并且无法导入未命名的程序包。

Since a JSP is compiled to a Java class in some package, it can never access a class in the unnamed package. 由于JSP在某个程序包中被编译为Java类,因此它永远无法访问未命名程序包中的类。

Solution: You have to declare a package for the User class, then import the class in the JSP. 解决方案:您必须为User类声明一个包,然后将该类导入JSP。

See Import package with no name Java . 请参阅导入不带Java名称的软件包

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

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