Apache Tomcat:Path Error - java

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

Related

Java Web Application Edit is Not Working

I am learning Java CRUD Operation . I am trying to insert ,update and delete records from sql database.The insert and displaying all records methods is working but the problem is when I click edit and delete links ,its throw http 404 not found exception
Here is my HTML code display all the records .
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Posts</title>
</head>
<body>
<div style="width: 1200px; margin-left: auto; margin-right: auto;">
<table cellpadding="10">
<tr>
<th>Id</th>
<th>Title</th>
<th>Description</th>
<th>Detail</th>
<th>Category</th>
<th>Date</th>
<th>Image</th>
<th></th>
</tr>
<c:forEach items="${AllPost}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.title}...</td>
<td>${p.description}...</td>
<td>${p.detail}...</td>
<td>${p.category}</td>
<td>${p.date}...</td>
<td>${p.image}...</td>
<td>
Edit
Delete
</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Here is the HTML for EidtPost.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Edit</title>
</head>
<body>
<h1>Edit News</h1>
<div style="width: 900px; margin-left: auto; margin-right: auto">
<c:forEach items="${getNewsById}" var="p">
<form action="JSP/ManagerEditPost.jsp" method="post">
<input type="hidden" name="id" value="${p.id}">
Title:<br>
<input type="text" value="${p.title}" name="title" style="width: 200px"><br>
Description:<br>
<input type="text" value="${p.description}" name="description" style="width: 200px"><br>
Detail:<br>
<textarea name="detail" style="width: 400px; height: 200px">${p.detail}</textarea><br>
Category:
<select name="category">
<option value="${p.category}">${p.category}</option>
<option value="World">World</option>
<option value="Tech">Tech</option>
<option value="Sport">Sport</option>
</select><br>
Image:<br>
<input type="text" value="${p.image}" name="image" style="width: 200px"><br>
<input type="submit" value="Submit">
</form>
</c:forEach>
</div>
</body>
</html>
Here is the Data Access code for CRUD operation.
public void edit(int id, String title, String description, String detail, String category, String image){
try {
String sql = "update News SET title = ?, description = ?, detail = ?, category = ?, image = ?" + " where id = ?";
PreparedStatement ps= DBUtils.getPreparedStatement(sql);
ps.setString(1, title);
ps.setString(2, description);
ps.setString(3, detail);
ps.setString(4, category);
ps.setString(5, image);
ps.setInt(6, id);
ps.executeUpdate();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Here is the servlet code .
#WebServlet(name = "EditPost", urlPatterns = {"/EditPost"})
public class EditPost extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
{
String idTemp = request.getParameter("id");
int id = Integer.parseInt(idTemp);
request.setAttribute("getNewsById", DataAccess.getNewById(id));
RequestDispatcher rd = request.getRequestDispatcher("CRUD/EditPost.jsp");
try {
rd.forward(request, response);
} catch (ServletException | IOException ex) {
Logger.getLogger(EditPost.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</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>
<servlet-name>EditPost</servlet-name>
<servlet-class>servlet.EditPost</servlet-class>
</servlet>
<servlet>
<servlet-name>DeletePost</servlet-name>
<servlet-class>servlet.DeletePost</servlet-class>
</servlet>
<servlet>
<servlet-name>AllPost</servlet-name>
<servlet-class>servlet.AllPost</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>EditPost</servlet-name>
<url-pattern>/EditPost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeletePost</servlet-name>
<url-pattern>/DeletePost</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AllPost</servlet-name>
<url-pattern>/AllPost</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Here is the screen shot of the error when i click the edit and delete link .
The following shows the minimum necessary to create the desired functionality. Obviously everything about the true implementation needs to be added.
Ultimately, the path in the .jsp needs to match to the #WebServlet path. Though the specific forwarding depends a bit on absolute vs. relative URLs.
This works in tomcat 9.0, but is likely applicable to other such servers such as glassfish, etc.
web.xml
This provides the basic information.
<web-app>
<welcome-file-list>
<welcome-file>welcome.jsp</welcome-file>
</welcome-file-list>
</web-app>
welcome.jsp
This is just an example .jsp that provides an href.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World!</h1>
<!-- note this can also be ./EditPost -->
<!-- also note that not passing any query here -->
Edit Post
</body>
</html>
EditPost.java
This is a quick example of an annotated servlet.
#WebServlet("/EditPost")
public class EditPost extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public EditPost() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
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 {
doGet(request, response);
}
}

Java spring MVC - Student database. Not able to edit the student document

I have created a java spring MVC web application for student management, Iam able to add the student . But when i click on edit student it shows HTTP 400 - The request sent by the client was syntactically incorrect.
Controller :
package com.akhil.controller;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
importorg.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;
import com.akhil.model.Student;
import com.akhil.service.StudentService;
#Controller
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping("/")
public String setupForm(ModelMap model){
Student student = new Student();
model.addAttribute("student", student);
model.addAttribute("studentList", studentService.getAllStudent());
return "student";
}
#RequestMapping(value="/student.do", method=RequestMethod.POST)
public String doActions(#ModelAttribute Student student, BindingResult result, #RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
studentService.add(student);
map.put("student", studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
#RequestMapping(value="/editstudent", method=RequestMethod.GET)
public String editstudent(#ModelAttribute Student student, BindingResult result, #RequestParam String action, Map<String, Object> map){
Student studentResult = new Student();
studentService.edit(student.getStudentId());
map.put("student",studentResult);
map.put("studentList", studentService.getAllStudent());
return "student";
}
}
View:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# include file="/WEB-INF/jsp/includes.jsp"%>
<!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>Student Management</title>
</head>
<body>
<h1>Students Data</h1>
<form:form action="student.do" method="POST" commandName="student">
<table>
<tr>
<td><form:label path="studentId">Student ID:</form:label></td>
<td><form:input path="studentId" value="${Student.studentID}" /> </td>
</tr>
<tr>
<td>First name</td>
<td><form:input path="firstname" value="${Student.firstname}"/></td>
</tr>
<tr>
<td>Last name</td>
<td><form:input path="lastname" value="${Student.lastname}" /></td>
</tr>
<tr>
<td>Year Level</td>
<td><form:input path="yearLevel" value="${Student.yearLevel}" /> </td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="action" value="Add" />
</td>
</tr>
</table>
</form:form>
<br>
<table border="1">
<tr>
<th>ID</th>
<th>First name</th>
<th>Last name</th>
<th>Year level</th>
</tr>
<c:forEach items="${studentList}" var="student">
<tr>
<td>${student.studentId}</td>
<td>${student.firstname}</td>
<td>${student.lastname}</td>
<td>${student.yearLevel}</td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>CRUDWebAppMavenized</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</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>
#RequestMapping(value="/editstudent", method=RequestMethod.GET)
public String editstudent(#ModelAttribute Student student,BindingResult result, #RequestParam String action, Map<String, Object> map)
this approach is wrong you cant get a studentObject from a GET Request,
since you are trying to edit the object i suggest using a POST request remove the #modelAttribute annotation inside the method parameter
this annotation forms an object from the fields inside the form.
BindingResult collects errors if it cant form an object from the incoming request.
since you are not submitting a form you dont need any of them.
but you can fetch the student object from the database using the id you are getting from the url
public String editstudent(#RequestParam("id") int id, Model model){
student studentobj = studentservice.get(id);//assuming that this loads the object from database;
model.addAttribute("student",studentobj);
return "student";
}
and now you can represent the student details inside the student.jsp
then have a form to edit those details.

Part null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to upload a file but I get a NullPointerException along the way.
The error I am getting is
SEVERE: java.lang.NullPointerException at servlet.UploadServlet.doPost(UploadServlet.java:36)
on this line:
InputStream is = part.getInputStream();
Here is the code for servlet and jsp page.
UploadServlet
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 50)
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Part part = request.getPart("file");
InputStream is = part.getInputStream();
String filename = getFileName(part);
String relativeWebPath = "/WEB-INF/uploads";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File uploadedFile = new File(absoluteFilePath, filename);
FileOutputStream os = new FileOutputStream(uploadedFile);
int i = is.read();
while (i != -1) {
os.write(i);
i = is.read();
}
os.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
out.close();
}
}
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
}
}
return null;
}
}
upload.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title>MobMel::Upload</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<table class="upload">
<tr>
<td>File</td>
<td><input type="file" name="file"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>RegisterServlet</servlet-name>
<servlet-class>servlet.RegisterServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>servlet.ProfileServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>servlet.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegisterServlet</servlet-name>
<url-pattern>/RegisterServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
I hope you guys can help me fix this.
Thanks
I think this may help:
https://coderanch.com/t/618813/Null-Pointer-Exception-request-getPart
In brief, you need to add Multipartsconfig annotation. At least in my case the troble has gone.

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

dwr reverse ajax stock demo application

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.

Categories

Resources