views:

313

answers:

2

I want to create a JSP page or servlet that will work in 2 ways.

A user visits their own profile page:

http//something.com/profile/

Or they visit their friends page:

http://something.com/profile/FriendsName

They could also visit their own page through an explicit URL like: http://something.com/profile/YourName

I have a servlet-mapping setup as follows to map any requests to /profile to my JSP that will handle that request.

  <servlet>
          <servlet-name>Profile</servlet-name>
          <jsp-file>/profile.jsp</jsp-file>
  </servlet>

  <servlet-mapping>
    <servlet-name>Profile</servlet-name>
    <url-pattern>/profile</url-pattern>
  </servlet-mapping>

Then I was thinking I could setup a filter that will parse the HTTPServletRequest's URL to read after the /profile/.

  <filter>
    <filter-name>profile-filter</filter-name>
    <filter-class>ProfileFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>profile-filter</filter-name>
    <url-pattern>/profile*</url-pattern>
  </filter-mapping>

Now the filter could set attributes in the HttpServletRequest, how would i go about pulling those out in the JSP page to check if a user name was specified and check if your own name was set?

How would I go about creating a page scoped bean in the ServletFilter so I could use in the JSP page using jspBean like this:

<jsp:useBean id="profileInfo" scope="page" class="ProfileInfo" />
A: 

I'm not completely following the question, but if you want a jsp to access request parameters or attributes, just do:

<%
  String parameter = request.getParameter("parameter");
  String attribute = request.getAttribute("attribute");

%>

You can also get access to the request url, etc... if you need to do anything with those.

Personally, I'd recommend that you use a servlet to handle your requests, and forward to the jsp of your choosing (possibly after setting session information that the jsp can use).

Using server level filters and request attributes for this kind of thing may be a bit overkill, but only you know your project's true requirements.

Kevin Day
+1  A: 

I think a filter only serves to artificially break the logic apart. You can very easily determine the value of the portion of the URL that doesn't match the url-pattern described in the web.xml. The HttpServletRequest class has a method that returns this value for you, it's called getPathInfo(). Here's an example:

<%
   String path = request.getPathInfo();
   if (path == null || "".equalsIgnoreCase(path)) {
      // The path was empty, display the current user's profile
   } else {
      // Display the named profile
   }
%>

This doesn't help you at all with the request beans, but I think it helps with the design.

Bryan Kyle
I think a filter would also be appropriate if you have multiple servlets or JSP's (profile, blog, photos etc) that need to do the same processing (pull out the user's ID from the Requests getPath()
Dougnukem