Using JSP and JAVA

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 I can unite the two. For example, when I click a button, it sends a variable to the .java and performs a certain method that is related to this button.

    
asked by anonymous 26.06.2014 / 17:16

2 answers

9

Who does the middle field is the Servlet.

First, let's name things. No project is too small that can not be used the MVC project template, which is short for Model - View - Controller, and this means that your project must have these three elements.

Your application should look like this:

  

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

The Controller is what we call Servlet, and the Servlet is a Java class. In the above example I called the Servlet from MyController.java. As a Java class, you can communicate normally with your Model, as you said you know Java for some time, I think you will have no difficulties in that part.

For a Java class to be a Servlet it should extend HttpServlet (or some other class that is a subclass in the Servlet interface hierarchy, but that's not the case). I'd advise putting this class in a separate package from your Model to make the distinction clear.

Your Servlet, because you have extended the HttpServlet class, will be able to override the doGet() and doPost() methods (among others, which are not usually used), which have the HttpServletRequest and HttpServletResponse parameters. These two parameters receive two objects as arguments, and the one that calls this method is Container (Tomcat), which is also responsible for creating the objects in question, consequently, the Container has a reference of them, and when updating them in its class Servlet the Container will be aware of these modifications. This is how you communicate your Model classes with your View.

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

In order for your home page to communicate with the doGet() and doPost() methods of your Servlet you must <form> in a .html file and submit it by directing to your Servlet, eg:

<form method=POST action=SelectCoffee.do> 

When you click the submit button you will send a POST request to your Servlet, so your doPost() method will fire, if you did not implement doPost() in your Servlet you will receive an error trying to submit the form.

If you make your form like this:

<form action=SelectCoffee.do> 

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

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

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

ThistemplateIcreatedbasedonChapter3ofthebook"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>

form.html

<!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 did not find it very appropriate in a working environment:)

Receiving a vector in Servlet

In the example above I used:

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

To receive the value of the select that is in the initial html:

<select name=type size=1>

To get a vector instead of a single value, you basically have to change the getParameter() to 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 to the console:

  

option 1
  second option
  third
  last option

Notice that I've added one more Servlet in the Deployment Descriptor, and its URL is "Vector.do".

    
26.06.2014 / 19:26
3

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

In the code below, for example. All access to the link URL will be processed by the defined servlet.

@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 override the methods listed above. There are other ways to process requests made to the URL assigned to the servlet. To better understand what methods these are, I recommend that you take a look at HttpServlet class documentation .

    
26.06.2014 / 18:02