JSP Test Page

Java Guides

Now, in the previous article, I mentioned that you wanted to minimize the scriptlets and declarations in a JSP.

You wanna avoid dumping thousands of lines of code in your JSP. Now, it’s okay to add small bits of script, small bits of declarations, but don’t overdo it.

So, in order to kinda help with this problem, you can refactor your code into a separate Java class or make use of MVC.

So the Java class will have all of our code, all of our business logic, and so on, and the JSP can simply make a call, let the Java code or the Java class do the heavy lifting, and then the JSP can get the results and continue on with its processing.

Development Steps

  1. Create a Java class
  2. Create a JSP page
  3. Call Java methods from Java class into JSP page.

1. Create a Java class — Calculator.java

I assume that you have already JSP application. Now you can create a Java class named Calculator.java and keep following code into it:

package net.javaguides.jsp.tutorial; public class Calculator < public int addition(int num1, int num2) < return (num1 + num2); > public int substraction(int num1, int num2) < return (num1 - num2); > public int multiplication(int num1, int num2) < return (num1 * num2); > public int division(int num1, int num2) < return (num1 / num2); > >

Create a JSP page — calculator.jsp

page import="net.javaguides.jsp.tutorial.Calculator"%>

Here is a complete example which is calling Calculator Java class methods and displaying results on brower.

page import="net.javaguides.jsp.tutorial.Calculator"%> page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> html> head> meta charset="ISO-8859-1"> title>Insert title heretitle> head> body>  Calculator calculator = new Calculator(); %> Addition of 20 + 10 =  calculator.addition(20, 10) %> br>br> Subtraction of 20 - 10 =  calculator.substraction(20, 10) %> br>br> Multiplication of 20 * 10 =  calculator.multiplication(20, 10) %> br>br> Division of 20/10 =  calculator.division(20, 10) %> body> html>

Источник

JSP in Java

JSP in Java

JSP is a short form of Java Server Pages. JSP does the processing of all its stuff on the server-side. This is an extension of the core Java Language. In Java, we can write a program but making things dynamic JSP is the one that can help us in doing that. This is basically a combination of HTML and Java. If we have an HTML file, the processes can be done using JavaScript. JavaScript works on the client machine but JSP works on the server-side. JSP is the best suited for server-side dynamic web pages. A JSP page can be the HTML or the JSP or the combination of both. The moment we save the HTML page as JSP, it will give us the ability to use the Java code on that page.

How does JSP Work in Java?

For running the JSP page, we need to have an environment. Since it runs on the server-side we need to have a server in addition to JDK. JDK can run the Java program only. As we know, the JSP code only runs on the server. We can use the Tomcat server for running our JSP file.

For writing JSP code we need to write our code inside .

Suppose we want to print Hello Word, we can write the code as mentioned below:

    Hello World!"); %> 

In the above code, we can see, it a combination of the HTML and the Java both.

The file extension of the JSP will be .jsp. If we want to save the above code as hello, then we need to save this with “hello.jsp”.

This program can be run using any of the web browsers. Function out.print() can be used to print anything on the output window. Everything we cannot achieve inside JSP but we can extend a fully functional Java class into our JSP file class. In JSP, we can get and set the session variable that we cannot in normal Java.

Since this is an extension of Java, code will be written in Java itself. There will be more features to play with addition to code Java features. There will be a block in which every code of the Java will be written. Outside this block HTML and the CSS, JavaScript, JQuery can be written. Now, time to see the scripting elements. These elements help us to write the java code into the JSP page.

Scriptlet Tag:

Expression Tag:

Declaration Tag:

Implicit objects of JSP in Java

There are 9 implicit objects in JSP to fulfill the various need.

PrintWriter out=response.getWriter();
String name=request.getParameter("user_name");
  • response: There are various things we can use this object. Like, sending a request to a page()
  • config: This can be used for initializing the parameter for a page or whole application.
  • Application
  • Session
  • pageContext
  • page
  • exception

This is some of the useful objects. JSP is more secure than another dynamic support language like PHP, ASP, etc. Due to Java Popularity, this JSP is still in demand.

Examples to Implement JSP in Java

Below are the examples of JSP in Java:

Example #1

Code: hello.jsp

    Hello World."); out.println("

This is my first JSP Program.

"); %>

JSP in Java Example 1

Example #2

Code: comment.jsp

    This is my first JSP Program."); %> 

Test Page Example 2

Example #3

JSP in Java Example 3

Example #4

     Reading session value: "+ session.getAttribute("SUMSESSION")); %> 

JSP in Java Example 4

Example #5

In this example, we will see, how we can print a message on the browser screen without using the out object.

    expression tag 

Expression Tag Example 5

Example #6

    

Test Initialization Page Example 6

Conclusion

It is better to use any IDE as it provides us a complete environment to run the JSP Program. Eclipse is the one we can move ahead with. We can choose any Eclipse out of its various available versions. There is another similar term Servlet, which is again very similar in nature and functionality to the JSP. For the beginner, we can also find some online editors if we are not able to set an environment for running the JSP on your machine.

Recommended Article

This is a guide to JSP in Java. Here we discuss the Introduction to JSP in Java and top Implicit objects along with its examples with Code Implementation. You can also go through our other suggested articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JSP JavaServer Pages Course Bundle — 11 Courses in 1 | 6 Mock Tests
93+ Hours of HD Videos
11 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Jsp code in java class

Страницы JSP могут включать некоторый код на Java. Таким образом, мы можем определять прямо в JSP переменные, методы, вообщем, некоторую логику. Однако если программной логики на Java довольно много, то лучше выносить ее в отдельные классы. Однако в данном случае может возникнуть вопрос, как организовать взаимодействие классов на Java и JSP. Рассмотрим этот вопрос.

В данном случае используем Eclipse. Создадим новый проект по типу Dynamic Web Project (как описано в прошлой теме) или возьмем уже имеющийся.

Допустим, в моем случае проект называется hellojsp. Перейдем в структуре проекта к узлу Java Resources и его под узлу src . Это тот узел, который хранит в проекте все классы на языке Java, которые мы хотим использовать в своем приложении.

Вначале добавим в папку src новый пакет, где будут располагаться классы. Поэтому нажмем на узел src правой кнопкой мыши и в контекстном меню выберем пункт New -> Package .

Добавление пакета Java в Eclipse

В появившемся окне укажем название пакета, например, com.metanit.hellojsp :

Далее добавим в этот пакет новый класс. Для этого в структуре проекта нажмем на пакет правой кнопкой мыши и в контекстном меню выберем пункт New -> Class :

Добавление класса Java для JSP в Eclipse

В окне добавления нового класса дадим ему имя Calculator (имя может быть произвольным). Остальные опции оставим по умолчанию.

Далее определим в файле Calculator.java следующий код:

package com.metanit.hellojsp; public class Calculator < public int square (int n) < return n * n; >>

В данном случае для простоты примера класс содержит один метод, который возводит число в квадрат.

Теперь определим в проекте в папке WebContent файл jsp, например, hello.jsp . Используем на странице hello.jsp класс Calculator. Для этого определим в hello.jsp следующий код:

       Square of 3 =  

Вначале с помощью директивы @page подключается класс com.metanit.hellojsp.Calculator. Затем его метод square используется на странице.

Источник

Читайте также:  Пример использования свойства CSS table-layout.
Оцените статью