Using JSP and JAVA

Asked

Viewed 3,778 times

5

I’m starting to mess with JSP. But I’ve been using JAVA for some time.

I have the index.jsp file which is my page and I have my indexJava.java which is the program itself. I would like to know how to join the two. For example, when I click on a button, it sends a variable to the . java and executes certain method that is related to this button.

2 answers

11


The middle man is Servlet.

First, let’s name things. No project is too small to use the MVC design standard, which is short for Model - View - Controller, and that means your project must have these three elements.

Your application should look like this:

Model: Java indexes.
(I took the liberty of capitalizing on the first letter of your class to follow the Java nomenclature pattern that says which classes should start with uppercase)
View: jsp result.
do not confuse with your index, which may be . html
Controller: Meucontroller.java
(just an example name, I suggest you put something more intuitive depending on what your application is about)

The Controller is what we call the Servlet, and the Servlet is a Java class. In the example above I called the Servlet Meucontroller.java. He, being a Java class, can communicate normally with his Model, as he said he has known Java for some time I believe that will not have difficulties in this part.

For a Java class to be a Servlet it must extend Httpservlet (or some other class that is a subclass in the Servlet interface hierarchy, but this is not the case). I recommend putting this class in a separate package of your Model to be very clear the distinction.

Your Servlet, by extending the Httpservlet class will have the possibility to override the methods doGet() and doPost() (among others, which are usually not used), which has the parameters Httpservletrequest and Httpservletresponse. These two parameters take two objects as argument, and who calls this method is Container (Tomcat), which is also responsible for creating the objects in question, consequently, Container has a reference to them, and when updating them in their Servlet class the Container will be aware of these modifications. This is how you communicate your Model classes with your View.

You still need to let your View know where your Servlet address, a flexible way to do this is by mapping the Servlet path through Deployment Descriptor, which is an XML file.

So that your homepage communicates with the methods doGet() and doPost() of your Servlet you must make a <form> in a . html file and submit directing to your Servlet, example:

<form method=POST action=SelectCoffee.do> 

By clicking the button submit you will send a POST type request to your Servlet, so your method doPost() will be triggered if you have not implemented the doPost() in your Servlet you will receive an error while trying to submit the form.

If you make your form so:

<form action=SelectCoffee.do> 

It will be of type GET, which is the default type. To work properly you will need to have implemented the method doGet() in his Servlet.

Selectcoffeee.do is the name I chose to give to Servlet, it is redirected to the class indicated in Deployment Descriptor.

Translating all this theory into practice, here is an example for you to use as a guide:

inserir a descrição da imagem aqui

This model I created based on chapter 3 of the book "Head First - Servlets & JSP", which is my object of study.

And the contents of the files are:

Coffeeexpert.java

package com.example.model;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServlet;

public class CoffeeExpert extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public List<String> getBrands(String type) {
        List<String> brands = new ArrayList<>();
        if(type.toLowerCase().equals("dark")) {
            brands.add("Toco");
            brands.add("3 Corações");
            brands.add("Pilão");
        }
        else if(type.toLowerCase().equals("cappuccino")) {
            brands.add("3 Corações");
            brands.add("Nescafé");
        }
        else if(type.toLowerCase().equals("expresso")) {
            brands.add("Do bar");
            brands.add("Da loja de carros");
        }
        return brands;
    }
}

Coffeeselect.java

package com.example.web;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.model.CoffeeExpert;

public class CoffeeSelect extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, 
            HttpServletResponse response) throws IOException, ServletException {
        String t = request.getParameter("type");
        CoffeeExpert ce = new CoffeeExpert();
        List<String> result = ce.getBrands(t);

        //--- LET THE FUN BEGIN! ---//
        request.setAttribute("styles", result);

        RequestDispatcher view = request.getRequestDispatcher("result.jsp");
        view.forward(request, response);
    }
}

web xml. (Deployment Descriptor)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <servlet>
        <servlet-name>Ch3 Coffee</servlet-name>
        <servlet-class>com.example.web.CoffeeSelect</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Ch3 Coffee</servlet-name>
        <url-pattern>/SelectCoffee.do</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>form.html</welcome-file>
    </welcome-file-list>
</web-app>

html form.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
    <h1 align=center>Coffee Selection Page</h1>
    <form method=GET action=SelectCoffee.do>
        <p>Select coffee type:</p>
        Type:
        <select name=type size=1>
        <option>Dark
        <option>Cappuccino
        <option>Expresso
        </select>
        <center><input type=submit></center>
    </form>
</body>
</html>

result.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Meu JSP</title>
</head>
<body>
    <h1 align=center>Coffee Recomendations JSP</h1>
    <p>
        <%
            @SuppressWarnings("unchecked")
            List<String> styles = (List<String>) request.getAttribute("styles");
            for(String s: styles) {
                out.print("<p>Try > " + s + "</p>");
            }
        %>
    </p>
</body>

PS: in the book it was Beer instead of Coffee, but I changed it because I didn’t find it very appropriate in a work environment :)


Receiving a vector in Servlet

In the above example I used:

String t = request.getParameter("type");

To receive the value of select in the initial html:

<select name=type size=1>

To take an array instead of a single value you basically have to change the getParameter() for getParameterValues(). See example:

