Dynamically include files in JSP

This is a good example to dynamically include a header file in JavaServer Pages (JSP):

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JSP Page</title>
  </head>
  <body>        
  <c:set var="userAgent" scope="page" value="${header['User-Agent']}"/>
  <c:choose>
    <c:when test="${fn:contains(userAgent,'iPhone')}">
      <%@include file="header_iphone.jsp" %>
    </c:when>
    <c:when test="${fn:contains(userAgent,'iPad')}">
      <%@include file="header_ipad.jsp" %>
    </c:when>
    <c:when test="${fn:contains(userAgent,'Android')}">
      <%@include file="header_android.jsp" %>
    </c:when>
    <c:otherwise>
      <%@include file="header_other.jsp" %>
    </c:otherwise>
  </c:choose>
</body>
</html>

Get user agent in JSP

This is how you can show the user agent in JavaServer Pages (JSP):

Version 1

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JSP Page</title>
  </head>
  <body>
    <%
      String userAgent = request.getHeader("user-agent");
      out.print(userAgent);
    %>
  </body>
</html>

Version 2

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JSP Page</title>
  </head>
  <body>
    <%
      String userAgent = request.getHeader("user-agent");
    %>
    <%= userAgent %>
  </body>
</html>

Version 3

<%@taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JSP Page</title>
  </head>
  <body>
  <c:out value="${header['User-Agent']}" />
</body>
</html>

Version 4

<%@taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JSP Page</title>
  </head>
  <body>
  <c:set var="userAgent" scope="page" value="${header['User-Agent']}"/>
  <c:out value="${userAgent}" />
</body>
</html>

Version 5

<%@taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>JSP Page</title>
  </head>
  <body>
  <c:set var="userAgent" scope="page" value="${header['User-Agent']}"/>
  <%=pageContext.getAttribute("userAgent")%>
</body>
</html>

Java Server Pages – Beispiel

Es folgt ein Beispiel zur Erstellung einer Java Server Page (kurz JSP).

Die Java Server Page wird durch ein Servlet (im Beispiel NewServlet.java) aufgerufen. Daher muss im Webbrowser auch die Adresse des Servlets eingegeben werden. Als Parameter wird dabei das gewünschte Command mit einer dazugehörigen Action ausgeführt.

Im Beispielaufruf heißt das Command „cmd“ und die Action „actionman“:
http://localhost:8080/Projekt/servlet?do=actionman

Quellcode:

Projektname > „Source Packages“ > controller.web > NewServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package controller.web;
 
import java.util.HashMap;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
 
@WebServlet(name="NewServlet", urlPatterns={"/servlet"})
public class NewServlet extends HttpServletControllerBase
{
    public void init(ServletConfig conf) throws ServletException
    {
        HttpRequestActionBase action = null;
        actions = new HashMap();
 
        // Action: Möglicher Wert (Value) für einen Steuerbefehl (Command)
        action = new MyAction();
        actions.put("actionman", action);
 
        // Weitere "action" erstellen und "actions" hinzufügen...
    }
 
    protected String getOperation(HttpServletRequest req)
    {
        // Command: Steuerbefehl
        return req.getParameter("do");
    }
}

Projektname > „Source Packages“ > controller.web > MyAction.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package controller.web;
 
import java.io.IOException;
import javax.servlet.RequestDispatcher;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class MyAction extends HttpRequestActionBase
{
    public void perform(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException
    {
        try
        {
            String strTemp = "Willkommen auf der JSP-Seite.";
            req.setAttribute("willkommen", strTemp);
            RequestDispatcher reqDisp = req.getRequestDispatcher("showaction.jsp");
            reqDisp.forward(req, resp);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Projektname > „Web Pages“ > showaction.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<%@page contentType="text/html" 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>JSP Page</title>
    </head>
    <body>
        <!-- Variante 1 -->
        <h1><%=request.getAttribute("willkommen")%></h1>
        <!-- Variante 2 -->
        <h1>${hallo}</h1>
    </body>
</html>

Benötigte Ressourcen:
Projektname > „Source Packages“ > controller.web > HttpServletControllerBase.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package controller.web;
 
import java.io.IOException;
import java.util.HashMap;
 
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public abstract class HttpServletControllerBase extends HttpServlet
{
	protected HashMap actions;
 
	public void init(ServletConfig conf) throws ServletException
        {
            HttpRequestActionBase action = null;
            actions = new HashMap();
	}
 
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException
        {
	    String op = getOperation(req);
	    HttpRequestActionBase action = (HttpRequestActionBase)actions.get(op);
	    action.perform(req, resp);
	}
 
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException
        {
 
	    // Zunaechst wird die URL analysiert,
            // um die Operation, die ausgefueht werden soll zu bestimmen
	    String op = getOperation(req);
	    // dann wird die entsprechende Aktion aus der Map geholt ...
	    HttpRequestActionBase action = (HttpRequestActionBase)actions.get(op);
	    // ... und angestossen
	    action.perform(req, resp);
	}
 
	/** Methode muss noch definiert werden, um die Kennung der
	  * Operation aus der URL zu lesen
	  * @param req Http-Request
	  * @return Name der Aktion, die ausgefuehrt werden soll
	  */
	protected abstract String getOperation(HttpServletRequest req);
}

Projektname > „Source Packages“ > controller.web > HttpRequestActionBase.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package controller.web;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public abstract class HttpRequestActionBase
{
    public abstract void perform(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException;
 
    protected void forward(HttpServletRequest req, HttpServletResponse resp, String forwardName)
    throws ServletException, IOException
    {
        RequestDispatcher reqDis = req.getRequestDispatcher(forwardName);
        reqDis.forward(req, resp);
    }
}