I'm trying to make pagination in my jsp page. But I didn't get data from Database. I got an error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1".
I didn't understand what's wrong. would you please check my code and help me to solve the problem?
BooksInfo.java
package com.sreejonee.books;
import java.sql.Date;
import java.sql.Timestamp;
public class BooksInfo {
private int book_id;
private String bookName;
private String filename;
private String writerName;
private String book_details;
private Timestamp date_time;
private int rating;
private int parentscat_id;
private String parentscat_name;
private String thumCoverImag;
private String filePath;
public int getBook_id() {
return book_id;
}
public void setBook_id(int book_id) {
this.book_id = book_id;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getWriterName() {
return writerName;
}
public void setWriterName(String writerName) {
this.writerName = writerName;
}
public String getBook_details() {
return book_details;
}
public void setBook_details(String book_details) {
this.book_details = book_details;
}
public Timestamp getDate_time() {
return date_time;
}
public void setDate_time(Timestamp date_time) {
this.date_time = date_time;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
public int getParentscat_id() {
return parentscat_id;
}
public void setParentscat_id(int parentscat_id) {
this.parentscat_id = parentscat_id;
}
public String getParentscat_name() {
return parentscat_name;
}
public void setParentscat_name(String parentscat_name) {
this.parentscat_name = parentscat_name;
}
public String getThumCoverImag() {
return thumCoverImag;
}
public void setThumCoverImag(String thumCoverImag) {
this.thumCoverImag = thumCoverImag;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
BooksInfoDAO.java
package com.sreejonee.books;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.sreejonee.db.ConnectionFactory;
import com.sreejonee.db.DBConnector;
public class BooksInfoDAO {
Connection connection;
Statement stmt;
private int noOfRecords;
private static Connection getConnection()
throws SQLException,
ClassNotFoundException
{
Connection con = ConnectionFactory.
getInstance().getConnection();
System.out.println("connected!");
return con;
}
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
List<BooksInfo> bookslist = new ArrayList<BooksInfo>();
BooksInfo books = null;
try {
connection = getConnection();
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
books = new BooksInfo();
books.setBook_id(rs.getInt("book_id"));
books.setBook_details(rs.getString("book_details"));
books.setBookName(rs.getString("bookName"));
books.setWriterName(rs.getString("writerName"));
books.setDate_time(rs.getTimestamp("date_time"));
books.setParentscat_id(rs.getInt("parentscat_id"));
books.setParentscat_name(rs.getString("parentscat_name"));
books.setFilename(rs.getString("filename"));
books.setFilePath(rs.getString("filePath"));
books.setRating(rs.getInt("rating"));
books.setThumCoverImag(rs.getString("thumCoverImag"));
bookslist.add(books);
}
rs.close();
rs = stmt.executeQuery("SELECT FOUND_ROWS()");
if (rs.next())
this.noOfRecords = rs.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e2) {
e2.printStackTrace();
}
}
return bookslist;
}
public int getNoOfRecords() {
return noOfRecords;
}
}
Servlet:
BooksInfoServlet.java
package com.sreejonee.servlet;
import java.io.IOException;
import java.util.List;
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;
import com.sreejonee.books.BooksInfo;
import com.sreejonee.books.BooksInfoDAO;
#WebServlet("/BooksInfoServlet")
public class BooksInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public BooksInfoServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int page = 1;
int recordsPerPage = 5;
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
int noOfRecords = booksInfoDAO.getNoOfRecords();
int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
request.setAttribute("booksList", bookslist);
request.setAttribute("noOfPages", noOfPages);
request.setAttribute("currentPage", page);
RequestDispatcher view = request.getRequestDispatcher("user.jsp");
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
JSP page:
<c:forEach var="books" items="${bookslist}">
<div id="${books.filename}" class="single_midlecontent_component">
<div class="socialicon_on_post">
<h4>
<i class="fa fa-facebook-square"></i>
</h4>
</div>
<div class="title_of_post ">
<a href="#" class="media-left">
<img class="media-object" src="${books.getFilePath()+File.separator+books.getThumCoverImag()}" alt="...">
</a>
<h5 class="media-body ">
<span>${books.getBookName()}</span>
</h5>
<h5 class="media-body ">
<span>by ${books.getWriterName()}</span>
</h5>
<p class="date_time media-body">${books.getDate_time()}</p>
</div>
<div class="body_of_post">
<p>${books.getBook_details()}</p>
<img src="" class="img-responsive" alt="Responsive image">
</div>
<div class="fb-like" data-href="https://developers.facebook.com/docs/plugins/" data-layout="standard" data-action="like" data-show-faces="true" data-share="true"></div>
<div class="download_book">
<form action="DownloadFileServlet" method="post">
<input type="hidden" name="filename" value="${books.getFilename()}">
<div>
<input type="hidden" name="parentscat_name" value="${books.getParentscat_name()}">
</div>
<div class="download_button">
<input class="btn btn-default " type="submit" value="Download">
</div>
</form>
</div>
<div class="bottom_of_post"></div>
</div>
I can see two errors here.
First one:
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
There is a space missing after limit -- the way you wrote it, it will generate ... limit10, 5.
Second one:
I think the caller of viewAllBooksInfo() gives a wrong offset argument. Based on the error, I assume that offset is -10 which is illegal because the arguments to the limit clause in MySQL need to be non-negative.
In your updated question, you show this code:
if(request.getParameter("page") != null)
page = Integer.parseInt(request.getParameter("page"));
BooksInfoDAO booksInfoDAO = new BooksInfoDAO();
List<BooksInfo> bookslist = booksInfoDAO.viewAllBooksInfo((page-1)*recordsPerPage, recordsPerPage);
Obviously, because recordsPerPage is 5, and offset is -10, page seems to be -1. You have not shown the Code for the page which calls the BooksInfoServlet, but I guess you have entered -1 as the requested page number there.
You should have looked yourself before asking this question. It is expected from you that you should first try to remove these error yourself.
If you would look into the error stack, it says:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '-10, 5' at line 1"
If you can look carefully, the limit options are "-10, 5". Limit arguments in MySQL should be non-negative.
And in BooksInfoDAO.java code:
public List<BooksInfo> viewAllBooksInfo(int offset, int noOfRecords) {
String query = "select SQL_CALC_FOUND_ROWS * from library ORDER by date_time DESC limit"+ offset + ", " + noOfRecords;
...
you are missing a space between the limit clause and the offset parameter.
Related
I am new to webservices,
inside chrome debugger getting error:
http://localhost:8080/CRUDrestApp/REST/WebService/addUser 500 (Internal Server Error)
And in postman app getting error:
http://localhost:8080/CRUDrestApp/REST/WebService/addUser?regUserName=a
status: 415 Unsupported Media Type
To fix this errors what necessary changes I have to do?
FeedService.java>>
package webService;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import model.ProjectManager;
import model.AddUserManager;
import model.GetUserManager;
import com.google.gson.Gson;
import dto.FeedObjects;
import dto.AddUserObject;
#Path("/WebService")
public class FeedService {
//for insert query
#POST
#Path("/addUser")
#Consumes("application/json")
#Produces("application/json")
public void reguserdata(AddUserObject reguserData)
{
String feeds = null;
try
{
//StringBuffer sb = new StringBuffer();
System.out.println("Inside reguserdata");
Gson gson = new Gson();
System.out.println("Inside add User web service::"+gson.toJson(reguserData));
feeds = gson.toJson(reguserData);
AddUserManager projectManager= new AddUserManager();
projectManager.SetFeeds(feeds);
} catch (Exception e)
{
System.out.println("error");
}
}
}
AddUser.Java>>>
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import dto.AddUserObject;
public class AddUser {
public ArrayList<AddUserObject> GetFeeds(Connection connection, String receivedData) throws Exception
{
ArrayList<AddUserObject> regData = new ArrayList<AddUserObject>();
String receivedData1 = receivedData;
try
{
//String uname = request.getParameter("uname");
//PreparedStatement ps = connection.prepareStatement("SELECT * from users");
//ps.setString(1,uname);
//PreparedStatement ps = connection.prepareStatement("insert into users(username,password,hint1,hint2,emailid,uid) values(?,?,?,?,?,?)");
PreparedStatement ps = connection.prepareStatement("insert into users (username) values (?)");
AddUserObject feedObject = new AddUserObject();
System.out.println("Add>>receivedData1.valueOf(0):"+receivedData1.valueOf(0));
feedObject.setRegUserName(receivedData1.valueOf(0));
System.out.println("Add>>getRegUserName:"+feedObject.getRegUserName());
ps.setString(1, feedObject.getRegUserName());
// ps.setString(2, feedObject.getRegPassword());
// ps.setString(3, feedObject.getRegHint1());
// ps.setString(4, feedObject.getRegHint2());
// ps.setString(5, feedObject.getRegEmail());
// ps.setString(6, feedObject.getRegUid());
regData.add(feedObject);
ps.executeUpdate();
ps.close();
return regData;
}
catch(Exception e)
{
throw e;
}
}
}
AddUserObject.java>>>
package dto;
public class AddUserObject {
private String regId;
private String regusername;
private String regpassword;
private String reghint1;
private String reghint2;
private String regemail;
private String reguid;
/**
* #return the url
*/
public String getRegId() {
return regId;
}
/**
* #param reguid to set
*/
public void setRegId(String regId) {
this.regId = regId;
}
/**
* #return the title
*/
public String getRegUserName() {
return regusername;
}
/**
* #param title the title to set
*/
public void setRegUserName(String regusername) {
this.regusername = regusername;
}
/**
* #return the description
*/
public String getRegPassword() {
return regpassword;
}
/**
* #param description the description to set
*/
public void setRegPassword(String regpassword) {
this.regpassword = regpassword;
}
/**
* #return the url
*/
public String getRegHint1() {
return reghint1;
}
/**
* #param url the url to set
*/
public void setRegHint1(String reghint1) {
this.reghint1 = reghint1;
}
/**
* #return the url
*/
public String getRegHint2() {
return reghint2;
}
/**
* #param url the url to set
*/
public void setRegHint2(String reghint2) {
this.reghint2 = reghint2;
}
/**
* #return the url
*/
public String getRegEmail() {
return regemail;
}
/**
* #param reguid to set
*/
public void setRegEmail(String regemail) {
this.regemail = regemail;
}
/**
* #return the url
*/
public String getRegUid() {
return reguid;
}
/**
* #param reguid to set
*/
public void setRegUid(String reguid) {
this.reguid = reguid;
}
}
AddUserManeger.java>>>
package model;
import java.sql.Connection;
import java.util.ArrayList;
import dao.Database;
import dao.AddUser;
import dto.AddUserObject;
public class AddUserManager {
public static ArrayList<AddUserObject> SetFeeds(String feeds2)throws Exception {
ArrayList<AddUserObject> feeds = null;
String receivedData = feeds2;
try {
Database database= new Database();
Connection connection = database.Get_Connection();
AddUser project= new AddUser();
feeds=project.GetFeeds(connection , receivedData);
} catch (Exception e) {
throw e;
}
return feeds;
}
}
app.js>>
var app = angular.module("mainApp", ['ngRoute','ngAnimate']);
var baseUrl ="http://localhost:8080/CRUDrestApp/REST/WebService";
console.log("Inside App js");
app.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'home.html',
controller: 'homeCtrl'
}).
when('/register', {
templateUrl: 'register.html',
controller: 'registerCtrl'
}).
when('/login', {
templateUrl: 'login.html',
controller: 'loginCtrl'
}).
otherwise({
templateUrl: 'home.html',
controller: 'HomeCtrl'
});
}]);
app.controller('NavController', function ($scope, $location) {
$scope.isCollapsed = true;
$scope.$on('$routeChangeSuccess', function () {
$scope.isCollapsed = true;
});
$scope.getClass = function (path) {
if(path === '/') {
if($location.path() === '/') {
return "active";
} else {
return "";
}
}
if ($location.path().substr(0, path.length) === path) {
return "active";
} else {
return "";
}
}
});
app.controller('homeCtrl', function($http, $scope, $timeout) {
});
app.controller('loginCtrl', function($http, $scope, $timeout) {
});
console.log("after route provider");
app.controller('registerCtrl', function($http, $scope, $timeout) {
console.log('inside registerAppCtrl controller');
$scope.addUser = function() {
var userdetails = JSON.stringify($scope.userAdd);
console.log("$scope.userAdd::"+userdetails);
if($scope.userAdd.regUserName == "" || $scope.userAdd.regUserPass == "" || $scope.userAdd.regUserCPass == "" || $scope.userAdd.regHint1 == "" || $scope.userAdd.regHint2 == ""){
console.log('Insert mandatory field values');
}
else{
$.ajax({
url: baseUrl + '/addUser',
dataType: 'json',
type: 'post',
contentType: 'application/json ',
data: userdetails,
success: function( data, textStatus, jQxhr ){
//$('#response pre').html( data );
console.log("successfully retrived response from server:::"+data);
/* console.log(data); */
$scope.userAdd = '';
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
}
};
});
Register.html
<section id="" ng-controller="registerCtrl">
<form>
<div>
User Name
</div>
<div>
<input type="text" ng-model="userAdd.regUserName" required>
</div>
<div>
Password
</div>
<div>
<input type="password" ng-model="userAdd.regUserPass" >
</div>
<div>
Confirm Password
</div>
<div>
<input type="password" ng-model="userAdd.regUserCPass" >
</div>
<div>
Enter Hint1
</div>
<div>
<input type="text" ng-model="userAdd.regHint1" >
</div>
<div>
Enter Hint2
</div>
<div>
<input type="text" ng-model="userAdd.regHint2" >
</div>
<div>
Enter UID
</div>
<div>
<input type="text" ng-model="userAdd.regUid" >
</div>
<div>
<input type="submit" name="Register" value="Register" ng-click="addUser()">
</div>
<div>
Login
</div>
</form>
</section>
make an empty constructor in your AddUserObject.java
public AddUserObject(){}
I'm writing a webapp where in there is a table that is to be generated using Ajax. This data is actually pulled from the database. And here I want to use jquery datatable plugin.
Index.jsp
<html>
<head>
</head>
<body>
<marquee>
<h1>This is an example of ajax</h1>
</marquee>
<form name="vinform">
Enter id:<input type="button" id="somebutton" value="Click Me">
</form>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Case Number</th>
<th>Case Owner</th>
<th>Status</th>
<th>Issue</th>
<th>Reason</th>
<th>Date/Time Opened</th>
<th>Age</th>
</tr>
</tfoot>
</table>
<span id="somediv"> </span>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="tableGenerator.js"></script>
</body>
</html>
tableGenerator.js
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
UserBean.java
package org.bean;
public class UserBean {
private int age;
private String caseOwner, status, issue, reason, dateOpened, caseNumber, resolution, finalStatus, startDate,
endDate;
private Double totalTimeTaken;
public String getStartDate() {
return startDate;
}
public void setStartDate(String startDate) {
this.startDate = startDate;
}
public String getEndDate() {
return endDate;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public String getCaseNumber() {
return caseNumber;
}
public void setCaseNumber(String caseNumber) {
this.caseNumber = caseNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCaseOwner() {
return caseOwner;
}
public void setCaseOwner(String caseOwner) {
this.caseOwner = caseOwner;
}
public String getStatus() {
return status;
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public void setStatus(String status) {
this.status = status;
}
public String getIssue() {
return issue;
}
public void setIssue(String issue) {
this.issue = issue;
}
public String getDateOpened() {
return dateOpened;
}
public void setDateOpened(String dateOpened) {
this.dateOpened = dateOpened;
}
public String getResolution() {
return resolution;
}
public void setResolution(String resolution) {
this.resolution = resolution;
}
public String getFinalStatus() {
return finalStatus;
}
public void setFinalStatus(String finalStatus) {
this.finalStatus = finalStatus;
}
public double getTotalTimeTaken() {
return totalTimeTaken;
}
public void setTotalTimeTaken(Double totalTimeTaken) {
this.totalTimeTaken = totalTimeTaken;
}
public UserBean() {
}
public UserBean(String caseNumber, String caseOwner, String issue, int age, String reason, String dateOpened,
String status, String finalStatus, String resolution, String startDate, String endDate,
Double totalTimeTaken) {
this.caseNumber = caseNumber;
this.caseOwner = caseOwner;
this.issue = issue;
this.reason = reason;
this.age = age;
this.dateOpened = dateOpened;
this.status = status;
this.resolution = resolution;
this.finalStatus = finalStatus;
this.startDate = startDate;
this.endDate = endDate;
this.totalTimeTaken = totalTimeTaken;
}
}
Controller.java(Servlet)
import java.io.IOException;
import java.util.ArrayList;
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 org.bean.UserBean;
import com.dao.DataDao;
import com.google.gson.Gson;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
// String id = request.getParameter("val");
DataDao dataDao = new DataDao();
ArrayList<UserBean> list = dataDao.getFrameWork();
String searchList = new Gson().toJson(list);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(searchList);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
DBUtility.java
package com.dao;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBUtility {
private static Connection connection = null;
public static Connection getConnection() throws Exception {
if (connection != null)
return connection;
else {
// Store the database URL in a string
String userName = "sa";
String password = "T!ger123";
String url = "jdbc:sqlserver:XXXXXX;DatabaseName=TEST";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// set the url, username and password for the databse
connection = DriverManager.getConnection(url, userName, password);
return connection;
}
}
}
DataDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.bean.UserBean;
public class DataDao {
private Connection connection;
public DataDao() throws Exception {
connection = DBUtility.getConnection();
}
public ArrayList<UserBean> getFrameWork() throws SQLException {
ArrayList<UserBean> list = new ArrayList<UserBean>();
PreparedStatement ps = null;
try {
ps = connection.prepareStatement("select * from statusTable");
// ps.setString(1, frameWork);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
UserBean userBean = new UserBean();
userBean.setCaseNumber(rs.getString(1));
userBean.setCaseOwner(rs.getString(2));
userBean.setStatus(rs.getString(3));
userBean.setIssue(rs.getString(4));
userBean.setReason(rs.getString(5));
userBean.setDateOpened(rs.getString(6));
userBean.setAge(rs.getInt(7));
list.add(userBean);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return list;
}
}
When I click on the button, instead of displaying the table data, it is showing nothing apart from the Basic html skeleton created in my index file.
Instead of using
$('#somebutton').click(function() {
$(document).ready(function() {
$('#example').DataTable({
"ajax" : "Controller",
"columns" : [ {
"data" : "userBean.caseNumber"
}, {
"data" : "userBean.caseOwner"
}, {
"data" : "userBean.status"
}, {
"data" : "userBean.issue"
}, {
"data" : "userBean.reason"
}, {
"data" : "userBean.age"
} ]
});
});
});
when i used
$('#somebutton').click(
function() {
$.getJSON('Controller', function(searchList) {
var $table = $('<table>').appendTo($('#somediv'));
$.each(searchList, function(index, userBean) {
$('<tr>').appendTo($table).append(
$('<td>').text(userBean.caseNumber)).append(
$('<td>').text(userBean.caseOwner)).append(
$('<td>').text(userBean.status)).append(
$('<td>').text(userBean.issue)).append(
$('<td>').text(userBean.reason)).append(
$('<td>').text(userBean.age));
});
});
});
A normal html table is getting displayed.
Please let me know how can i display this data.
Thanks
Compiled files of chat websocket example that comes with Tomcat 7 works fine on localhost and Openshift.
However, when I compile those files myself it doesn't work on Openshift, although on localhost still works great (tomcat 7).
I tried to compile through netbeans, eclipse, and terminal (OSX). Tried all versions of dependencies, tried building as java webapp, maven webapp, tried to upload as war file but no success.
The module I'm trying to test is the chat websocket. It is composed by two classes, one xhtml file and two dependencies.
working: http://chatoriginal-helioha.rhcloud.com:8000/examples/websocket/chat.xhtml
not working: http://chat-helioha.rhcloud.com:8000/websocket/chat.xhtml
I'm not changing a single line of code, so the files I compile myself should be the same as the ones that comes already compiled right?
I also tried to decompile files using www.javadecompilers.com to see if there was anything extra there but I couldn't find any difference.
There are only three files on this project and they are shown bellow.
ChatAnnotation.java
package websockets.chat;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import util.HTMLFilter;
#ServerEndpoint(value = "/websocket/chat")
public class ChatAnnotation {
private static final Log log = LogFactory.getLog(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<ChatAnnotation> connections =
new CopyOnWriteArraySet<>();
private final String nickname;
private Session session;
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
#OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
#OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
#OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, HTMLFilter.filter(message.toString()));
broadcast(filteredMessage);
}
#OnError
public void onError(Throwable t) throws Throwable {
log.error("Chat Error: " + t.toString(), t);
}
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
log.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
HTMLFilter.java
package util;
/**
* HTML filter utility.
*
* #author Craig R. McClanahan
* #author Tim Tye
*/
public final class HTMLFilter {
/**
* Filter the specified message string for characters that are sensitive
* in HTML. This avoids potential attacks caused by including JavaScript
* codes in the request URL that is often reported in error messages.
*
* #param message The message string to be filtered
*/
public static String filter(String message) {
if (message == null)
return (null);
char content[] = new char[message.length()];
message.getChars(0, message.length(), content, 0);
StringBuilder result = new StringBuilder(content.length + 50);
for (int i = 0; i < content.length; i++) {
switch (content[i]) {
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
default:
result.append(content[i]);
}
}
return (result.toString());
}
}
chat.xhtml
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Apache Tomcat WebSocket Examples: Chat</title>
<style type="text/css"><![CDATA[
input#chat {
width: 410px
}
#console-container {
width: 400px;
}
#console {
border: 1px solid #CCCCCC;
border-right-color: #999999;
border-bottom-color: #999999;
height: 170px;
overflow-y: scroll;
padding: 5px;
width: 100%;
}
#console p {
padding: 0;
margin: 0;
}
]]></style>
<script type="application/javascript"><![CDATA[
"use strict";
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
Console.log('Error: WebSocket is not supported by this browser.');
return;
}
Chat.socket.onopen = function () {
Console.log('Info: WebSocket connection opened.');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function () {
document.getElementById('chat').onkeydown = null;
Console.log('Info: WebSocket closed.');
};
Chat.socket.onmessage = function (message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host + '/examples/websocket/chat');
} else {
Chat.connect('wss://' + window.location.host + '/examples/websocket/chat');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
document.addEventListener("DOMContentLoaded", function() {
// Remove elements with "noscript" class - <noscript> is not allowed in XHTML
var noscripts = document.getElementsByClassName("noscript");
for (var i = 0; i < noscripts.length; i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}
}, false);
]]></script>
</head>
<body>
<div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
Javascript and reload this page!</h2></div>
<div>
<p>
<input type="text" placeholder="type and press enter to chat" id="chat" />
</p>
<div id="console-container">
<div id="console"/>
</div>
</div>
</body>
</html>
Basically my goal for this page I'm working on is for users to type in a stock symbol and this information goes to a post method and send back the data to put on the same html/jsp page. I have been able to get this to work where the form leads to another JSP page, but that has to be a separate page, I'd like to be able to stay on the same page and have the info come up. If you have a resource that could teach me how to deal with this problem, I would appreciate that just as much as a solution. I have been using the Gradle Build Tool.
Here is the form(in index.jsp):
<h1>Search Stock</h1>
<form method="POST" action="DataPage.jsp">
<input type = "text" name = "Symbol">
<input type = "submit" name = "getData">
</form>
Here is the functioning JSP code(DataPage.jsp):
<%
String Ticker = request.getParameter("Symbol");
PrintWriter write = response.getWriter();
if((Ticker == null)){
String message = "Please enter a stock symbol";
write.println(message);
}else{
try{
Company object = Serializing.getCompany(Ticker);
object.updateData();
write.println("data last added" + object.getLastUpdate());
write.println(object.getSentiment());
}catch(NullPointerException x){
Company object = Serializing.getCompany(Ticker);
}
}%>
Here is the servlet I tried writing(DataServlet.java), I have very little experience with servlets, I scavenged this from different sources and questions on stackoverflow:
package Default;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Created by Ceyer on 9/3/2015.
*/
#javax.servlet.annotation.WebServlet(name = "DataServlet", urlPatterns = ("/"))
public class DataServlet extends javax.servlet.http.HttpServlet {
private static final long serialVersionUID = 1L;
public DataServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
String Ticker = request.getParameter("Symbol");
if ((Ticker == null)||Ticker.trim().isEmpty()) {
String message = "Please enter a stock symbol";
request.setAttribute("data", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} else {
PrintWriter write = response.getWriter();
try {
Company object = Serializing.getCompany(Ticker);
object.updateData();
request.setAttribute("data", object.getSentiment() + "updated last" + object.getLastUpdate());
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (NullPointerException x) {
Company object = Serializing.getCompany(Ticker);
request.setAttribute("data", "We do not have info on this stock");
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
If you want to use only one page and with a servlet, I think you can use session and response.sendRedirect() to do it.
This is index.jsp page
<h1>Search Stock</h1>
<form method="POST" action="DataServlet" onsubmit="dataCheck()">
<input type="text" name="Symbol">
<input type="submit" value="getData">
</form>
<%
if(session.getAttribute("data") != null) {
out.print("<p>" + session.getAttribute("data"));
session.removeAttribute("data");
}
%>
<script>
function dataCheck() {
if(document.getElementsByName[0].value == ""){
alert("Symbol is null!");
return false;
}
return true;
}
</script>
This is DataServlet class
public class DataServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String Ticker = request.getParameter("Symbol");
Company object = Serializing.getCompany(Ticker);
if (object != null) {
object.updateData();
request.getSession().setAttribute("data", object.getSentiment() +
"updated last" + object.getLastUpdate());
} else {
request.getSession().setAttribute("data", "We do not have info on this stock");
}
response.sendRedirect("index.jsp");
}
}
I would like to get rid of the printWriter code in the servlet.
Basically I want to output the current customers and their respective cities with the id which is a hidden field on the index page. From there I would like to be able to edit the customer name or city and then have it sent back to the index page where the information would be updated.
How do I do this?
Servlet
package edu.witc.Assignment02.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletConfig;
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 edu.witc.Assignment02_model.*;
/**
* Servlet implementation class CustomerServlet
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<Customer> customers = new ArrayList<Customer>();
/**
* #see HttpServlet#HttpServlet()
*/
public CustomerServlet() {
super();
// TODO Auto-generated constructor stub
}
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setName("Donald D.");
customer1.setCity("Miami");
customer1.add(customer1);
Customer customer2 = new Customer();
customer1.setId(2);
customer1.setName("Mickey M.");
customer1.setCity("Orlando");
customer1.add(customer2);
}
private void sendCustomerList(HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>Customers</title></head>"
+ "<body><h2>Custoemrs</h2>");
writer.println("<ul>");
for (Customer customer : customers){
writer.println("<li>" + customer.getName()
+ "(" + customer.getCity() + ") ("
+ "<a href='editCustomer?id=" + customer.getId()
+ ";>edit</a>)");
}
writer.println("</ul>");
writer.println("</body></html>");
}
private Customer getCustomer(Integer customerId){
for (Customer customer : customers) {
if(customer.getId() == customerId){
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Integer customerId = 0;
try{
customerId = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e){
}
Customer customer = getCustomer(customerId);
if(customer != null){
writer.println("<html><head>"
+ "<title>Edit Customer</title></head>"
+ "<body><h2>Edit Customer</h2>"
+ "<form method = 'post' action = 'updateCustomer'>");
writer.println("<input type = 'hidden' name = 'id' value = 'customerId'/>");
writer.println("<table>");
writer.println("<tr><td>Name:</td><td>"
+ "<input name = 'name' value = '"
+ customer.getName().replaceAll("'", "'")
+ "'/></td></tr>");
writer.println("<tr><td>City:</td><td>"
+ "<input name = 'city' value = '"
+ customer.getCity().replaceAll("'", "'")
+ "'/></td></tr>");
writer.println("<tr>"
+ "<td colspan='2' style = 'text-align: right'>"
+ "<input type ='submit' value = 'Update'/></td>"
+ "</tr>");
writer.println("<tr><td colspan='2'>"
+ "<a href = 'customer'>CustomerList</a>"
+ "</td></tr>");
writer.println("</table>");
writer.println("</form></body>");
}else{
writer.println("No Customer Found");
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
if(uri.endsWith("/customer")){
sendCustomerList(response);
}else if(uri.endsWith("/editCustomer")){
sendEditCustomerForm(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//update customer
Integer customerId = 0;
try{
customerId = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e){
}
Customer customer = getCustomer(customerId);
if(customer != null){
customer.setName(request.getParameter("name"));
customer.setCity(request.getParameter("city"));
}
sendCustomerList(response);
}
}
Customer Class
package edu.witc.Assignment02_model;
public class Customer {
private Integer id;
private String name;
private String city;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public void add(Customer customer1) {
// TODO Auto-generated method stub
}
}
index page
<%# 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>Home</title>
</head>
<body>
<h1>Current Customer(s) w/City</h1><br>
<%! String name, city; %>
<% %>
</body>
</html>
Better late than never.
Ok, to get this working you should add jstl library to your project.
Servlet
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"
})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<Customer> customers = new ArrayList<Customer>();
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
...
customers.add(customer1);
Customer customer2 = new Customer();
...
customers.add(customer2);
}
private Customer getCustomer(Integer customerId){
for (Customer customer : customers) {
if(customer.getId() == customerId){
return customer;
}
}
return null;
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
if(uri.endsWith("/customer")){
request.setAttribute("customers", customers);
request.getRequestDispatcher("/customers.jsp").forward(request, response);
}else if(uri.endsWith("/editCustomer")){
try{
customerId = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e){
e.printStackTrace();
}
Customer customer = getCustomer(customerId);
request.setAttribute("customer", customer);
request.getRequestDispatcher("/edit_customer.jsp").forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Integer customerId = 0;
try{
customerId = Integer.parseInt(request.getParameter("id"));
}catch(NumberFormatException e){
}
Customer customer = getCustomer(customerId);
if(customer != null){
customer.setName(request.getParameter("name"));
customer.setCity(request.getParameter("city"));
}
response.sendRedirect("/customer");
}
}
customers.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Customer list</h1>
<ul>
<c:forEach var="c" items="${customers}">
<li>${c.name} (Edit)</li>
</c:forEach>
</ul>
edit_customer.jsp
<%#page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" session="false" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Edit customer</h1>
<form method="POST" action="/updateCustomer">
<input type="hidden" name="id" value="${customer.id}"/>
Name: <input type="text" name="name" value="${customer.name}"/><br/>
City: <input type="text" name="city" value="${customer.city}"/><br/>
<input type="submit" value="Save"/>
</form>