I have a web application which includes few jsp pages. And my home page is welcome.jsp And the Application url is like www.test.com
So, whenever a user hit the url (www.test.com) it redirects to www.test.com/welcome.jsp
now i want if a user directly wants to access any other page like www.test.com/*.jsp it should always redirect to my home page that is www.test.com/welcome.jsp
Kindly give any suggestion on how to do it.
You can add the following mapping to your web.xml:
<servlet>
<servlet-name>welcome</servlet-name>
<jsp-file>welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>*.jsp</url-pattern>
</servlet-mapping>
This will map all requests for a .jsp file to welcome.jsp.
Edit:
If you want to only redirect the users if they haven't already been to the welcome jsp, don't use the code above in your web.xml file. Instead in your jsp set a flag on the user's session in welcome.jsp:
<c:set scope="session" var="sessionStarted" value="true"/>
Then add create Filter to redirect them like this one RedirectFilter.java:
#WebFilter("*.jsp")
public class RedirectFilter implements Filter {
public void destroy() {}
public void init(FilterConfig fConfig) throws ServletException {}
/**
* #see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
Object sessionStarted = ((HttpServletRequest)request).getSession(true).getAttribute("sessionStarted");
if(sessionStarted==null){
request.getServletContext().getRequestDispatcher("welcome.jsp").forward(request, response);
}else{
chain.doFilter(request, response);
}
}
}
Related
Here is how I do i8n with coockies.
I have created a resources bundle and set it in a page.
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setLocale value="${cookie['lang'].value}"/>
<fmt:setBundle basename="messages"/>
I have created a filter
#WebFilter(filterName = "CookieLocaleFilter", urlPatterns = { "/*" })
public class CookieLocaleFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
if (req.getParameter("locale") != null) {
Cookie cookie = new Cookie("lang", req.getParameter("locale"));
res.addCookie(cookie);
}
chain.doFilter(request, response);
}
}
Locale is changed with such a link
<li><fmt:message key="label.lang.en" /></li>
<li><fmt:message key="label.lang.ua" /></li>
The problem: page locale changes only when this link is clicked for 2 times
Let me print out the locale on a page.
<c:out value="${cookie['lang'].value}"/>
When I click the link for the first time - I can see lang=ua in Google chrome cookies immediately, but the page still shows en. If I click the link again only then the page will show ua.
Why is it so and how can I fix it?
It seems like cookies are read only with 2 click or page is somehow loaded before the cookie update.
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println("Received Value: " + request.getRequestURL());
response.getWriter().append("Decoded string: ").append(
Utils.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length())));
String decodeValue = Utils
.getDataFromFeedbackLink(request.getPathInfo().substring(1, request.getPathInfo().length()));
request.setAttribute("finalData", decodeValue);
RequestDispatcher rd = request.getRequestDispatcher(decodeValue);
rd.forward(request, response);
}
jsp:
<body>
Hello World ::::
<%=request.getAttribute("finalData")%>
</body>
web.xml
<servlet>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<description></description>
<servlet-class>com.techjini.tfs.servlets.SubmitFeedbackServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SubmitFeedbackServlet</servlet-name>
<url-pattern>/submitfeedback/*</url-pattern>
</servlet-mapping>
i am getting value but when i try to send value from Servlet to Jsp then each time same servlet loaded so am unable to get value inside jsp please suggest me how to get value from servlet to jsp using request dispatcher or some thing i did wrong please point me where am doing mistake .
If you store some data in request attribute in will be seen on forwarded page. Just set req.setAttribute("key", "value") and it will be visible on destination page via ${"key"}
in the line "RequestDispatcher rd = request.getRequestDispatcher(decodeValue);"
the decodeValue should contain the name of the jsp file . can you check that by printing the value of decodeValue on console.
I am new to programming and i have written two pieces of code to learn urlrewriting in servlet:
My html form is :
<form action="loginhidden" method="get">
Login ID:<input name="login" ><br>
Password:<input name="pass" type="password"><br>
<input type="submit" >
</form>
My web.xml file is :
<web-app>
<servlet>
<servlet-name>loginhidden</servlet-name>
<servlet-class>loginhidden</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginhidden</servlet-name>
<url-pattern>/loginhidden</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>loginhidden1_name</servlet-name>
<servlet-class>loginhidden1_name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginhidden1_name</servlet-name>
<url-pattern>/loginhidden1_name/*</url-pattern>
</servlet-mapping>
</web-app>
The pieces of code are as follows:
1.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginhidden extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String login= req.getParameter("login");
String pass=req.getParameter("pass");
if(pass.equals("admin"))
{
out.println(login);
out.println(pass);
out.println("<html><head><form action=loginhidden1_name?
mylogin="+login+">");
out.println("Your Name:<input type=text name=myname><br>");
out.println("<input type=submit>");
out.println("</body></head></html>");
}
}
}
2.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class loginhidden1_name extends HttpServlet{
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res )throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(req.getParameter("mylogin"));
out.println(req.getParameter("myname"));
}
}
I am able to get the value of name in my second servlet(loginhidden1_name) but i am not able to get the value of login id("mylogin") through urlrewriting.I am getting null value for it.Please Help.
Thanks a lot in Advance.
If you're just looking to transfer control from one servlet to another, it's a simple matter of forwarding the request to the other servlet. A "forward" in this case does not go back to the client.
In your original servlet, at the end, you'll want to get a RequestDispatcher, and forward to the new URL.
e.g.
getServletContext().getRequestDispatcher("/modified/url").forward(request, response);
The thread of control will transfer to the other servlet. IIRC, you will still finish out the method call in the first servlet. i.e. it doesn't return from your method and then call the other servlet.
You can take advantage of this if you need post processing of the request for some reason. Although a ServletFitler would be a more appropriate way to handle this case.
You cannot can use URL rewriting in a form action. Any parameters after ? will be dropped by the browser. Instead you can add the login as a hidden form field in your second form:
...
out.println("<input type=hidden name=\"mylogin\" value=\""+login+"\">");
...
This will be passed through to your second Servlet in the same way as the other fields.
See submitting a GET form with query string params and hidden params disappear
I am getting this "HTTP method POST is not supported by this URL" error when I run my project. The funny thing is, it was running perfectly fine two days ago. After I made a few changes to my code but then restored my original code and its giving me this error. Could you please help me?
Here is my index.html:
<form method="post" action="login.do">
<div>
<table>
<tr><td>Username: </td><td><input type="text" name="e_name"/>
</td> </tr>
<tr><td> Password: </td><td><input type="password" name="e_pass"/>
</td> </tr>
<tr><td></td><td><input type="submit" name ="e_submit" value="Submit"/>
Here is my Login servlet:
public class Login extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
int status;
String submit = request.getParameter("e_submit");
String submit2 = request.getParameter("a_submit");
out.println("Here1");
String e_name = request.getParameter("e_name");
String e_password = request.getParameter("e_pass");
String a_name = request.getParameter("a_name");
String a_password = request.getParameter("a_pass");
out.println(e_name+e_password+a_name+a_password);
Author author = new Author(a_name,a_password);
Editor editor = new Editor(e_name,e_password);
// If it is an AUTHOR login:
if(submit==null){
status = author.login(author);
out.println("Author Login");
//Incorrect login details
if(status==0) {
out.println("Incorrect");
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
}
//Correct login details --- AUTHOR
else {
out.println("Correct login details");
HttpSession session = request.getSession();
session.setAttribute(a_name, "a_name");
RequestDispatcher view = request.getRequestDispatcher("index_S.jsp");
view.forward(request, response);
}
}
//If it is an EDITOR login
else if (submit2==null){
status = editor.login(editor);
//Incorrect login details
if(status==0) {
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
}
//Correct login details --- EDITOR
else {
out.println("correct");
HttpSession session = request.getSession();
session.setAttribute(e_name, "e_name");
session.setAttribute(e_password, "e_pass");
RequestDispatcher view = request.getRequestDispatcher("index_S_1.html");
view.forward(request, response);
} }
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}}
And my web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>controller.Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
I use Glassfish v3 server - let me know anything else you need to know
That's because on your doGet() and doPost() method, you're calling it's super methods. Rather, call the processRequest() inside the respective methods mentioned above.
The super.doGet() and super.doPost() method, returns an HTTP 405, by default, so you don't call your superclass doGet() and doPost().
Why is there a processRequest method in your code? Who will call that method?
You can't get up to that method by calling super.doGet() or super.doPost()
you need to call that method explicitly.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp)
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
processRequest(req,resp)
}
EDIT
Do this
response.sendRedirect("index_F.html");
return;
instead of
RequestDispatcher view = request.getRequestDispatcher("index_F.html");
view.forward(request, response);
Inside doPost() you have to call processRequest().
You're calling doGet() and doPost() method without actually implementing (using super).
The HttpServlet basically follows the template method pattern where all non-overridden HTTP methods returns a HTTP 405 error "Method not supported". When you override such a method, you should not call super method, because you would otherwise still get the HTTP 405 error. The same story goes on for your doPost() method.
Call the processRequest(req,resp) inside the respective methods mentioned above.
EDIT:
Second,
Do not use dispatcher to forward request to HTML. Use redirect anyway if you want to show html only.
response.sendRedirect("index_F.html");
return;
Also, It is good practice to use redirect when you do Logout or send back for invalid credentials.
let me give you an idea about how the system works.
I am using JAAS login module for login and role management. I can access specific pages depending on the role i have.
I type my url in the address bar, hit enter.
The login page appears and after correct login, it redirects me to the correct page(for now lets call it page1.jsf).
I want to call a server side method on page load.
Can you help me please?
** EDIT **
Assume i have to access page1.jsf which is accessible to role1 only.
In the address bar, i type http://localhost:8080/myapp/page1.jsf
JAAS shows up the login page and after correctly inputting the credentials, i am redirected to page1.jsf
As soon as page1.jsf is requested or on page load, i want to call a server side method from my class to reload page1.jsf
If you are using JSF 2, you can use the above page snippet:
<html xmlns="http://www.w3.org/1999/xhtml"
... >
<f:view contentType="text/html">
<f:event type="preRenderView" listener="#{permissionManager.checkRoles}" />
<f:attribute name="roles" value="ROLE" />
...
</f:view>
</html>
you can add an attribute containing the role and in the PermissionManager.checkRoles() perform redirect to the corret page.
#Named
#ApplicationScoped
class PermissionManager {
...
public void checkRoles(ComponentSystemEvent event) {
String acl = "" + event.getComponent().getAttributes().get("roles");
//Check user role
...
//Redirect if required
try {
ConfigurableNavigationHandler handler = (ConfigurableNavigationHandler) context
.getApplication().getNavigationHandler();
handler.performNavigation("access-denied");
} catch (Exception e) {
...
}
}
}
Check out this example
and take a look at this related question
Yes this works. Instead of accessing a jsp or jsf page, you can also access Servlets. So create a new servlet. E.g.:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class TestServlet
*/
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public static void yourMethod() {
// do something useful
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
yourMethod();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Then create a new entry in the web.xml file, in order to map the Servlet to /.
<servlet>
<display-name>TestServlet</display-name>
<servlet-name>TestServlet</servlet-name>
<servlet-class>your.packages.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
After this, you should be able to call localhost:8080/TestServlet which then calls your method.