Archive

Archive for the ‘JAVA EE’ Category

Getting a Request Parameter Using JSTL in a JSP Page

Thursday, 17 February, 2011 Leave a comment

When using the JSTL’s expression language (see Enabling the JSTL Expression Language in a JSP Page), the request parameters are made available in the implicit object param. This example demonstrates how to include the value of a request parameter from the query string or posted data in the generated output:

<%-- Declare the core library --%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>

<c:choose>
    <c:when test="${empty param.name}">
        Please enter your name.
    </c:when>
    <c:otherwise>
        Hello <b><c:out value="${param.name}" /></b>!
    </c:otherwise>
</c:choose>

If the page was accessed with the URL:
http://hostname.com/mywebapp/mypage.jsp?name=UserName
the resulting output would be:
Hello UserName!

Advertisements
Categories: jsp Tags: , ,

Getting a Request Parameter in a Servlet

Monday, 31 January, 2011 Leave a comment

In a GET request, the request parameters are taken from the query string (the data following the question mark on the URL). For example, the URL http://hostname.com?p1=v1&p2=v2 contains two request parameters – – p1 and p2. In a POST request, the request parameters are taken from both query string and the posted data which is encoded in the body of the request. This example demonstrates how to get the value of a request parameter in either a GET or POST request.

// See also The Quintessential Servlet

// This method is called by the servlet container to process a GET request.
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

// This method is called by the servlet container to process a POST request.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    doGetOrPost(req, resp);
}

// This method handles both GET and POST requests.
private void doGetOrPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the value of a request parameter; the name is case-sensitive
    String name = "param";
    String value = req.getParameter(name);
    if (value == null) {
        // The request parameter 'param' was not present in the query string
        // e.g. http://hostname.com?a=b
    } else if ("".equals(value)) {
        // The request parameter 'param' was present in the query string but has no value
        // e.g. http://hostname.com?param=&a=b
    }

    // The following generates a page showing all the request parameters
    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // Get the values of all request parameters
    Enumeration enum = req.getParameterNames();
    for (; enum.hasMoreElements(); ) {
        // Get the name of the request parameter
        name = (String)enum.nextElement();
        out.println(name);

        // Get the value of the request parameter
        value = req.getParameter(name);

        // If the request parameter can appear more than once in the query string, get all values
        String[] values = req.getParameterValues(name);

        for (int i=0; i<values.length; i++) {
            out.println("    "+values[i]);
        }
    }
    out.close();
}

w3

Categories: JAVA EE Tags: , , ,

How to get information about user using Servlet

Friday, 21 January, 2011 1 comment

The method getRemoteUser() of the HttpServletRequest gives the username of the client. With the remote user’s name, a servlet can save information about each client. Over the long term, it can remember each individual’s preferences. For the short term, it can remember the series of pages, viewed by the client and use them to add a sense of state to a stateless HTTP protocol.

A simple servlet that uses getRemoteUser() can greet its clients by name and remember when each last logged in as shown in the example below:

import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PersonalizedWelcome extends HttpServlet{
    
    Hashtable accesses = new Hashtable();
    
    public void doGet(HttpServletRequest req,HttpServletResponse res)
            throws ServletException,IOException{
        
        res.setContentType("text/plain");
        PrintWriter out= res.getWriter();
        
        // Some introductory HTML...
        String remoteUser = req.getRemoteUser();
        
        // See if the client is allowed
        if(remoteUser == null){
            out.println("Welcome");
        } else{
            out.println("Welcome " + remoteUser + "!");
            Date lastAccess = (Date)accesses.get(remoteUser);
            if(lastAccess==null){
                out.println("This last visit was "  + accesses.get(remoteUser));
            }
            if(remoteUser.equals("Rohit")){
                out.println("Shall we play  a game");
            }
            accesses.put(remoteUser, new Date());
        }
        
        //continue handling the request
    }
}

The following HttpServletRequest interface methods are also available to access security information about the component’s caller:

getRemoteUser: This method is called to get the user name with which the client authenticated. It returns the name of remote user associated by the container with the request. If no user has been authenticated, the method returns null.
isUserInRole: This method determines whether a remote user is in a specific security role. If no user has been authenticated, it returns false. This method expects a String user role-name parameter. The security-role-ref element should be declared in the deployment descriptor with a role-name sub-element containing the role name to be passed to the method.
getUserPrincipal: The getUserPrinicipal method is called to determine the principal name of the current user and returns a java.security.Principal object. If no user has been authenticated, it returns null. Calling the getName method on the Principal returned by getUserPrincipal returns the name of the remote user.

getRemoteUser() [java.lang.String]
Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated.

isUserInRole(String role) [boolean]
Returns a boolean indicating whether the authenticated user is included in the specified logical “role”.

getUserPrincipal() [java.security.Principal]
Returns a java.security.Principal object containing the name of the current authenticated user

1 w3
2 w3
3 w3

Categories: JAVA EE, secure Tags: ,