Java到JSP - 如何将Java应用程序集成到JSP网页中?

Evi*_*mes 1 java jsp

好的,这是当天最简单的问题.这是我第一次尝试Java和JSP.

我刚刚使用Eclipse编写了一个小Java应用程序.现在我想把这个小应用程序提供到一个网页中.我需要弄清楚Java应用程序和网页之间的联系.

这是我的申请:

public class PhraseOMatic {

    public static void main(String[] args) {

        // CREATE WORD ARRAYS
    String[] wordListOne = {"24/7", "Multi-tier", "30,000 foot", "B-to-B", "win-win", "front-end", "back-end", "web-based"};
    String[] wordListTwo = {"empowered", "sticky", "concentric", "distributed", "leveraged", "shared", "accelerated", "aligned"};
    String[] wordListThree = {"process", "tipping point", "mindshare", "mission", "space", "paradigm", "portal", "vision"};

    // CALCULATE ARRAY LENGTHS
    int oneLength = wordListOne.length;
    int twoLength = wordListTwo.length;
    int threeLength = wordListThree.length;


    // PRINT OUT THE PHRASE
    int i = 1;
    while (i < 10) {
        // GENERATE RANDOM NUMBERS
        int rand1 = (int) (Math.random() * oneLength);
        int rand2 = (int) (Math.random() * twoLength);
        int rand3 = (int) (Math.random() * threeLength);

        // BUILD A PHRASE
        String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];

        // PRINT OUT PHRASE
        System.out.println("What we need is a " + phrase + ".");
        i = i + 1;

    }   

}
Run Code Online (Sandbox Code Playgroud)

}

如何将已编译的应用程序呈现为网页?接下来我需要采取哪些步骤?

谢谢!!!

Mav*_*rik 9

1)您必须使用一些返回某些结果的方法来定义一个类.例如

package example;
public class WordLength {

private String word="";
public int length=0;

public WordLength(){}

public void setWord(String w){
    word = w;
    length = word.length();
}

public String getWord(){
    return word;
}

public int getLength(){
    return length;
}

}
Run Code Online (Sandbox Code Playgroud)

2)你必须编译java文件并生成一个.class.您可以使用该命令执行此操作javac.否则你可以查看eclipse工作区的文件夹,在项目文件夹中你会发现.class从eclipse生成的文件夹.

3)将此文件放在名为的文件夹中WEB_INF\classes\example,该文件夹保留在tomcat文档文件夹的根目录中.(例子是包的名称)

4)在你的jsp文件中导入java类并使用它:

<!-- wordLegth.jsp -->

<%@ page language="java" import="java.util.*" %>

<html>
  <head>
    <title>Word length</title>
  </head>
  <body>

    <jsp:useBean id="counter" scope="session" class="example.WordLength"/>

    <% 
      String w1= request.getParameter("p1"); 
      int l1 = 0;
      counter.setWord(w1);
      l1 = counter.getLength();
    %>

    <p> The word <%= w1 %> has <%= l1 %> characters.</p>

  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

此示例由要求用户插入单词的表单自动调用:

<!-- form.html -->
<html>
  <head>
    <title>Form</title>
  </head>
  <body>

    <form action="wordLegth.jsp">

      <p> Word 1: <input name="p1"></p>
      </p>
      <input type="submit" value="Count">
    </form>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

此致,卢卡