How to use a Java class in JSP scriptlet? Error sa

2019-01-27 16:25发布

I have written a sample JSP file in Eclipse and a Java file and was trying to call the Java class inside my JSP but it is not working. The code of the JAVA file is as follows:

TestJava.jva

public class TestJava {
     public void test(String msg)
      {
          System.out.println("My name is "+msg);
      }
}

The Javafile is located at src folder. My JSP file test.jsp is as follows:

test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

 <html>
 <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
     <title>My First JSP with JAVA</title>
 </head>
 <body>
 <jsp:useBean id="link" scope="application" class = "TestJava" />   
  <% TestJava t=new TestJava();
  t.test("Joy");
 %>
 </body>
 </html>

It is giving error as "TestJava cannot be resolved to a type". I have studied other related posts in Stack Overflow but those approaches also did not work. Being new to JSP I cannot understand how to fix that error. So I am asking if anyone can help me to fix that problem.

Thank you.

6条回答
甜甜的少女心
2楼-- · 2019-01-27 16:42

You need to import your class using <%@ page %>

In your case, import Test in your jsp page like this.

<%@ page import="yourpackagename.Test" %>

if you want to import multiple classes that are in different packages declare them like this.

<%@ page import="yourpackagename.Test,yourpackagename2.Test2" %>

Also, I highly suggest you put your Test class outside the default package, and put it in another package.

查看更多
男人必须洒脱
3楼-- · 2019-01-27 16:42

Which IDE are you using? I recommend you use something like Eclipse with the JSP plugin. It will underline with a red objects that you attempt to declare that have not been compiled and imported.

You don't have to use beans by the way.. you can just create java objects and import them

查看更多
唯我独甜
4楼-- · 2019-01-27 16:47

<%@ page import="TestJava" %> Make sure that your TestJava is in the classpath

查看更多
Lonely孤独者°
5楼-- · 2019-01-27 16:48

Make sure about the @import as others said

and then The "class" attribute specifies the actual class of the bean instance.

 <jsp:useBean id="link" scope="application" class = "fullpackagename.TestJava" />
      <% TestJava t=new TestJava();
      t.test("Joy");
     %>
查看更多
Bombasti
6楼-- · 2019-01-27 16:56

In order to use class objects in java, you need to import classes first. Pretty much the same with scriplets in jsp, here you import it via <%@ page %> scriplet tags.

<%@ page import="your.class*" %>

查看更多
聊天终结者
7楼-- · 2019-01-27 17:04

You have to write fully qualified name of your class in page directive

<%@ page import="fully qualified name of the class" %>
查看更多
登录 后发表回答