macbert
macbert

Reputation: 798

redirect from http to https and back to http within java servlet

there are a bunch of links accessing my servlet without https
As the servlet is a generic form and the http urls are generated with an random id it is difficult to use modrewrite or something like that.

Therefore I modified my servlet with code like that:

//redirect to https
        String sec = servletRequest.getParameter("Sec");
        String qString = servletRequest.getQueryString();

        if (StringUtils.isEmpty(sec)){
              try {
                    HttpServletResponse rsp = request.getServletResponse(true);


                         String PORTAL_URL = l_aliasHelper.getPath(request);


              rsp.sendRedirect("https://"+servletRequest.getServerName() +PORTAL_URL+"?" +qString+"&Sec=yes");
              } catch (Exception e) {
              e.printStackTrace();
              }

        }

Now this works fine!

But, what if I want back to http because I want to avoid nagging warnings about insecure elements on other pages.

So how do I redirect to http again after the user has submitted the form?

If everything worked well the user gets displayed a response with a success message under the same URL he started.

So the cycle goes like this: 
http://<somedomain>/<anypath>?<anyid>
https://<somedomain>/<anypath>?<anyid>&Sec=yes
and now it should go back maybe with a step inbetween to
http://<somedomain>/<anypath>?<anyid> <- the success message should be
displayed here

the last method before the message is displayed is
sucessmessage.render(request,response)

request and response are both appserver component specific views on all request / response related matters. They have methods like:

getServletResponse

public HttpServletResponse getServletResponse(boolean answering)

Gets the original servlet response. Note: This should be accessed

in extraordinary cases only. If the parameter is set to true all further content procession of the runtime will be skipped. This is only available, if the request was initiated from a servlet based connection.

So how can the response be manipulated in a way that the form is submitted secure, but the user can go on with http on the rest of the site afterwards.

Upvotes: 1

Views: 8111

Answers (1)

AngerClown
AngerClown

Reputation: 6229

It seems like you are trying to do too much in one place. Maybe the following break down will be easier:

  • Specify https in the URL for the action parameter in HTML form.
  • Create a ServletFilter class that uses ServletRequest.isSecure() to make sure that requests to your form action actually came in over https. This could also be in your action servlet, but making it a filter means you can reuse it. Just make sure the secure servlets have this filter set.
  • In your form action servlet, simply send a redirect to the success page over http

Upvotes: 1

Related Questions