Page redirecting in a web application at server side
Java EE has Filters which run in every request. All request to firstwebsite.com
will be handled ,first in the code, by a filter then redirected to secodnwebsite.com
.
public class RedirectionFilter implements Filter {
/**
* Default constructor.
*/
public RedirectionFilter () {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String servletPath = request.getServletPath();
if (servletPath.endsWith(".html")) {
response.sendRedirect("http://secondwebsite.com" + servletPath);
}
else {
chain.doFilter(request, response);
}
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
Do not forget to add this filter to deployment descriptor (web.xml). Put it to first order if you have another filters so that this filter runs first.
<filter>
<display-name>RedirectionFilter</display-name>
<filter-name>RedirectionFilter</filter-name>
<filter-class>your.package.RedirectionFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RedirectionFilter</filter-name>
<servlet-name>Servlet which firstwebsite.com run</servlet-name>
</filter-mapping>
See also
Patan
Updated on June 04, 2022Comments
-
Patan almost 2 years
I have two websites say
1. firstwebsite.com 2. secondwebsite.com
All the pages in firstwebsite are static. Now I want to move all pages in firstwebsite.com to secondwebsite.com. I want to shutdown all servers of firstwebsite.com
I also want to make sure that when the URL firstwebsite.com/** should redirect to secondwebsite.com/**
firstwebsite.com/abc.html should redirect to secodnwebsite.com/abc.html
I am using springs. Can some one guide me how to do it. Later I also want to do some processing based on device from which request is sent.
It would be really great if I can get some references for above.
-
Patan over 10 yearsThank you for the response. As I said I will be placing all the pages in firstwebsite into secondwebsite.com. And I will be closing the firstwebsite. Ideally it is a virtual path which does not exist any more. DO I need to make any changes in apache servers.
-
erencan over 10 yearsWhen you placing pages in firstwebside, do not remove the files, because if there is no requested page you will get 404 before filter runs. There is no need any changes in apache servers for my solution, just add the filter then it redirect pages to new domain.