Removing Empty Lines and whitespaces genereted by JSP

I have been working on a JSP page which was generating emtpy lines & extra whitespaces. I found an Oracle’s document mentioning about this issue.

Here’s what document says

“White space included in the template text of JSP pages is preserved by default. This can have undesirable effects. For example, a carriage return added after a taglib directive would be added to the response output as an extra line. If you want to eliminate the extra white space from the page, you can add a trim-directive-whitespaces element to a jsp-property-group element in the deployment descriptor and set it to true.”

There are two ways in which this issue can be solved.

 

  1. Insert the following directive in your JSP file
<%@ page trimDirectiveWhitespaces="true" %>

 

2.Add the following configuration to your web.xml

<init-param>
    <param-name>trimSpaces</param-name>
    <param-value>true</param-value>
</init-param>

Hope this helps you.

Sample JSP code for a Complete Web Login System

Useful JSP code to implement a secure Login system. You can deploy the below sample JSP code for a Complete Web Login System on any Servlet/JSP container like Tomcat

login.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Login Page</h1>
        <center>
        <%
    if(null!=request.getAttribute("errorMsg"))
    {
        out.print(request.getAttribute("errorMsg"));
    }
        %>
            <form action="Check.jsp" method="post">
           <pre/> <br/>Username:<input type="text" name="username">
            <br/>Password:<input type="password" name="password">
            <br/><input type="submit" value="Submit">
            </form>
        </center>
    </body>
</html>

logout.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
        session.removeAttribute("username");
        session.removeAttribute("password");
        session.invalidate();
        %>
        <h1>You're Successfully Logged out. Redirecting you back to Login page...</h1>
<%      response.sendRedirect("ping.jsp"); %>
        </body>
        </html>

ping.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="refresh" content="120">
<title>URL Monitor</title>
</head>
<body>
<%
if (session.getAttribute("username") == null || session.getAttribute("username").equals(""))
{
//out.print("Error : Unknown Login");
//response.setHeader("Refresh", "5;url=login.jsp");
request.setAttribute("errorMsg","Please enter your Credentials to Login");
request.getRequestDispatcher("login.jsp").forward(request, response);
//response.sendRedirect("login.jsp");
}
<a href="logout.jsp">Logout</a>
//All Stuff for Logged in user goes here
</body>
</html>

Error.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Some Error has occured,Please try again later...</h1>
        <a href="/login.jsp">Click here to Go back and Login again</a>
    </body>
</html>

Check.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
        String username=request.getParameter("username");
        String password=request.getParameter("password");

        if((username.equals("test") && password.equals("test")))
            {
            session.setAttribute("username",username);
            response.sendRedirect("ping.jsp");
            }
        else
            response.sendRedirect("Error.jsp");
        %>
        </body>
        </html>

 

Sample JSP code to Monitor Website URLs

This sample JSP code can be used for monitoring any Simple Web Applications or Websites in your internal network as well as over internet. Just create save it with a .jsp extension (For Example index.jsp) & deploy onto a Tomcat or any other J2EE server.

Following is the sample JSP code to Monitor Website URLs. I have tested it & it works fine. In the following code you need to replace the value of variable “monitor1” with your Domain name or Application URL

<%@page import="java.net.ConnectException"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.net.HttpURLConnection" %>
    <%@ page import="java.net.URL" %>
    <%@ page import="java.io.IOException" %>
    <%@ page import="java.net.HttpURLConnection" %>
    <%@ page import="java.net.URL" %>
    <%@ page import="java.net.Authenticator" %>
    <%@ page import="java.net.PasswordAuthentication" %>
    <%@ page import="java.io.IOException" %>
    <%@ page import="java.text.SimpleDateFormat" %>
<!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">
<meta http-equiv="refresh" content="120">
<title>URL Monitor</title>
</head>
<body>
<%


String monitor1="http://www.serverliving.com/";
HttpURLConnection rmonitor1 = ( HttpURLConnection ) new URL( monitor1 ).openConnection();

String bg="";
SimpleDateFormat time_formatter = new SimpleDateFormat("dd-MM-yyyy::HH:mm");
String current_time_str = time_formatter.format(System.currentTimeMillis());
out.print("<center/><h3>Current Time: "+current_time_str+"</h3>");
out.print("<table align=center border=1>");
out.print("<tr><th>APPLICATION</th><th>URL</th><th>STATUS</th></tr>");

try{
out.print("<tr><td>My Application Name</td>");
out.print("<td>"+monitor1+"</td>");
if(rmonitor1.getResponseCode() == 200){bg="#66ccff";}else{bg="#ff6600";}
out.print("<td bgcolor="+bg+">"+rmonitor1.getResponseCode()+"</td></tr>");
} catch (Exception e) {
        out.print("<td bgcolor=#ff6600>Connection Failed</td>");
}

%>
</body>
</html>

If your monitoring server requires proxy authentication, you can simply add following code for Proxy Authentication

System.getProperties().put("http.proxyHost", "proxyHost.com");
System.getProperties().put("http.proxyPort", "9090");
System.setProperty("https.proxyUser", "Proxy_username");
System.setProperty("https.proxyPassword", "Proxy_password");
Authenticator.setDefault(new Authenticator() {
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestorType() == RequestorType.PROXY) {
            String prot = getRequestingProtocol().toLowerCase();
            String host = System.getProperty(prot + ".proxyHost", "");
            String port = System.getProperty(prot + ".proxyPort", "80");
            String user = System.getProperty(prot + ".proxyUser", "");
            String password = System.getProperty(prot + ".proxyPassword", "");
            if (getRequestingHost().equalsIgnoreCase(host)) {
                if (Integer.parseInt(port) == getRequestingPort()) {
                    return new PasswordAuthentication(user, password.toCharArray());
                }
            }
        }
        return null;
    }
});

Any suggestions or improvments to this code are welcome.