Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Friday, September 4, 2026

JavaScript: How to Open a New Browser Window Using window.open()

Some times its an useful job to create a window with a new requirement. But , when we are in development room/area , we always remember any search engine to fine the solutions for any type of problem. Even I , also  following some of the search engine. 

But, it is a fact that I am always try to avoid this type of habits. Be , traceable  for finding any solution. This article is one of the mail memory & also my teaching my myself , that don't guess any coding is normal and easy , so don't remember.


So, below the topic:- code line put inside script tag
window.open('','','left=0,top=0,width=1000,height=780,toolbar=0,scrollbars=0,status=0');

You can also use:

window.open();
 
All parameters are not mandatory  to put with values. If you don't need any scrollbar, toolbar, status bar then you can put 0 as the value here, either put 1. 


How to Set Print Area in JSP/HTML Page for Printing

This is one the interesting topic related to print the specific data from a jsp/html page. Directly to printer, without other browser data. I have done a quite obvious way in javascript for set the print area for printing. I faced this problem in my development team with me, for set a specific area for print.

Caution:-  Use of JavaScript may not be  always acceptable, due to client. If user/client disable the script setting in browser these may not work properly. But, every browsers are support script by default.  

As we know, window.print() is used for print in JavaScript. There are so many ways to do a printing task in jsp/html page. Out of all I have mentioned 2 process below with advantage & disadvantage.  Put the below function in script area of your page:-

Procedure-1
function setDivPrint(val){
var printdata=document.getElementById('printarea').innerHTML;
var srcOriginalContent=document.body.innerHTML;
document.body.innerHTML=printdata;
window.print();
document.body.innerHTML=
srcOriginalContent;
}
Here ‘printarea ‘ is the id of printable div. It has some limitation, with getting the cancel button click event and some more. I am not mentioning all here. But in procedure-2 is so eminent than procedure-1.

Procedure-2

function setDivPrint(val){
var printdata=document.getElementById('printarea').innerHTML;
var printwindow=window.open('','','left=0,top=0,width=1000,height=780,toolbar=0,scrollbars=0,status=0');
printwindow.document.write(printdata);
printwindow.document.close();
printwindow.focus();
printwindow.print();
printwindow.close();
}

Here ‘printarea ‘ is the id of printable div. .This method is recommended to use. In this method no need to get the cancel or print button event. Suppose the user click on cancel, then the main original page should come, but it may not coming with the Procedure-1 . So, No need to face this problem in Procedure-2.


Java: Prevent Browser Back After Logout

How to Prevent Browser Back After Logout

I found many problems and questions related to logout/signout. One common problem is that after logout, the browser's Back button allows the user to go back to a previously visited page.

Once a user logs out, they should not be able to access the previously logged-in page without logging in again.

To avoid this problem, we can prevent the browser from using cached copies of protected pages and check whether the user's session is still valid.

Steps

1. Invalidate the Session

When the user logs out, invalidate the session:

session.invalidate();

This removes the session and its associated attributes.

Note: If the application uses other session attributes that must remain available, do not invalidate the session without considering the application's session design. In a normal login/logout flow, however, invalidating the authenticated session is the preferred approach. 

2. Set Cache-Control Headers on Protected Pages

Set the following headers on pages that contain protected information:

// Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control", "no-cache");

// Prevents the response from being stored in the cache
response.setHeader("Cache-Control", "no-store");

// Causes the cached response to be considered expired
response.setDateHeader("Expires", 0);

// HTTP 1.0 backward compatibility
response.setHeader("Pragma", "no-cache");

You can also combine the Cache-Control directives:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setDateHeader("Expires", 0);
response.setHeader("Pragma", "no-cache");

3. Check the Session Before Showing the Page

Before displaying a protected page, check whether the user is logged in.

For example:

Object facultyList = session.getAttribute("facultyList");

if (facultyList == null) {
    response.sendRedirect("index.jsp");
    return;
}

// Continue with the normal page processing

This ensures that the application checks the user's session on the server before allowing access to the protected page.

Important Note

The browser's Back button cannot be disabled from a Java/JSP application.

The purpose of these steps is different: after logout, the application should no longer allow access to protected resources, and appropriate cache-control headers help prevent previously viewed protected content from being reused from the browser cache.

For larger applications, authentication checks are usually better handled centrally using a Servlet Filter or a security framework rather than repeating the session check in every JSP page.


Java: Sending Data from JSP to Servlet

Sending Data from Jsp to Servlet or Communication between Jsp & Servlet , we need certain things like
  • A JSP File
  •  Deployment Descriptor (web.xml)
  • A Servlet File (Normal Java File)

Jsp File (index.jsp)
<form action="test1" method="get">
    <label>Name:</label>
    <input type="text" name="txtname">
    <input type="submit" value="Submit">
</form>




Servlet File (test1.java)

Note: In this example, the form uses the GET method, so the Servlet handles the request in doGet(). If the form uses POST, the Servlet should generally handle it in doPost(). The service() method is responsible for dispatching HTTP requests to methods such as doGet() and doPost(), so application code normally overrides doGet() or doPost() rather than overriding service() directly.

import java.io.IOException;
import java.io.PrintWriter;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/test1")
public class Test1 extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");

        String name = request.getParameter("txtname");

        PrintWriter out = response.getWriter();
        out.println("<h2>Hi, I am " + name + "</h2>");
    }
}

Alternative: Using web.xml

Instead of using @WebServlet, the Servlet can be mapped using the web.xml deployment descriptor. This approach is common in older Java EE applications and is still supported.

<servlet> <servlet-name>test1</servlet-name> <servlet-class>Test1</servlet-class> </servlet> <servlet-mapping> <servlet-name>test1</servlet-name> <url-pattern>/test1</url-pattern> </servlet-mapping>

The url-pattern defines the URL path used to access the Servlet. In this example, the JSP form uses action="test1", which corresponds to the /test1 Servlet mapping.



Note: In web.xml url-pattern is the path for browser ,so any name can be used (not /test1). we need & tag for run & map a servlet to the path. But, Url-pattern must match with the form action .

Legacy Java EE note: If you are working with an older application running on Tomcat 9 or earlier, you may see imports such as javax.servlet.http.HttpServlet. Tomcat 10 and later use jakarta.servlet.http.HttpServlet, so applications may require migration when moving from Tomcat 9 to Tomcat 10+