Commit 14601439 by Patryk Czarnik

Uzupełnienia do PC25

"sprawy techniczne" oraz dodatkowe wersje kalkulatora
parent 54e7a95b
package kalkulator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/Kalkulator5")
public class Kalkulator5 extends HttpServlet {
private static final long serialVersionUID = 1L;
// Jeśli w serwlecie umieścimy pole, np. listę, to jest ono widoczne i wspólne dla różnych klientów.
// Serwer ma też prawo w dowolnym momencie skasować ten obiekt Kalkulator5 (a wraz z nim listę) i utworzyć nowy.
private final List<String> historia = Collections.synchronizedList(new ArrayList<>());
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = ustawNaglowkiIPobierzWritera(response);
poczatek(out);
formularz(out);
wyswietlHistorie(out);
koniec(out);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = ustawNaglowkiIPobierzWritera(response);
poczatek(out);
formularz(out);
obsluzParametryIWyswietlWynik(request, out);
wyswietlHistorie(out);
koniec(out);
}
private PrintWriter ustawNaglowkiIPobierzWritera(HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
return out;
}
private void poczatek(PrintWriter out) {
out.println("<html>");
out.println("<head>");
out.println("<title>Kalkulator 5</title>");
out.println("<link rel='stylesheet' type='text/css' href='styl.css'>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Kalkulator 5</h1>");
}
private void koniec(PrintWriter out) {
out.println("</body>");
out.println("</html>");
}
private void formularz(PrintWriter out) {
out.println("<form method='post'>");
out.println("<label for='liczba1'>Liczba 1: </label>");
out.println("<input type='text' name='liczba1'/> <br/>");
out.println("<label for='liczba2'>Liczba 2: </label>");
out.println("<input type='text' name='liczba2'/> <br/>");
out.println("<label for='operacja'>Wybierz działanie: </label>");
out.println("<select name='operacja'>");
out.println("<option value='+'>+</option>");
out.println("<option value='-'>-</option>");
out.println("<option value='*'>×</option>");
out.println("<option value='/'>÷</option>");
out.println("</select><br/>");
out.println("<button>Oblicz</button>");
out.println("</form>");
}
private void obsluzParametryIWyswietlWynik(HttpServletRequest request, PrintWriter out) {
String parametr1 = request.getParameter("liczba1");
String parametr2 = request.getParameter("liczba2");
String operacja = request.getParameter("operacja");
if (parametr1 != null && parametr2 != null && operacja != null) {
try {
long liczba1 = Long.parseLong(parametr1);
long liczba2 = Long.parseLong(parametr2);
long wynik = LogikaKalkulatora.oblicz(liczba1, liczba2, operacja);
out.println("<div class='wynik'>");
out.printf("%d %s %d = <strong>%d</strong>", liczba1, operacja, liczba2, wynik);
out.println("</div>");
historia.add(String.format("%d %s %d = %d", liczba1, operacja, liczba2, wynik));
} catch (NumberFormatException e) {
out.printf("<div class='error'>Niepoprawny format liczby %s</div>", e.getMessage());
} catch (Exception e) {
out.printf("<div class='error'>Inny wyjątek %s</div>", e);
}
}
}
private void wyswietlHistorie(PrintWriter out) {
out.println("<h3>Historia</h3>");
out.println("<ul class='historia'>");
synchronized (historia) {
for (String s : historia) {
out.printf("<li>%s</li>\n", s);
}
}
out.println("</ul>");
}
}
package kalkulator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Kalkulator6")
public class Kalkulator6 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = ustawNaglowkiIPobierzWritera(response);
poczatek(out);
formularz(out);
wyswietlHistorie(request, out);
koniec(out);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = ustawNaglowkiIPobierzWritera(response);
poczatek(out);
formularz(out);
obsluzParametryIWyswietlWynik(request, out);
wyswietlHistorie(request, out);
koniec(out);
}
private PrintWriter ustawNaglowkiIPobierzWritera(HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
return out;
}
private void poczatek(PrintWriter out) {
out.println("<html>");
out.println("<head>");
out.println("<title>Kalkulator 6</title>");
out.println("<link rel='stylesheet' type='text/css' href='styl.css'>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Kalkulator 6</h1>");
}
private void koniec(PrintWriter out) {
out.println("</body>");
out.println("</html>");
}
private void formularz(PrintWriter out) {
out.println("<form method='post'>");
out.println("<label for='liczba1'>Liczba 1: </label>");
out.println("<input type='text' name='liczba1'/> <br/>");
out.println("<label for='liczba2'>Liczba 2: </label>");
out.println("<input type='text' name='liczba2'/> <br/>");
out.println("<label for='operacja'>Wybierz działanie: </label>");
out.println("<select name='operacja'>");
out.println("<option value='+'>+</option>");
out.println("<option value='-'>-</option>");
out.println("<option value='*'>×</option>");
out.println("<option value='/'>÷</option>");
out.println("</select><br/>");
out.println("<button>Oblicz</button>");
out.println("</form>");
}
private void obsluzParametryIWyswietlWynik(HttpServletRequest request, PrintWriter out) {
String parametr1 = request.getParameter("liczba1");
String parametr2 = request.getParameter("liczba2");
String operacja = request.getParameter("operacja");
if (parametr1 != null && parametr2 != null && operacja != null) {
try {
long liczba1 = Long.parseLong(parametr1);
long liczba2 = Long.parseLong(parametr2);
long wynik = LogikaKalkulatora.oblicz(liczba1, liczba2, operacja);
out.println("<div class='wynik'>");
out.printf("%d %s %d = <strong>%d</strong>", liczba1, operacja, liczba2, wynik);
out.println("</div>");
List<String> historia = pobierzHistorieZSesji(request);
historia.add(String.format("%d %s %d = %d", liczba1, operacja, liczba2, wynik));
} catch (NumberFormatException e) {
out.printf("<div class='error'>Niepoprawny format liczby %s</div>", e.getMessage());
} catch (Exception e) {
out.printf("<div class='error'>Inny wyjątek %s</div>", e);
}
}
}
private void wyswietlHistorie(HttpServletRequest request, PrintWriter out) {
out.println("<h3>Historia</h3>");
out.println("<ul class='historia'>");
List<String> historia = pobierzHistorieZSesji(request);
synchronized (historia) {
for (String s : historia) {
out.printf("<li>%s</li>\n", s);
}
}
out.println("</ul>");
}
private List<String> pobierzHistorieZSesji(HttpServletRequest request) {
HttpSession session = request.getSession();
final String HISTORIA = "historia6";
// próbuję odczytać listę z sesji
List<String> historia = (List<String>) session.getAttribute(HISTORIA);
if(historia == null) {
// aa jeśli jeszcze nie została utowrzona (bo to jest pierwsze działanie tego klienta), to tworze pustą listę i zapamiętuję w sesji
historia = Collections.synchronizedList(new ArrayList<>());
session.setAttribute(HISTORIA, historia);
}
return historia;
}
}
package kalkulator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Kalkulator7")
public class Kalkulator7 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = ustawNaglowkiIPobierzWritera(response);
poczatek(out);
formularz(out);
wyswietlHistorie(request, out);
koniec(out);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = ustawNaglowkiIPobierzWritera(response);
poczatek(out);
formularz(out);
obsluzParametryIWyswietlWynik(request, out);
wyswietlHistorie(request, out);
koniec(out);
}
private PrintWriter ustawNaglowkiIPobierzWritera(HttpServletResponse response) throws IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
return out;
}
private void poczatek(PrintWriter out) {
out.println("<html>");
out.println("<head>");
out.println("<title>Kalkulator 7</title>");
out.println("<link rel='stylesheet' type='text/css' href='styl.css'>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Kalkulator 7</h1>");
}
private void koniec(PrintWriter out) {
out.println("</body>");
out.println("</html>");
}
private void formularz(PrintWriter out) {
out.println("<form method='post'>");
out.println("<label for='liczba1'>Liczba 1: </label>");
out.println("<input type='text' name='liczba1'/> <br/>");
out.println("<label for='liczba2'>Liczba 2: </label>");
out.println("<input type='text' name='liczba2'/> <br/>");
out.println("<label for='operacja'>Wybierz działanie: </label>");
out.println("<select name='operacja'>");
out.println("<option value='+'>+</option>");
out.println("<option value='-'>-</option>");
out.println("<option value='*'>×</option>");
out.println("<option value='/'>÷</option>");
out.println("</select><br/>");
out.println("<button>Oblicz</button>");
out.println("</form>");
}
private void obsluzParametryIWyswietlWynik(HttpServletRequest request, PrintWriter out) {
String parametr1 = request.getParameter("liczba1");
String parametr2 = request.getParameter("liczba2");
String operacja = request.getParameter("operacja");
if (parametr1 != null && parametr2 != null && operacja != null) {
try {
long liczba1 = Long.parseLong(parametr1);
long liczba2 = Long.parseLong(parametr2);
long wynik = LogikaKalkulatora.oblicz(liczba1, liczba2, operacja);
out.println("<div class='wynik'>");
out.printf("%d %s %d = <strong>%d</strong>", liczba1, operacja, liczba2, wynik);
out.println("</div>");
List<String> historia = pobierzHistorieZSesji(request);
historia.add(String.format("%d %s %d = %d", liczba1, operacja, liczba2, wynik));
} catch (NumberFormatException e) {
out.printf("<div class='error'>Niepoprawny format liczby %s</div>", e.getMessage());
} catch (Exception e) {
out.printf("<div class='error'>Inny wyjątek %s</div>", e);
}
}
}
private void wyswietlHistorie(HttpServletRequest request, PrintWriter out) {
out.println("<h3>Historia</h3>");
out.println("<ul class='historia'>");
List<String> historia = pobierzHistorieZSesji(request);
synchronized (historia) {
for (String s : historia) {
out.printf("<li>%s</li>\n", s);
}
}
out.println("</ul>");
}
private List<String> pobierzHistorieZSesji(HttpServletRequest request) {
HttpSession session = request.getSession();
return (List<String>) session.getAttribute(ListenerHistorii.HISTORIA_KLIENTA);
}
}
package kalkulator;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Kalkulator8")
public class Kalkulator8 extends HttpServlet {
private static final long serialVersionUID = 1L;
// Technologia serwletów nie gwarantuje, że wszystkie zapytania będą obsługiwane przez ten sam obiekt serwletu.
// Dlatego nie powinniśmy przechowywać istotnych danych w polach instancyjnych tej klasy.
// Użycie zmiennej statycznej spowodowałoby, że będzie to poprawne, ale to jest uznawane za "brzydkie podejście".
private static List<String> historiaStatyczna = Collections.synchronizedList(new ArrayList<>());
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Kalkulator 8</title>");
out.println("<link rel='stylesheet' type='text/css' href='styl.css'/>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Kalkulator 8</h1>");
out.println("<form method='post'>");
out.println("<label for='liczba1'>Liczba 1: </label>");
out.println("<input type='number' name='liczba1'/> <br/>");
out.println("<label for='liczba2'>Liczba 2: </label>");
out.println("<input type='number' name='liczba2'/> <br/>");
out.println("<label for='operacja'>Wybierz działanie: </label>");
out.println("<select name='operacja'>");
out.println("<option value='+'>+</option>");
out.println("<option value='-'>-</option>");
out.println("<option value='*'>×</option>");
out.println("<option value='/'>÷</option>");
out.println("</select><br/>");
out.println("<button>Oblicz</button>");
out.println("</form>");
// Tutaj zakładamy, że listener przygotował historię działań globalną i klienta.
// ServletContext to jest obiekt, który dostarcza informacji o bieżącej aplikacji na serwerze.
// Pełni też rolę "globalnego schowka" - przechowuje obiekty w zakresie aplikacji. (scope="application")
ServletContext servletContext = this.getServletContext();
List<String> historiaGlobalna = (List<String>) servletContext.getAttribute(ListenerHistorii.HISTORIA_GLOBALNA);
// Sesja jest schowkiem do przechowywania danych skojarzonych z konretnym klientem (np. koszyk w sklepie).
HttpSession sesja = request.getSession();
List<String> historiaKlienta = (List<String>) sesja.getAttribute(ListenerHistorii.HISTORIA_KLIENTA);
String parametr1 = request.getParameter("liczba1");
String parametr2 = request.getParameter("liczba2");
String operacja = request.getParameter("operacja");
if(parametr1 != null && parametr2 != null && operacja != null) {
try {
long liczba1 = Long.parseLong(parametr1);
long liczba2 = Long.parseLong(parametr2);
long wynik = LogikaKalkulatora.oblicz(liczba1, liczba2, operacja);
out.printf("<p>%d %s %d = <strong>%d</strong></p>", liczba1, operacja, liczba2, wynik);
String tekst = String.format("%d %s %d = %d", liczba1, operacja, liczba2, wynik);
historiaStatyczna.add(tekst);
historiaGlobalna.add(tekst);
historiaKlienta.add(tekst);
} catch (NumberFormatException e) {
out.printf("<div class='error'>Niepoprawny format liczby %s</div>", e.getMessage());
} catch (Exception e) {
out.printf("<div class='error'>Inny wyjątek %s</div>", e);
}
}
out.println("<h3>Historia działań (static):</h3>");
out.println("<ul>");
// Gdy na liście wykonujemy wiele operacji, np. w pętli, to powinniśmy synchronizować cały ten fragment.
synchronized(historiaStatyczna) {
for (String dzialanie : historiaStatyczna) {
out.println("<li>" + dzialanie + "</li>");
}
}
out.println("</ul>");
out.println("<h3>Historia działań (ServletContext):</h3>");
out.println("<ul>");
synchronized(historiaGlobalna) {
for (String dzialanie : historiaGlobalna) {
out.println("<li>" + dzialanie + "</li>");
}
}
out.println("</ul>");
out.println("<h3>Historia działań klienta (HttpSession):</h3>");
out.println("<ul>");
synchronized(historiaKlienta) {
for (String dzialanie : historiaKlienta) {
out.println("<li>" + dzialanie + "</li>");
}
}
out.println("</ul>");
out.println("</body>");
out.println("</html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
\ No newline at end of file
package kalkulator;
import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Kalkulator9")
public class Kalkulator9 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Tylko wyświetl formularz - po stronie Javy nie ma żadnej logiki do wykonania
// Przekierowanie obsługi zapytania do innego elementu aplikacji (do serwletu, skryptu jsp, zwykłej strony...)
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/kalkulator_view.jsp");
dispatcher.forward(request, response);
// sterowanie tu wraca - można coś jeszcze zrobić
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Obsługa wypełnionego formularza. Zanim przekażemy sterowanie do skryptu JSP, wcześniej wykonujemy działania "logiki".
String parametr1 = request.getParameter("liczba1");
String parametr2 = request.getParameter("liczba2");
String operacja = request.getParameter("operacja");
if (parametr1 != null && parametr2 != null && operacja != null) {
try {
long liczba1 = Long.parseLong(parametr1);
long liczba2 = Long.parseLong(parametr2);
long wynik = LogikaKalkulatora.oblicz(liczba1, liczba2, operacja);
// Jeśli serwlet chce przekazać jakieś dane do JSP,
// (patrząc bardziej ogólnie: z wcześniejszego etapu obsługi zapytania chcemy coś przekazać do następnego etapu)
// możemy użyć obiektu request, który pełni rolę schowka podobnego do servletContext i HttpSession.
request.setAttribute("wynik", wynik);
String tekst = String.format("%d %s %d = %d", liczba1, operacja, liczba2, wynik);
ServletContext servletContext = this.getServletContext();
List<String> historiaGlobalna = (List<String>) servletContext.getAttribute(ListenerHistorii.HISTORIA_GLOBALNA);
historiaGlobalna.add(tekst);
HttpSession sesja = request.getSession();
List<String> historiaKlienta = (List<String>) sesja.getAttribute(ListenerHistorii.HISTORIA_KLIENTA);
historiaKlienta.add(tekst);
} catch (NumberFormatException e) {
request.setAttribute("error", "Niepoprawny format liczby " + e.getMessage());
} catch (Exception e) {
request.setAttribute("error", String.valueOf(e));
}
}
// Prezekazujemy dalszą obsługę zapytania do innego "zasobu", np. do pliku JSP
RequestDispatcher dispatcher = this.getServletContext().getRequestDispatcher("/kalkulator_view.jsp");
dispatcher.forward(request, response);
}
}
package kalkulator;
public class KalkulatorBean {
private int arg1, arg2;
private String operacja;
public int getArg1() {
return arg1;
}
public void setArg1(int arg1) {
this.arg1 = arg1;
}
public int getArg2() {
return arg2;
}
public void setArg2(int arg2) {
this.arg2 = arg2;
}
public String getOperacja() {
return operacja;
}
public void setOperacja(String operacja) {
this.operacja = operacja;
}
public int getWynik() {
switch(operacja) {
case "+" : return arg1 + arg2;
case "-" : return arg1 - arg2;
case "*" : return arg1 * arg2;
case "/" : return arg1 / arg2;
default : return 0;
}
}
}
package kalkulator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class ListenerHistorii implements HttpSessionListener, ServletContextListener {
public static final String HISTORIA_KLIENTA = "historia_klienta";
public static final String HISTORIA_GLOBALNA = "historia_globalna";
public void sessionCreated(HttpSessionEvent se) {
// Gdy podłączy się nowy klient, jest tworzona nowa sesja, a my do tej sesji
// dodajemy pustą listę "historia_dzialan"
List<String> historia = Collections.synchronizedList(new ArrayList<>());
se.getSession().setAttribute(HISTORIA_KLIENTA, historia);
se.getSession().setMaxInactiveInterval(60);
System.out.println("Do sesji została dodana pusta historia");
}
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("Koniec sesji");
}
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
List<String> historiaGlobalna = Collections.synchronizedList(new ArrayList<>());
servletContext.setAttribute(HISTORIA_GLOBALNA, historiaGlobalna);
}
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("aplikacja kończy się");
List<String> historiaGlobalna = (List<String>) sce.getServletContext().getAttribute(HISTORIA_GLOBALNA);
System.out.println("W sumie wykonano " + historiaGlobalna.size() + " działań");
}
// W serwletach mamy trzy obiekty (tak jakby na trzech poziomach), w których za pomocą setAttribute / getAttribute można przechowywać dane
// ServletContext - dane globalne
// HttpSession - dane sesji, skojarzone z konkretnym klientem
// HttpRequest - dane potrzebne podczas obsługi pojedynczego zapytania
}
package kalkulator;
public class LogikaKalkulatora {
public static long oblicz(long liczba1, long liczba2, String operacja) {
switch(operacja) {
case "+": return liczba1 + liczba2;
case "-": return liczba1 - liczba2;
case "*": return liczba1 * liczba2;
case "/": return liczba1 / liczba2;
default : throw new IllegalArgumentException("Nieznana operacja " + operacja);
}
}
}
package techniczne;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Ello
*/
@WebServlet(asyncSupported = true, urlPatterns = { "/Async" })
public class Asynchroniczny extends HttpServlet {
private static final long serialVersionUID = 1L;
public Asynchroniczny() {
System.out.println("Ello konstr");
}
@Override
public void init() {
System.out.println("Ello init");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
final AsyncContext asyncContext = request.startAsync();
System.out.println("Puszczone");
asyncContext.start(new Runnable() {
public void run() {
try {
PrintWriter out = asyncContext.getResponse().getWriter();
Thread.sleep(1000);
out.println("Jeden");
out.flush();
Thread.sleep(3000);
out.println("Dwa");
out.flush();
Thread.sleep(3000);
out.println("Trzy");
Thread.sleep(1000);
asyncContext.complete();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
package techniczne;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import beans.InfoBean;
@WebFilter("/zakresy_filtr.jsp")
public class FiltrZwiekszajacy implements Filter {
public void init(FilterConfig fConfig) throws ServletException {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("filtr - początek");
InfoBean obiekt = new InfoBean();
obiekt.setLicznik(100);
request.setAttribute("req", obiekt);
// pass the request along the filter chain
chain.doFilter(request, response);
// sterowanie wraca do filtru już po wysłaniu treści z jsp (w tym przypadku)
System.out.println("licznik = " + obiekt.getLicznik());
}
}
package techniczne;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import beans.InfoBean;
@WebListener
public class Listener implements ServletContextListener, HttpSessionListener, ServletRequestListener {
// wykonywane po uruchomieniu aplikacji na serwerze
public void contextInitialized(ServletContextEvent ev) {
System.out.println("start aplikacji");
// dodaję atrybut do kontekstu aplikacji (do "application scope")
InfoBean obiekt = new InfoBean();
obiekt.setLicznik(500);
obiekt.setTekst("servlet context");
ev.getServletContext().setAttribute("licznik-app", obiekt);
}
// wykonywane podczas "kontrolowanego" zamykania aplikacji
public void contextDestroyed(ServletContextEvent ev) {
System.out.println("koniec aplikacji");
}
// gdy jest tworzona nowa sesja
public void sessionCreated(HttpSessionEvent ev) {
System.out.println("utworzenie sesji " + ev.getSession().getId());
// timeout sesji w sekundach
// ev.getSession().setMaxInactiveInterval(60);
InfoBean obiekt = new InfoBean();
obiekt.setLicznik(600);
obiekt.setTekst("sesja");
ev.getSession().setAttribute("licznik-ses", obiekt);
}
public void sessionDestroyed(HttpSessionEvent ev) {
System.out.println("koniec sesji " + ev.getSession().getId());
}
public void requestInitialized(ServletRequestEvent ev) {
System.out.println("przyszedł request");
InfoBean obiekt = new InfoBean();
obiekt.setLicznik(700);
obiekt.setTekst("request");
ev.getServletRequest().setAttribute("licznik-req", obiekt);
}
public void requestDestroyed(ServletRequestEvent ev) {
System.out.println("obsługa requestu zakończona");
}
}
package techniczne;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import beans.InfoBean;
@WebServlet("/Zakresy")
public class Zakresy extends HttpServlet {
private static final long serialVersionUID = 1L;
// Standard nie gwarantuje nam żadnego zachowania jeśli chodzi o zmienne instancyjne w serwletach.
// Nie wiemy kiedy i ile obiektów klasy serwlet będzie tworzył serwer.
// W praktyce zazwyczaj tworzony jest jeden wspólny obiekt dla wszystkich zapytań, ale nie możemy tego zakładać.
private InfoBean instancyjna = new InfoBean();
// Zmienna statyczna będzie istniała do restartu serwera albo redeploy aplikacji.
private static InfoBean statyczna = new InfoBean();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InfoBean lokalna = new InfoBean();
HttpSession sesja = request.getSession();
InfoBean req = (InfoBean) request.getAttribute("licznik-req");
InfoBean ses = (InfoBean) sesja.getAttribute("licznik-ses");
InfoBean app = (InfoBean) getServletContext().getAttribute("licznik-app");
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println("lokalna : " + lokalna.getLicznik());
out.println("instancyjna: " + instancyjna.getLicznik());
out.println("statyczna : " + statyczna.getLicznik());
out.println();
out.println("request : " + req.getLicznik());
out.println("sesja : " + ses.getLicznik());
out.println("aplikacja : " + app.getLicznik());
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dodawanie w JSP</title>
<link rel="stylesheet" type="text/css" href="styl.css">
</head>
<body>
<h1>Dodawanie w JSP</h1>
<form>
<input type="number" name="arg1" value="${param.arg1}">
+
<input type="number" name="arg2" value="${param.arg2}">
<button>=</button>
</form>
<div class="wynik">
Sumą jest: ${param.arg1 + param.arg2}
</div>
</body>
</html>
\ No newline at end of file
...@@ -35,10 +35,32 @@ ...@@ -35,10 +35,32 @@
<li><a href="Kalkulator4">Kalkulator4</a> - zrefaktoryzowany POST</li> <li><a href="Kalkulator4">Kalkulator4</a> - zrefaktoryzowany POST</li>
</ul> </ul>
<h3>Kalkulator z historią</h3>
<ul>
<li><a href="Kalkulator5">Kalkulator 5</a> - historia w zmiennej instancyjnej</li>
<li><a href="Kalkulator6">Kalkulator 6</a> - historia w sesji (inicjalizacja if-em)</li>
<li><a href="Kalkulator7">Kalkulator 7</a> - historia w sesji (inicjalizacja listenerem)</li>
<li><a href="Kalkulator8">Kalkulator 8</a> - historia w sesji i kontekście aplikacji (inicjalizacja listenerem)</li>
<li><a href="Kalkulator9">Kalkulator 9</a> - wersja z <code>forward</code> i widokiem JSP</li>
</ul>
<h3>Przykłady JSP</h3> <h3>Przykłady JSP</h3>
<ul> <ul>
<li><a href="przyklad.jsp">przyklad.jsp</a></li> <li><a href="przyklad.jsp">przyklad.jsp</a></li>
<li><a href="przyklad.jsp?imie=Ala&liczba1=12&liczba2=13">przyklad.jsp</a> z parametrami</li> <li><a href="przyklad.jsp?imie=Ala&liczba1=12&liczba2=13">przyklad.jsp</a> z parametrami</li>
<li><a href="dodaj.jsp">dodaj.jsp</a> - minimalna wersja w czystym JSP (tylko dodawanie)</li>
<li><a href="kalkulator_tylko_jsp.jsp">kalkulator</a> - zrobiony w czystym JSP</li>
<li><a href="kalkulator_bean.jsp">kalkulator bean</a> - wersja z pomocniczą klasą w Javie</li>
</ul>
<h3>Sprawy techniczne</h3>
<ul>
<li><a href="Info">Info</a> - serwlet prezentujący zawartość <code>Request</code>, nagłówki, ciasteczka itp.</li>
<li><a href="Async">Async</a> - serwlet obługujący zapytania asynchronicznie</li>
<li><a href="Zakresy">Zakresy</a> - zakresy zmiennych w serwlecie</li>
<li><a href="zakresy.jsp">zakresy.jsp</a> - zakresy zmiennych w JSP</li>
<li><a href="zakresy_filtr.jsp">zakresy.jsp</a> - zakresy zmiennych w JSP - wersja z filtrem</li>
</ul> </ul>
</body> </body>
......
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Kalkulator w JSP</title>
<link rel="stylesheet" type="text/css" href="styl.css">
</head>
<body>
<h1>Kalkulator w JSP</h1>
<form class="kalkulator" method="post">
<input type="number" name="arg1" value="${param.arg1}">
<select name="operacja">
<c:forEach var="op" items="+,-,*,/">
<c:choose>
<c:when test="${op == param.operacja}">
<option value="${op}" selected="selected">${op}</option>
</c:when>
<c:otherwise>
<option value="${op}">${op}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<input type="number" name="arg2" value="${param.arg2}">
<button style="color:red;font-weight:bold">Oblicz</button>
</form>
<jsp:useBean id="kalkulatorBean" class="kalkulator.KalkulatorBean"/>
<jsp:setProperty name="kalkulatorBean" property="arg1" param="arg1"/>
<jsp:setProperty name="kalkulatorBean" property="arg2" param="arg2"/>
<jsp:setProperty name="kalkulatorBean" property="operacja" param="operacja"/>
<c:if test="${not empty param.operacja}">
<div class="wynik">
${kalkulatorBean.arg1} ${kalkulatorBean.operacja} ${kalkulatorBean.arg2} =
<strong>${kalkulatorBean.wynik}</strong>
</div>
</c:if>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dodawanie w JSP</title>
<link rel="stylesheet" type="text/css" href="styl.css">
</head>
<body>
<h1>Dodawanie w JSP</h1>
<form class="kalkulator" method="post">
<input type="number" name="arg1" value="${param.arg1}">
<select name="operacja">
<c:forEach var="op" items="+,-,*,/">
<c:choose>
<c:when test="${op == param.operacja}">
<option value="${op}" selected="selected">${op}</option>
</c:when>
<c:otherwise>
<option value="${op}">${op}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<input type="number" name="arg2" value="${param.arg2}">
<button style="color:red;font-weight:bold">Oblicz</button>
</form>
<c:if test="${not empty param.operacja}">
<div class="wynik">
${param.arg1} ${param.operacja} ${param.arg2} =
<strong><c:choose>
<c:when test="${param.operacja == '+'}">${param.arg1 + param.arg2}</c:when>
<c:when test="${param.operacja == '-'}">${param.arg1 - param.arg2}</c:when>
<c:when test="${param.operacja == '*'}">${param.arg1 * param.arg2}</c:when>
<c:when test="${param.operacja == '/'}">${param.arg1 / param.arg2}</c:when>
</c:choose></strong>
</div>
</c:if>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Kalkulator w JSP</title>
<link rel="stylesheet" type="text/css" href="styl.css">
</head>
<body>
<h1>Kalkulator w JSP</h1>
<form class="kalkulator" method="post">
<input type="number" name="liczba1" value="${param.liczba1}">
<select name="operacja">
<c:forEach var="op" items="+,-,*,/">
<c:choose>
<c:when test="${op == param.operacja}">
<option value="${op}" selected="selected">${op}</option>
</c:when>
<c:otherwise>
<option value="${op}">${op}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
<input type="number" name="liczba2" value="${param.liczba2}">
<button style="color:red;font-weight:bold">Oblicz</button>
</form>
<%-- Obiekty zapisane w ServletContext, HttpSession i HttpRequest są dostępne "tak po prostu" poprzez ${expression language} --%>
<c:if test="${not empty wynik}">
<div class="wynik">
${param.liczba1} ${param.operacja} ${param.liczba2} = <strong>${wynik}</strong>
</div>
</c:if>
<h3>Historia globalna</h3>
<ul>
<%-- Nazwy historia_globalna i historia_klienta muszą być dokładnie takie, jak stałe zdef. w ListenerHistorii --%>
<c:forEach var="dzialanie" items="${historia_globalna}">
<li>${dzialanie}</li>
</c:forEach>
</ul>
<h3>Historia klienta</h3>
<ul>
<c:forEach var="dzialanie" items="${historia_klienta}">
<li>${dzialanie}</li>
</c:forEach>
</ul>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rozmowa JSP</title>
</head>
<body>
<h1>Rozmowa JSP</h1>
<form>
<label for="imie">Jak masz na imię?</label>
<input type="text" name="imie">
<button>Wyślij</button>
</form>
<p>Witaj ${param.imie}!</p>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Zakresy</title>
</head>
<body>
<h1>Zakresy zmiennych</h1>
<p>Wersja bez filtru.</p>
<p>Odświeżaj stronę i zobacz, które zmienne się zmieniają. Działanie seji można sprawdzić otwierając inną przeglądarkę lub profil prywatny.</p>
<jsp:useBean id="domyslnie" class="beans.InfoBean"/>
<jsp:useBean id="strona" class="beans.InfoBean" scope="page"/>
<jsp:useBean id="req" class="beans.InfoBean" scope="request"/>
<jsp:useBean id="sesja" class="beans.InfoBean" scope="session"/>
<jsp:useBean id="app" class="beans.InfoBean" scope="application"/>
<h2>Domyślnie</h2>
<p>${domyslnie.licznik}</p>
<p>${domyslnie.licznik}</p>
<h2>Page</h2>
<p>${strona.licznik}</p>
<p>${strona.licznik}</p>
<h2>Request</h2>
<p>${req.licznik}</p>
<p>${req.licznik}</p>
<h2>Session</h2>
<p>${sesja.licznik}</p>
<p>${sesja.licznik}</p>
<h2>Application</h2>
<p>${app.licznik}</p>
<p>${app.licznik}</p>
</body>
</html>
\ No newline at end of file
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Zakresy</title>
</head>
<body>
<h1>Zakresy zmiennych</h1>
<p>Zawartość ta sama co <code>zakresy.jsp</code>, ale ten adres przechodzi przez filtr.</p>
<p>Odświeżaj stronę i zobacz, które zmienne się zmieniają. Działanie seji można sprawdzić otwierając inną przeglądarkę lub profil prywatny.</p>
<jsp:useBean id="domyslnie" class="beans.InfoBean"/>
<jsp:useBean id="strona" class="beans.InfoBean" scope="page"/>
<jsp:useBean id="req" class="beans.InfoBean" scope="request"/>
<jsp:useBean id="sesja" class="beans.InfoBean" scope="session"/>
<jsp:useBean id="app" class="beans.InfoBean" scope="application"/>
<h2>Domyślnie</h2>
<p>${domyslnie.licznik}</p>
<p>${domyslnie.licznik}</p>
<h2>Page</h2>
<p>${strona.licznik}</p>
<p>${strona.licznik}</p>
<h2>Request</h2>
<p>${req.licznik}</p>
<p>${req.licznik}</p>
<h2>Session</h2>
<p>${sesja.licznik}</p>
<p>${sesja.licznik}</p>
<h2>Application</h2>
<p>${app.licznik}</p>
<p>${app.licznik}</p>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment