JSF 2.0 call server side method on page load - java

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.

Related

Tomcat Server in Eclipse: Error 404 submitting to servlet

I have set up a tomcat V8.5 server in Eclipse on OSX. I have setup a default servlet to handle get requests from the following html form. I can startup the server and load index.html, but whenever I click submit on the form I receive a 404 error. This code came from a professor and works on her PC, so I am assuming that I have a setup problem with my server on OSX. Does anyone have any idea where I should look first? My professor isn't willing to help diagnose OSX problems. I am not sure exactly what all information I need to provide, happy to provide additional details to anyone willing to help! Thanks in advance!
Picture of my project structure
<form action="http://localhost:8080/CyberFlix0/CyberFlixServlet" method="get">
Film Title: <input type="text" name="film_title"><br>
<input type="submit" value="Submit">
</form>
my doGet function:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
Full Servlet Code:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class CyberFlixServlet
*/
#WebServlet("/CyberFlixServlet")
public class CyberFlixServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public CyberFlixServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
Change the value of action tag like this: <form action="/CyberFlixServlet" method="get">
use action="CyberFlixServlet" as shown in bellow
<form action="CyberFlixServlet" method="get">
Film Title: <input type="text" name="film_title"><br>
<input type="submit" value="Submit">
</form>
Please make sure there no Issue exists in your project, for check any issue
open problems view from window -> show view -> problems, if there's any error, fix it
eclipse will reject to compile if there is any problems in your project
I pulled this answer from another post, but this fixes it.
This a problem with tomcat and the catalina config files:
what you have to do is simply:
right click on the server tomcat in eclipse
click on properties
click switch location a little server will appear on the left side in the navigation view
double click on it after you have launched your server
Then select use Tomcat installation and save
this will solve that common 404 problem.

HttpServlet mapping doesn't work

I'm using Apache Tomcat v8.0 server and in Java EE application. Basically, I created an ResponseUpload servlet. I need to get JSON data from the web app through POST request. Here it is the code of the Servlet:
#WebServlet("/RequestUpload")
public class RequestUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RequestUpload() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
BufferedReader reader = request.getReader();
Gson gson = new Gson();
JSONObject json = gson.fromJson(reader, JSONObject.class);
uplRequest.upload(json);
PrintWriter out = response.getWriter();
out.print(json);
}
Then to test if it works I added a form to jsp file, doing POST to url:
http://localhost:8080/webApp/RequestUpload
The form:
<form action= "RequestUpload" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
But I got 404 error -
HTTP Status 404 - /webApp/RequestUpload
Can somebody show me where is my mistake?
My web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>webApp</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
P.S. Another form doing the same with RPC servlet (which structure is similar) is working.
After a research and with help of previous answer I found the problem in build path. The build path image
I had to allow output folders for source folder and change the output folder from build to WEB-INF/classes.
Servlet Class:
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
#WebServlet("/RequestUpload")
public class RequestUpload extends HttpServlet {
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Map<String, String> options = new LinkedHashMap<String, String>();
options.put("first_name", request.getParameter("first_name"));
options.put("last_name", request.getParameter("last_name"));
String json = new Gson().toJson(options);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
JSP:home.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<form action= "RequestUpload" method = "POST">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
if your context root of the web app is webApp and server is running on port:8080. you can see the home.jsp as follows:
When data are given in first_name as Minhajur and last_name as Rahman, After clicking the submit button,
following json response will be returned:
Note: make sure that you have added the required jar dependencies in lib folder. For example: gson-1.7.1.jar exists in webapp/WEB-INF/lib folder.
Trouble Shooting:
HTTP Status 404 - /webApp/RequestUpload
-> Check whether your webApp has been compiled successfuly and your compiled RequestUpload.class has been existed on your webapp/WEB-INF/classes directory on tomcat server.
if RequestUpload.class does not exist, then
1) It has not been compiled successfully.
or
2) the Compiled class files has not been moved to webapp/WEB-INF/classes directory.
So, follows the following steps:
i) Clean your tomcat working directory and compile run again and check the class file is existed there.
ii) Delete and Add Tomcat server on eclipse again. then follow the previous steps.
You can also read for further references:
How to use Servlets and Ajax?

