B4J Question WebServer filtering

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am using the web server sample (https://www.b4x.com/android/forum/threads/server-building-web-servers-with-b4j.37172/#content)

What I am trying to do is load the web page which is working but I want to be able to add things in the webpage such as $test and then get the B4J app to replace $test with something else such as 'hello world' which my B4J app will do.

In my Main Module I have added the following line of code in the AppStart sub:

B4X:
srvr.AddHandler("/*", "HTMLFilter", False)

I then added a Class Module called 'HTMLFilter'.

In my HTMLFilter module I have the following code:

B4X:
'Class module
Sub Class_Globals
    Private mreq As ServletRequest 'ignore
    Private mresp As ServletResponse 'ignore
  
    Private templates As Map
  
End Sub

Public Sub Initialize
    templates.Initialize
End Sub

Sub Handle(req As ServletRequest, resp As ServletResponse)
    Try
      
        Log(req.RequestURI) 'handle the request based on the URL
      
        If req.RequestURI.EndsWith("html") Then
            HandleMainPage (resp, req.RequestURI)
        End If
      
    Catch
  
        resp.Status = 404
        resp.ContentType = "text/html"
        Log("Error serving request: " & LastException)
        resp.Write("<h1><b>Error serving request</b></h1><br>Error: " & LastException)
    End Try

End Sub

' Will replace values on the page and will then send it to the user in the browser
' Response = resp
' Page = page name including file extension, For Example: index.html
'<code>HandleMainPage(resp,"index.html")</code>
Sub HandleMainPage (Response As ServletResponse, page As String)
  
    Dim MainPage As String = GetTemplate(page) 'load the template from the assets folder - ** All web pages should be in the 'www' folder **
    MainPage = MainPage.Replace("$test$", "Hello World")
  
    Response.ContentType = SetContentType(page)
    Response.Write(MainPage)
End Sub

Sub GetTemplate(Name As String) As String
    If templates.ContainsKey(Name) Then Return templates.Get(Name)
    Dim temp As String = File.ReadString(File.DirApp & "/www/", Name)
    templates.Put(Name, temp)
    Return temp
End Sub

Sub SetContentType(FileName As String)
    Dim extension, ContentType As String
    Dim m As Matcher = Regex.Matcher("\.([^\.]*)$", FileName) 'find the file extension
    If m.Find Then
        extension = m.Group(1).ToLowerCase
        Log(extension)
        Select extension
            Case "html", "htm"
                ContentType = "text/html"
            Case "js"
                ContentType = "text/javascript"
            Case "gif", "png"
                ContentType = "image/" & extension
            Case "jpeg", "jpg"
                ContentType = "image/jpeg"
            Case "css", "xml"
                ContentType = "text/" & extension
            Case "ico"
                ContentType = "image/vnd.microsoft.icon"
            Case "txt"
                ContentType = "text/plain"
            Case "logfile"
                ContentType = "application/octet-stream"
              
            Case Else
                ContentType = "application/octet-stream"
        End Select
        Return ContentType
    End If
End Sub

My HTML page I have in the www folder is:

index.html
HTML:
<img src="images/logo.png" width=100 height=100><br>
<b>Hello this is a test!!!</b><br>
$test

The problem I have is the page loads and replaces the text on the screen (eg. $test is replaced with 'hello world') which is fine but the image on the screen doesn't display.

If I then remove the following line from the main module

B4X:
srvr.AddHandler("/*", "HTMLFilter", False)

It then works but the text is not replaced (eg. $test doesn't get replaced with 'Hello World').

How can I make it replace the text on the page but also allow the rest of the page to load as well?
 

billzhan

Active Member
Licensed User
Longtime User
our code is similar to the demo of B4A (android) httpserver.

Code of B4J server hello world demo (the link in your post):

B4X:
Sub Handle(req As ServletRequest, resp As ServletResponse)
    mreq = req
    mresp = resp
    Dim start As Long = DateTime.Now
    resp.ContentType = "text/html"
    resp.Write("<img src='images/logo.png'/ width=100 height=100><br/>") 'this file will be loaded from the www folder
    resp.Write("<b>Hello world!!!</b><br/>")
    resp.Write("Your ip address is: " & req.RemoteAddress & "<br/>")  
    resp.Write("The time here is: " & DateTime.Time(DateTime.Now)).Write("<br/>")
    resp.Write("It took: ").Write(DateTime.Now - start).Write(" ms to create this page.<br/>")
    resp.Write("<a href='/'>Back</a>")
End Sub

If your are using B4J server:
1. You used a wildcard for every request to the server (including images/logo.png), the logo was not returned properly.
B4X:
srvr.AddHandler("/*", "HTMLFilter", False)

2. You should start with B4J server demo.
Use resp.Write("html contents") to return html contents.
B4X:
   Dim htmlstring As String ="hello world $test$"
   htmlstring=htmlstring.replace("$test$","YourContents")
   resp.Write("<html><body>")
   resp.Write(htmlstring)
   resp.Write("</body></html>")
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Thanks for your reply..

I ended up putting a folder called 'pages' and another folder called 'img' in the 'www' folder. All my HTML files are stored in the 'pages'.
I then put all my images in the 'img' folder.

Then in my HTML page I am pointing the image to the img folder.

I then changed:

B4X:
srvr.AddHandler("/*", "HTMLFilter", False)
To
B4X:
srvr.AddHandler("/pages/*", "HTMLFilter", False)

Now it works just like what I wanted. Well kind of like what I wanted. I wanted all the webpages in the root dir (www folder) but for now I will need to put all my pages in the 'pages' folder.
 
Upvote 0

aaronk

Well-Known Member
Licensed User
Longtime User
Yeah that's where my files are kept.
www/pages/

I have been playing around with it today and I now have it working the way I want it to.
I am still learning and playing around with it, but so far everything seems to be working fine.
 
Upvote 0
Top