dwr reverse ajax stock demo application - java

I am implementing a dwr reverse ajax example given here
http://wiki.netbeans.org/CreateReverseAjaxWebAppsWithDWR
below is the code
index.jsp fetches the values from StocksDemo.java
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>DWR StocksDemo</title>
<%-- This files are created in the runtime --%>
<script type='text/javascript' src='${pageContext.request.contextPath}/dwr/util.js'></script>
<script type='text/javascript' src='${pageContext.request.contextPath}/dwr/interface/StocksDemo.js'></script>
<script type='text/javascript' src='${pageContext.request.contextPath}/dwr/engine.js'></script>
<script type="text/javascript">
function getStocks() {
StocksDemo.sendStocks();
}
</script>
<link rel="stylesheet" type="text/css" href="generic.css" />
</head>
<body onload="dwr.engine.setActiveReverseAjax(true);">
<h1>Receiving Stock Rates using Reverse Ajax</h1>
<p>The following example illustrates how stock rates can be pushed from the server. Note: these are faked rates. A real application would use something like a Reuters live stockfeed at the back-end.</p>
<input type="button" value="Get Stocks" onclick="getStocks()"/>
<hr>
<table style="width:500px" border="0" cellpadding="0">
<tr>
<td class="headName" ><b>Name</b></td>
<td class="headValue" ><b>value</b></td>
</tr>
<tr><td>Allianz SE</td><td><div id="allianz">wait...</div></td></tr>
<tr><td>Bayer AG</td><td><div id="bayer">wait...</div></td></tr>
<tr><td>BMW AG St</td><td><div id="bmw">wait...</div></td></tr>
<tr><td>Commerzbank AG</td><td><div id="commerzbank">wait...</div></td></tr>
<tr><td>Daimler AG</td><td><div id="daimler">wait...</div></td></tr>
<tr><td>Deutsche Bank AG</td><td><div id="deutschebank">wait...</div></td></tr>
<tr><td>Deutsche Post AG</td><td><div id="deutschepost">wait...</div></td></tr>
<tr><td>Deutsche Telekom AG</td><td><div id="telekom">wait...</div></td></tr>
<tr><td>Hypo Real Estate Holding AG</td><td><div id="hypo">wait...</div></td></tr>
<tr><td>Infineon Technologies AG</td><td><div id="infineon">wait...</div></td></tr>
<tr><td>Linde AG</td><td><div id="linde">wait...</div></td></tr>
<tr><td>METRO AG St</td><td><div id="metro">wait...</div></td></tr>
<tr><td>RWE AG St</td><td><div id="rwe">wait...</div></td></tr>
<tr><td>SAP AG</td><td><div id="sap">wait...</div></td></tr>
<tr><td>Siemens AG</td><td><div id="siemens">wait...</div></td></tr>
<tr><td>TUI AG</td><td><div id="tui">wait...</div></td></tr>
<tr><td>Volkswagen AG St</td><td><div id="vw">wait...</div></td></tr>
</table>
<br>
</body>
</html>
my pojo classe
StocksDemo.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.proxy.dwr.Util;
import org.directwebremoting.util.Logger;
/**
* Reverse Ajax class.
*
* #author Siegfried Bolz (blog.jdevelop.eu)
*/
public class StocksDemo {
protected static final Logger log = Logger.getLogger(StocksDemo.class);
private List<StocksBean> stocks = new ArrayList<StocksBean>();
/**
* Initialize the stocklist with values.
*/
public StocksDemo() {
stocks.add(new StocksBean("bmw", "36.55"));
stocks.add(new StocksBean("linde", "91.01"));
stocks.add(new StocksBean("commerzbank", "22.59"));
stocks.add(new StocksBean("infineon", "5.07"));
stocks.add(new StocksBean("siemens", "71.77"));
stocks.add(new StocksBean("sap", "31.61"));
stocks.add(new StocksBean("bayer", "51.29"));
stocks.add(new StocksBean("metro", "52.70"));
stocks.add(new StocksBean("tui", "16.96"));
stocks.add(new StocksBean("daimler", "54.34"));
stocks.add(new StocksBean("vw", "178.48"));
stocks.add(new StocksBean("allianz", "134.48"));
stocks.add(new StocksBean("deutschebank", "76.32"));
stocks.add(new StocksBean("rwe", "80.63"));
stocks.add(new StocksBean("hypo", "18.79"));
stocks.add(new StocksBean("deutschepost", "20.19"));
stocks.add(new StocksBean("telekom", "11.13"));
}
/**
* Send the Stock-Values to the file "index.jsp"
*/
public void sendStocks() throws InterruptedException {
WebContext wctx = WebContextFactory.get();
String currentPage = wctx.getCurrentPage();
Collection sessions = wctx.getScriptSessionsByPage(currentPage);
Util utilAll = new Util(sessions);
for (int i = 0; i < stocks.size(); i++) {
Thread.sleep(1);
utilAll.setValue(stocks.get(i).getStock(), stocks.get(i).getValue());
log.info("Pushing stock: " + stocks.get(i).getStock() + " = " + stocks.get(i).getValue());
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>pollAndCometEnabled</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dwr-invoker</servlet-name>
<url-pattern>/dwr/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
dwr.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC "-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.ltd.uk/dwr/dwr20.dtd">
<dwr>
<allow>
<create creator="new" javascript="StocksDemo">
<param name="class" value="eu.jdevelop.dwrstocksdemo.StocksDemo"/>
</create>
</allow>
</dwr>
I have added the dwr js engine.js and util.js files in webcontent folder.
when i run the project on tomcat and in firefox.
On click the getStocks button which triggers the javascript getStock() method.
I get a session error popup.
And the message in the tomcat console is
1020033 [http-bio-8080-exec-19] ERROR org.directwebremoting.dwrp.Batch
-A request has been denied as a potential CSRF attack.
Can anyone please tell me why. Am I missing something?
below is StocksDemo.js created in the browser
// Provide a default path to dwr.engine
if (dwr == null) var dwr = {};
if (dwr.engine == null) dwr.engine = {};
if (DWREngine == null) var DWREngine = dwr.engine;
if (StocksDemo == null) var StocksDemo = {};
StocksDemo._path = '/ReverseAjax/dwr';
StocksDemo.sendStocks = function(callback) {
dwr.engine._execute(StocksDemo._path, 'StocksDemo', 'sendStocks', callback);
}

Add
<init-param>
<param-name>crossDomainSessionSecurity</param-name>
<param-value>false</param-value>
</init-param>
to your web.xml .it will work fine.

Related

JavaEE/Tomcat 9.0.0/ IntellijIdea 2016.2: At least one JAR was scanned for TLDs yet contained no TLDs

Error
There is a problem while starting application. It complains about:
org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
There is a link to screenshot output
Some source files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/users</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/context.xml</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
</web-app>
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/users"
global="jdbc/users"
auth="Container"
type="javax.sql.DataSource"
username="root"
password="admin"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/users" />
</Context>
InputServlet
package pl.javastart.prepared.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
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.sql.DataSource;
#WebServlet("/InputServlet")
public class InputServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
ResultSet resultSet = null;
Statement statement = null;
try {
Context initialContext = new InitialContext();
Context envContext = (Context) initialContext
.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/users");
conn = ds.getConnection();
statement = conn.createStatement();
String username = request.getParameter("username");
String password = request.getParameter("password");
// pass2" OR '1'='1'; --
final String sqlQuery = "SELECT username, password FROM user WHERE "
+"username=" + "\"" + username + "\" "
+"AND "
+"password=" + "\"" + password + "\";";
System.out.println(sqlQuery);
resultSet = statement.executeQuery(sqlQuery);
if(resultSet.next()) {
String userFound = resultSet.getString("username");
request.getSession().setAttribute("username", userFound);
if("admin".equals(userFound)) {
request.getSession().setAttribute("privigiles", "all");
} else{
request.getSession().setAttribute("privigiles", "view");
}
} else {
request.getSession().setAttribute("username", "Nieznajomy");
request.getSession().setAttribute("privigiles", "none");
}
request.getRequestDispatcher("result.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
resultSet.close();
statement.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
result.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>Welcome <%= session.getAttribute("username") %></h1>
<h2>Your privigiles: <%= session.getAttribute("privigiles") %></h2>
</body>
</html>
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Log in</title>
</head>
<body>
<h1>Log in</h1>
<form action="InputServlet" method="post">
<input type="text" placeHolder="Username" name="username">
<br>
<input type="password" placeHolder="Password" name="password">
<br>
<input type="submit" value="Zaloguj">
</form>
</body>
</html>
Solutions from older versions of Tomcat didn't work in here
add servlet mapping in web.xml:
<servlet>
<servlet-name>InputServlet</servlet-name>
<servlet-class>pl.javastart.prepared.servlet.InputServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InputServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>

Requested Resource is not available error [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
I'm trying to build a twitter search using jsp, servlet, Tomcat-6.0.43 and eclipse and getting HTTP Status 404 error. Can anyone please check where am I going wrong.
My Code:
first.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ServletValues.java" method="get">
Enter Twitter Search Details : <input type="text" name="first"><br>
<input type="submit">
</form>
</body>
</html>
TwitterServlet.java:
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
public class TwitterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public TwitterServlet() {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String CONSUMER_KEY = "[data]";
String CONSUMER_KEY_SECRET = "[data]";
String AccessToken = "[data]";
String AccessTokenSecret = "[data]";
response.setContentType("text/html");
String input1 = request.getParameter("first");
try{
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
AccessToken oathAccessToken = new AccessToken(AccessToken, AccessTokenSecret);
twitter.setOAuthAccessToken(oathAccessToken);
List<Status> status = twitter.getUserTimeline(input1);
for (Status status2 : status)
{
System.out.println("---Tweet---"+status2.getText());
}}catch (TwitterException te){
System.out.println("Error occured "+te);
}
super.doPost(request, response);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>
Twitter12</display-name>
<servlet>
<description>
</description>
<display-name>
TwitterServlet</display-name>
<servlet-name>TwitterServlet</servlet-name>
<servlet-class>
TwitterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>
<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>
Error: HTTP Status 404 - /Twitter12/ServletValues.java
type Status report
message /Twitter12/ServletValues.java
description The requested resource is not available.
In your jsp file form action, Replace
<form action="ServletValues.java" method="get">
With
<form action="TwitterServlet" method="get">
Since in your web.xml your servlet mapping pattern is TwitterServlet for the Servlet class that you intend to call.
Also in your servlet you are just printing to System.out while you should write into the reponse stream using
response.getOutputStream().write("---Tweet---"+status2.getText());
so that it shows up in the response
Change your form action to:​
<form action="/TwitterServlet" method="get">
your servlet url is /TwitterServlet as you have defined
<servlet-mapping>
<servlet-name>TwitterServlet</servlet-name>
<url-pattern>/TwitterServlet</url-pattern>
</servlet-mapping>

Skip Java Filter based on Condition

I have looked in to How to skip a filter in the filter chain in java and followed the solution but this didn't help.
I have three filters in my web.xml. Struts filter, custom filter and IAM Agent filter in this order. I want to skip IAM filter based on some condition. I do not have control on IAM filter its external peace of code. So when ever the front end parameter says that the usertype is internal I need to call IAM agent filter else I need to skip this filter.
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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5">
<display-name>App</display-name>
<!-- Struts2 Filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- Custom App Filter for Handling Internal And External User-->
<filter>
<filter-name>UserType</filter-name>
<filter-class>com.App.web.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserType</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- IAM Filter for Internal Users only-->
<filter>
<filter-name>Agent</filter-name>
<filter-class>com.sun.identity.agents.filter.AmAgentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Agent</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
</listener>
<listener>
<listener-class>com.App.init.InitListener</listener-class>
</listener>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<!-- Web Service -->
<servlet>
<servlet-name>EventManagementWS</servlet-name>
<servlet-class>com.App.eventmanagement.ws.EventManagementWS</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>EventManagementWS</servlet-name>
<url-pattern>/EventManagementWS</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>url/ConfigProperty</res-ref-name>
<res-type>java.net.URL</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
I am using RequestDispatcher#forward(), but I not getting anything in my index.jsp page output, just a blank page. The css files are giving 404 error. When I was using Struts tag it gave error
Uncaught exception created in one of the service methods of the servlet /index.jsp in application App. Exception created: The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.
So i removed S tag and used hard coding, but now I am getting 404 error in all css which i was trying to include.
I feel as if the forward is not working fine.
Java Filter Code:
package com.App.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import com.App.constant.Constant;
import com.App.init.WIMSInitListener;
import com.App.log.WIMSMessageLogger;
public class LoginFilter implements Filter{
FilterConfig _filterConfig = null;
#Override
public void destroy(){
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException{
// Check IAM is enabled
if (InitListener.isIAMEnabled()){
HttpSession session = httpRequest.getSession();
String userType = (String) session.getAttribute(Constant.USER_TYPE);
if(userType == null || "".equals(userType)){
MessageLogger.putMessageLog("User type is null : First Request" + userType, getClass());
userType = request.getParameter(Constant.USER_TYPE);
session.setAttribute(Constant.USER_TYPE, userType);
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
.forward(request, response);
}
if("external".equals(userType)){
MessageLogger.putMessageLog("External User" + userType, getClass());
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
.forward(request, response);
}
else if("internal".equals(userType)){
MessageLogger.putMessageLog("Internal User" + userType, getClass());
//IAM Filter com.sun.identity.agents.filter.AmAgentFilter
filterChain.doFilter(request, response);
}
}
//Its always External User
else{
MessageLogger.putMessageLog("User IAM Not Enabled", getClass());
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()) )
.forward(request, response);
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException{
this._filterConfig = filterConfig;
}
}
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>App</title>
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/common.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/style.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/default.css" />
<script type="text/javascript">
function selectUserType(){
var frm = document.forms["UserTypeForm"];
if(document.getElementById("userTypeInternal").checked){
//frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
frm.action='/App/loginAction.action?usertype=internal';
}
else{
//frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
frm.action='/App/loginAction.action?usertype=external';
}
frm.target='_parent';
frm.submit();
}
function checkUserType(){
//var userType = '<s:property value="#session.usertype" />';
var userType = '<%= session.getAttribute("usertype") %>';
if(userType == 'internal'){
//frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
frm.action='/App/loginAction.action?usertype=internal';
frm.target='_parent';
frm.submit();
}
else if(userType == 'external'){
//frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
frm.action='/App/loginAction.action?usertype=external';
frm.target='_parent';
frm.submit();
}
}
</script>
</head>
<body onload="javascript:checkUserType();">
<form method="POST" action="loginAction.action" name="UserTypeForm">
<div id="display_option"
style="DISPLAY: none; position: absolute; top: 40%; width: 100%;"
align="center">
<div class="rcorp-tbl">
<div style="width: 340px;">
<div style="border: 1px solid #6da6fe; padding: 5px;">
<table style="background-color: #f0f8ff;" cellspacing=2 border=0>
<tr>
<td class="t-cellsecnowrap">Select User type:</td>
<td>
<td class="t-cell">
<div id="wwgrp_systemType" class="wwgrp">
<div id="wwctrl_systemType" class="wwctrl">
<input type="radio" name="UserType" id="internal" value="internal" checked/>
<label for="userTypeInternal">Internal User (Sydney Trains Users)</label>
<input type="radio" name="userType" id="external" value="external"/>
<label for="userTypeExternal">External User</label>
<input type="button" name="applyBtn" id="applyBtn" class="btn" value="Go" title="Go" onclick="javascript:selectUserType();"/>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Instead of trying to control it in your LoginFilter, create a new class that extends com.sun.identity.agents.filter.AmAgentFilter and configure that in your web.xml. You class would look something like this:
public class CustomFilter extends AmAgentFilter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (InitListener.isIAMEnabled()) {
HttpSession session = httpRequest.getSession();
String userType = (String) session.getAttribute(Constant.USER_TYPE);
if ("internal".equals(userType)) {
super.doFilter(servletRequest, servletResponse, filterChain);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
#Override
public void destroy() {
super.destroy();
}
}
The super.doFilter() call will only perform the actions in AmAgentFilter if the criteria in that if-block is met; otherwise, we ignore that filter and move on to the next one in the chain.
You would configure this filter in your web.xml instead of the AmAgentFilter.

Import servlet in JSP Index => Null parameter

I'm currently working on a school project. We have to do a small market website in Java.
I've a small problem. I have an Index.jsp where i want to include a servlet (RandomArticle.jsp). This servlet have a .jsp and a .java and just shuffle a collection and return names.
When I display index.jsp, the html of RandomArticle.jsp is well displayed (so the include is correct) but the returned name are "null".
Here is some code:
Index.jsp (in WebContent of eclipse)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Market</title>
</head>
<body>
<header>
<h1>market 2013</h1>
<h2>Bievenue </h2>
</header>
<nav>
<% String include = "/WEB-INF/RandomArticle.jsp"; %>
<jsp:include page='<%=include%>' />
</nav>
</body>
</html>
RandomArticle.jsp (in WEB-INF):
<h1>Liste des produits EpiMarket</h1>
<%
String productName1 = (String) request.getAttribute("productName1");
String productName2 = (String) request.getAttribute("productName2");
String productName3 = (String) request.getAttribute("productName3");
%>
<p>Acheter <% out.println(productName1); %></p>
<p>Acheter <% out.println(productName2); %></p>
<p>Acheter <% out.println(productName3); %></p>
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>Market</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Test</servlet-name>
<servlet-class>fr.market.servlets.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>RandomArticle</servlet-name>
<servlet-class>fr.market.servlets.RandomArticle</servlet-class>
</servlet>
</web-app>
and RandomARticle.java
public class RandomArticle extends HttpServlet {
private ArrayList<Object> allProducts;
public String getProductName(int index){
return (((AbstractProduct) allProducts.get(index)).getName());
}
public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException{
ADAO<AbstractProduct> dao = new DAOProduit();
allProducts = ((DAOProduit) dao).getAll();
Collections.shuffle(allProducts);
request.setAttribute("productName1", getProductName(0));
request.setAttribute("productName2", getProductName(1));
request.setAttribute("productName3", getProductName(2));
this.getServletContext().getRequestDispatcher( "/WEB-INF/RandomArticle.jsp" ).forward( request, response );
}
}
I think that the .java is never called, but I don't understand why.
Thanks for your time.
Gilles

Apache Tomcat:Path Error

Hı,I have JSP and Web_Service.java.Web_Service.java is just a java class.It has a methods which are called by JSP.JSP file has a two button and two textbox.And when ı enter a number and click button,ıt call java class to do something on number.
This is my JSP class Web_Client.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form
action='http://localhost:8080/WebService/services/Web_Service/FahrenheitToCelsius'
method="post" target="_blank">
<table>
<tr>
<td>Fahrenheit to Celsius:</td>
<td><input type="text" size="30" name="Input"></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Convert"></td>
</tr>
</table>
</form>
<form
action='http://localhost:8080/WebService/services/Web_Service/CelsiusToFahrenheit'
method="post" target="_blank">
<table>
<tr>
<td>Celsius to Fahrenheit:</td>
<td><input type="text" size="30" name="Input"></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="Convert"></td>
</tr>
</table>
</form>
</body>
</html>
The following code is my web service class which is in package mypack:Web_Service.java: package mypacket;
/**
* Web Service
* Temp Converter
*
*#version 1.0 Release 1
*#author mert
*
**/
public class Web_Service{
public String FahrenheitToCelsius(String Input) {
if (!Input.isEmpty() && isNumber(Input)) {
double result = 0;
result = Double.parseDouble(Input);
result = (((result) - 32) / 9) * 5;
Input = Double.toString(result);
return Input;
} else {
return "ERROR! Please enter the input number...";
}
}
public String CelsiusToFahrenheit(String Input) {
if (!Input.isEmpty() && isNumber(Input)) {
double result = 0;
result = Double.parseDouble(Input);
result = (((result) * 9) / 5) + 32;
Input = Double.toString(result);
return Input;
} else {
return "ERROR! Please enter the input number...";
}
}
The following code is my 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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Bitirme_Proje_New</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>/axis2-web/index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<display-name>Apache-Axis Servlet</display-name>
<servlet-name>AxisServlet</servlet-name>
<servlet-class>org.apache.axis2.transport.http.AxisServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/servlet/AxisServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>*.jws</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AxisServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<servlet>
<display-name>Apache-Axis Admin Servlet Web Admin</display-name>
<servlet-name>AxisAdminServlet</servlet-name>
<servlet-class>org.apache.axis2.transport.http.AxisAdminServlet</servlet-class>
<load-on-startup>100</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>AxisAdminServlet</servlet-name>
<url-pattern>/axis2-admin/*</url-pattern>
</servlet-mapping>
</web-app>
When I run the project, the JSP works: Buttons and textbox appears. But when I enter a number ın a textbox and click button, I get this error:
HTTP Status 404 -
/WebService/services/Web_Service/FahrenheitToCelsius
type Status report
message /WebService/services/Web_Service/FahrenheitToCelsius
description The requested resource is not available.
Apache Tomcat/6.0.37
Why does Apache Tomcat say "The requested resource is not available"? What can I do for this error?
There is a incorrect web service call.
You have to set up some page for action property of form. The page can to do web service call.
I propose Spring MVC rest service with JSON for your: http://www.javacodegeeks.com/2013/04/spring-mvc-easy-rest-based-json-services-with-responsebody.html

Categories

Resources