how to make servlets send applets to the same html page that has the form

I am very very new to this. and yeah it's a homework.
I am trying to make an HTML page with a form to send some variables to a servlet and the servlet sends an applete to the same form page. so far i succeeded in sending the applet alone. I tried using jQuery, but i couldn't send the HTML tags. I can only send text.
My code so far:
index.html
<html>
<head>
<title> title </title>
</head>
<body>
<form action = "Servlet">
<input type="text" name="Name" value="" size="5" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
Servlet.java
package ServletPackage;
import java.awt.Font;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Servlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public Servlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
String nm;
nm = request.getParameter ("Name");
PrintWriter mess = response.getWriter();
mess.println("<html>");
mess.println("<head>");
mess.println("</head>");
mess.println("<body>");
mess.println("<b> You've entered Name: </b>" + nm);
mess.println("<p align=center>");
mess.println("<applet code='NameInShape.class' width=200 height=200>");
mess.println("<param name='NAME' value='" + nm + "'>");
mess.println(" </applet>");
mess.println("</p>");
mess.println("</html>");
mess.println("</body>");
mess.close();
}
public static void main( String[] args )
{ }
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
All help appreciated
One way to do it is by using RequestDispatcher to call a .jsp (JavaServer Pages) clone of your index.html with the parameters posted by your form. And don't worry, it's pretty simple to implement. The result will look like the initial page the form still available, but the applet will be called using the specified parameters.
You need to import RequestDispatcher (import javax.servlet.RequestDispatcher;) and then you can do something like this in your doPost method:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = request.getRequestDispatcher("clone.jsp");
rd.forward(request, response);
}
The method rd.forward(request, response); makes the parameters posted to your servlet available on the clone.jsp page, and you can insert them using <%=request.getParameter("ParameterName")%> inside the .jsp page.
For example, after adding the above code in your servlet, you could insert something like this in the clone.jsp page to embed the applet with a parameter received from the index.html form submission:
<applet code=Applet.class width=300 height=300>
<param name=NAME value="<%=request.getParameter("NAME")%>">
</applet>

404 error while running jsp

Hi I am receiving the 404 HTTP status while submiting the below jsp.
HTTP Status 404 - /TestServlet1
Could you please help me to resolve this error
Note : The person and the dog class were defined
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
<form id="a" action="/TestServlet1">
<input type="submit">
</form>
<%
%>
Name = '${person.name}'
Dog = '${person.dog.name}'
</body>
</html>
TestServlet1
package test;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Dog g = new Dog();
g.setName("dogeee");
Person p = new Person();
p.setDog(g);
p.setName("xxx");
request.setAttribute("person", p);
RequestDispatcher dispatch = request.getRequestDispatcher("/index.jsp");
dispatch.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>GlobalWeather</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>test.TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet1</url-pattern>
</servlet-mapping>
</web-app>
First and Third answers are right. Either write action="TestServlet1" or action="/Projectname/TestServlet1". If you put /testServet1 in action, it means you are specifying the path the desired file which in this case is wrong while if you use testservlet1 in action , it means you are searching for a file name testservlet1 in your project to run.
404 means that the URL was not found. I suspect that you need the web application name in your URL.
So rather than using a form action of:
/TestServlet1,
try
/name_of_your_web_app/TestServlet1
Just remove tha / in your form action:
<form id="a" action="/TestServlet1">
change it to
<form id="a" action="TestServlet1">
In HTML, adding a / means the relative URL and without a slash means absolute URL. Or better to use the context as mentioned here:
<form id="a" action=${pageContext.request.contextPath}/TestServlet1>
you have to put your contextroot + your servlet name...
contextRoot usually is the name of your project.
action="/nameProject/TestServlet1"
I hope this helps you

Redirect All the Pages in Home Page

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);
}
}
}

Categories

Resources