<form method=GET action=Vector.do>
    <p>Select more than one option:</p>
    <input type=checkbox name=info value="opcao 1">op1
    <input type=checkbox name=info value="segunda opcao">op2
    <input type=checkbox name=info value=terceira>op3
    <input type=checkbox name=info value="ultima opcao">op4
    <center><input type=submit></center>
</form>

Servlet:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String[] info = req.getParameterValues("info");
    for(String s: info) {
        System.out.println(s);
    }
}

Selecting the four options the program prints in the console:

option 1
second option
third
last option

Note that I added another Servlet to Deployment Descriptor, and its URL is "Vector.do".

  • Vlw by the teachings Math. Already gave me a helping hand. Now I have the following context.xml files , index.jsp , Extract.java (my same class), Newservlet.java . But I still don’t understand how I’m going to pass a variable that’s in index.jsp and be able to use it in Extract.java

  • 1

    @user7569 in case your index.jsp was represented in my example as form.html, at least for what I understood. Note that you have to do a GET or POST type submission for your Servlet, then in the doGet() or doPost() method of your Servlet you can communicate normally with the Extract.java. Got it?

  • 1

    @user7569 I realized that I was missing an important piece of communication between the home page and Servlet, I made an edition adding these explanations. If you’d rather see only what I’ve changed in this edition click here

  • Thanks again for helping Math. I’m starting to see a light at the end of the tunnel. haha My question is now the following, I move from my html/jsp page to my Servlet a string and a list with some checkbox values (ie a vector with the values of the selected options). Then my Servlet takes u m string and a vector. How do I use them? I can see them on the link because I’m using GET, but I don’t know how to separate them so I can mess with them.

  • 1

    @user7569 good, to receive the parameters in Servlet you do through the request.getParameter("nomeParam"), in my example above is String t = request.getParameter("type"); which is the name of the select element in html. Now, to be quite honest, I never passed an array, I have to do some tests here to not talk nonsense. How you are generating this vector in your html?

  • I’m using <input type="checkbox" name="info[]" value="4"/> Then the marked options will be sent via GET, and the variable I need is also being sent. The end of my link is like this, "test" the string that passes from jsp to Servlet: Newservlet? test=Extract.pdf&info[]=1&info[]=3

  • 1

    @Peacefulness I edited my answer showing how to pick up a vector, rather than a single value. For your case you will have to combine the two forms, time you will use the getParameter() to pick up the variable "test" and time will use getParameterValues() to catch the vector.

  • +1 by the tutorial, very good even!

  • @Math thank you very much... but I have no idea how I will switch getParameter() and getParameterValues(). How do I step the two together, how do I switch? I do this in Servlet or already in my application (.java)??

  • 1

    @Peace is not alternating, it is combining. In a row you put String[] info = req.getParameterValues("info"); in another row a String t = request.getParameter("type");, soon, you will have your variables t and info loaded with the values brought from html.

  • I don’t think I expressed myself well @Math In your program, the Google method is responsible for the passage. However, I cannot have two Google methods. I need one for getParameter and one for getParameterValues ??

  • 1

    @Peace is not possible to have two doGet() in the same Servlet. It will be all within the same doGet() method. You can use getParameterValues() and getParameter() methods on top of a msm request, for example: String[] info = request.getParameterValues("info[]"); String teste = request.getParameter("teste"); Note that I used the names you used in your example in this comment here

  • @Math again thank you for your patience and help. This part is round. : D But now I have another problem :| in my . jsp I have an input file, q need to grab a file and in my . java I need to open it and grab the contents of that file. However, I had thought to just take what is passed by the url, as in the example cited above: Newservlet? test=Extract.pdf&info[]=1&info[]=3 But when it arrives in my . java does not recognize it as a path but as a string (half obvious and I didn’t think of it). How to pass a file or file path?

  • @Peace that I could help :) On your second question, it seems to me that you are distancing yourself a little from the doubt created in this topic here. I advise you to create a new question explaining in detail what you need, because the space of the comment is half short and you can not answer everything here, Moreover we maintain the organization of the site which makes it possible that future visitors with similar questions can easily find the answer to what they are looking for. I have ctz that you will have the answer to that doubt very easily the way I told you. Hug.

Show 9 more comments

3

Servlets are responsible for processing accesses to a given URL. Therefore, you need to create a Servlet to process the requests that will be made to the URL that your button points to.

In the code below, for example. All accesses to the URL http://meusite.com/home will be processed by the defined.

@WebServlet("/home")
public class ControllerServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // processar requisições GET aqui.
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // processar requisições POST aqui.
    }
}

You do not necessarily need to overwrite the methods listed above. There are other ways to process requests made to the URL assigned to Servlet. To better understand what these methods are, I recommend you take a look at Httpservlet class documentation.

  • 1

    It is worth mentioning that if you want to generate HTML in Servlet, you do not need to concatenate Strings: just give a forward to a JSP at the end of doGet (request.getRequestDispatcher(«página»).forward(request, response);). At the end of doPost, we recommend using a redirect to a GET (so that if the user refreshes the resulting page, the application does not repeat the operation)

  • Another very important thing with Servlets: don’t use instance variables, as they are shared by multiple requests. Use only local variables or method parameters. If it becomes difficult to guarantee this, please install another object for each request and do all the processing there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.