如何使用 JSTL 在 .jsp 页面中调用 java 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15131033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:35:24  来源:igfitidea点击:

How to call a java method inside a .jsp page using JSTL

javajspservletsjstl

提问by Chamara Keragala

Below is my java code:

下面是我的java代码:

package employees;  
public class showString{    
    public String setSection(){
        String myStr = "Hello";
        return myStr ;
    }
};

How do i call setSection()method in my jsp page using JSTL? I've tried several methods but none of them worked.

如何setSection()使用 JSTL 在我的 jsp 页面中调用方法?我尝试了几种方法,但都没有奏效。

I've already checked this page How to avoid Java Code in JSP-Files?but don't understand how to call my method on the jsp file

我已经检查过这个页面如何避免 JSP 文件中的 Java 代码?但不明白如何在jsp文件上调用我的方法

This will be a great help. Thanks

这将是一个很大的帮助。谢谢

回答by MayurB

You can try <jsp:usebean>to call the method of the java bean.. Check the example below

你可以尝试<jsp:usebean>调用java bean的方法..查看下面的例子

package my;
public class MyBean {

  private String name=new String();

  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  } 

To call the setname method in jsp

在jsp中调用setname方法

<jsp:useBean id="mybean" class="my.MyBean" scope="session" >
<jsp:setProperty name="mybean" property="name" value=" Hello world" />
</jsp:useBean>

To call the getname method in jsp

在jsp中调用getname方法

<jsp:getProperty name="mybean" property="name" />

The main requirement is your method name should be start from get and set appended by property name

主要要求是您的方法名称应该从 get 和 set 开始,并附加属性名称

回答by orique

showStringis not a method but a class. You cannot "call" classes. If you want to call setSectionmethod, then you can try ${objectYouCreated.setSection()}

showString不是方法而是类。你不能“调用”类。如果你想调用setSection方法,那么你可以尝试${objectYouCreated.setSection()}

Also note you code does not follow case conventions in Java (The name of the class should start with an uppercase letter), and I'm not 100% sure if that semicolon at the end is valid Java syntax but looks really strange to me.

另请注意,您的代码不遵循 Java 中的大小写约定(类的名称应以大写字母开头),我不能 100% 确定末尾的分号是否是有效的 Java 语法,但对我来说看起来很奇怪。