Tomcat cannot find JDBC driver when connecting to DB [duplicate] - mysql

This question already has an answer here:
jdbc to MYSQL error: No suitable driver found for jdbc:mysql://localhost:3306/test?user='root'&password='' [duplicate]
(1 answer)
Closed 7 years ago.
I've put mysql driver in .../ROOT/WEB-INF/lib and Tomcat 8.0/lib but it has no effect. I'm using the following class to connect to DB:
package db;
import java.sql.*;
public class ConnectToDB implements AutoCloseable {
Connection con;
public ConnectToDB(String server, String database, String user,
String password) throws SQLException {
con = DriverManager.getConnection("jdbc:mysql://" + server + "/"
+ database, user, password);
}
#Override
public void close() throws SQLException {
con.close();
}
public Connection getConnection() {
return con;
}
}
The following classes are included in the Eclipse project:
1. src/nr3/model
package nr3.model;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import db.ConnectToDB;
public class MusikkHandler {
private ConnectToDB db;
private Connection con;
private String tableName;
private PreparedStatement pstmtGetRows;
public MusikkHandler(String server, String database, String user,
String password) throws SQLException {
db = new ConnectToDB(server, database, user, password);
con = db.getConnection();
tableName = "album";
}
public void close() throws SQLException {
db.close();
}
public ArrayList<Album> getRows(String genre) throws SQLException {
ArrayList<Album> list = new ArrayList<Album>();
pstmtGetRows = con.prepareStatement("SELECT * FROM " + tableName
+ " WHERE SJANGER = ?");
pstmtGetRows.setString(1, genre);
ResultSet rs = pstmtGetRows.executeQuery();
while (rs.next()) {
list.add(new Album(rs.getString(1), rs.getString(2), rs.getInt(3),
rs.getInt(4), rs.getString(5)));
}
rs.close();
pstmtGetRows.close();
return list;
}
}
-
package nr3.model;
public class Album {
private String tittel;
private String artist;
private int spor;
private int utgitt;
private String sjanger;
public Album (String artist, String tittel, int spor, int utgitt, String sjanger){
setArtist(artist);
setTittel(tittel);
setUtgitt(utgitt);
setSpor(spor);
setSjanger(sjanger);
}
public Album(){
this(null, null, 0, 0, null);
}
public void setTittel(String tittel){
this.tittel = tittel;
}
public void setArtist(String artist){
this.artist = artist;
}
public void setSpor(int spor) {
this.spor = spor;
}
public void setUtgitt(int utgitt) {
this.utgitt = utgitt;
}
public void setSjanger(String sjanger) {
this.sjanger = sjanger;
}
public String getTittel() {
return tittel;
}
public String getArtist() {
return artist;
}
public int getSpor() {
return spor;
}
public int getUtgitt() {
return utgitt;
}
public String getSjanger() {
return sjanger;
}
public String toString(){
return getTittel() + " (" + getArtist() + ")" + " Utgitt: "
+ getUtgitt();
}
}
2. src/nr3/servlets
package nr3.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import nr3.model.Album;
import nr3.model.MusikkHandler;
public class MusikkValg extends HttpServlet {
private static final long serialVersionUID = 428937262021570370L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String genre = request.getParameter("sjanger");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
MusikkHandler mh;
out.println("<html>");
out.println("<head>");
out.println("<title>Musikk</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>MUSIKK-ANBEFALINGER</h1>");
out.println("<br/>");
out.println("<br/>");
out.println("<h3>Da bør du kanskje forsøke en av disse:</h3>");
out.println("<br/>");
out.println("<br/>");
try {
mh = new MusikkHandler(" ", " ", " ", " ");
for (Album a : mh.getRows(genre))
out.println("<p>" + a + "</p>");
} catch (SQLException e) {
e.printStackTrace(out);
}
out.println("</body>");
out.println("</html>");
}
}
Update: I've got the following error stacktrace in the browser:
java.sql.SQLException: No suitable driver found for
jdbc:mysql://localhost/pg3100 at
java.sql.DriverManager.getConnection(Unknown Source) at
java.sql.DriverManager.getConnection(Unknown Source) at
db.ConnectToDB.(ConnectToDB.java:10) at
nr3.model.MusikkHandler.(MusikkHandler.java:20) at
nr3.servlets.MusikkValg.doGet(MusikkValg.java:39) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:618) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:534)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1081)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
at
org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2381)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2370)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

First, you must register your driver at the beginning so DriverManager can user it when getting a connection. It might vary on the implementation.
DriverManager.registerDriver (new com.mysql.jdbc.Driver());
or
Class.forName("com.mysql.jdbc.Driver");
Then you can perform a getConnection() because you'll have a driver registered to be used by DriverManager.
Second: /webapps/ROOT/WEB-INF/lib is a different context and its libraries won't be available for your app unless you are setting the context path of your app as shown in this question. If you wanna add it, try placing your JDBC driver on /webapps/<yourapp>/lib first. Tomcat lib should work as well (but it's not nice when you distribute your app, might conflict with other apps deployed there, using different versions of the driver, etc.)
Third: When asking here, try to reduce your verifiable example to something readable. There's a lot of code which is not relevant to your problem. Reducing makes it easier to read your question and provide help.

Related

when I try to update the values in table I get java.lang.NumberFormatException: For input string: "{id}(id=1)"

In spring boot using Jsp, I have created a Employee management System where we can add,update and delete employee. but the problem is when I try to update the values in table I get NumberFormatException error. I couldn't add Employee Details also so, I had fetch values into table from database. the problem is in DAO.Class where I should do some changes. I've tried many ways but nothing works for me. so, please give me a solution for this problem.
EmployeeDao class
package net.javaguides.ems.controller;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import net.javaguides.ems.entity.Employee;
#Service()
public class EmployeeDao
{
#Autowired
JdbcTemplate jdbcTemplate;
/*
* public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate =
* jdbcTemplate; }
*/
public List<Employee> getAllEmployees()
{
//List<Map<String,String>> data = new ArrayList<Map<String, String>>();
return jdbcTemplate.query("select * from employee", new RowMapper<Employee>()
{
public Employee mapRow(ResultSet rs, int row) throws SQLException
{
Employee emp = new Employee();
emp.setId(rs.getLong("id"));
emp.setFirstName(rs.getString("first_name"));
emp.setLastName(rs.getString("last_name"));
emp.setEmail(rs.getString("email"));
emp.setGender(rs.getString("gender"));
emp.setMarriage(rs.getString("marriage"));
emp.setBirthday(rs.getDate("birthday"));
emp.setWorkat(rs.getString("workat"));
emp.setDepartment(rs.getString("department"));
return emp;
}
});
}
public long saveEmployee(Employee p)
{
/*
* SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
* System.out.println("DOB ::"+p.getBirthday()+"::"+format1.format(p.getBirthday
* ()));
*/
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
format1.format(p.getBirthday());
/*
* String sql
* ="insert into emsystem.employee(id,birthday,department,email,first_name,gender,last_name"
* + ",marriage,workat) values" + " ('"+p.getFirstName()+"','1','2021-08-06'" +
* ",'"+p.getDepartment()+"','"+p.getEmail()+"','"+p.getLastName()+"'," +
* "'"+p.getGender()+"','"+p.getLastName()+"','"+p.getMarriage()+"','"+p.
* getWorkat()+"');";
*/
String sql="insert into employee(id,firstName,lastName,email,gender,marriage,birthday,workat,department) values "
+
"('"+p.getId()+"',"+p.getFirstName()+","+p.getLastName()+","+p.getEmail()+","+p.getGender()
+","+p.getMarriage()+","+p.getBirthday()+","+p.getWorkat()+",'"+p.getDepartment()+"')";
System.out.println("SQL ::"+sql);
return jdbcTemplate.update(sql);
// return jdbcTemplate.update(sql);
}
//#Deprecated
public Employee getEmployeeById(Long id)
{
String sql="select * from employee where id=?";
//return jdbcTemplate.queryForObject("select * from employee where id=?",new BeanPropertyRowMapper<Employee>(Employee.class), new Object[]{id});
return jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Employee>(Employee.class),new Object[]{id});
}
public long updateEmployee(Employee p)
{
String sql="update employee set firstName='"+p.getFirstName()+"', lastName="+p.getLastName()+",email="+p.getEmail()+",gender="+p.getGender()+",marriage="+p.getMarriage()+",birthday="+p.getBirthday()+",workat="+p.getWorkat()+",department='"+p.getDepartment()+"' where id="+p.getId()+"";
return jdbcTemplate.update(sql);
}
public long deleteEmployeeById(Long id)
{
String sql="delete from employee where id="+id+"";
return jdbcTemplate.update(sql);
}
}
Error
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun Jul 11 11:01:50 IST 2021
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{id}(id=1)"
org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "{id}(id=1)"
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:133)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:170)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1063)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:831)
Caused by: java.lang.NumberFormatException: For input string: "{id}(id=1)"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Long.parseLong(Long.java:714)
at java.base/java.lang.Long.valueOf(Long.java:1166)
at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:214)
at org.springframework.beans.propertyeditors.CustomNumberEditor.setAsText(CustomNumberEditor.java:115)
at org.springframework.beans.TypeConverterDelegate.doConvertTextValue(TypeConverterDelegate.java:429)
at org.springframework.beans.TypeConverterDelegate.doConvertValue(TypeConverterDelegate.java:402)
at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:155)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:73)
at org.springframework.beans.TypeConverterSupport.convertIfNecessary(TypeConverterSupport.java:53)
at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:696)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:125)
... 47 more
Controller
package net.javaguides.ems.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import net.javaguides.ems.entity.Employee;
#Controller // Controller Layer holds all Spring MVC Controllers
public class EmployeeController {
#Autowired
EmployeeDao employeeDao;
/*
* #GetMapping("/") //from this method will call findPaginated method -> this
* will return paginated Employees. public String viewHomePage(Model model) {
* return findPaginated(1, model); }
*/
//handler method to handle list employees and return mode and view
#GetMapping("/employees")
public String listEmployees(Model model)
{
model.addAttribute("employees", employeeDao.getAllEmployees());
return "employees";
}
#GetMapping("/employees/new")
public String createEmployeeForm(Model model)
{
//Create empty employee object to hold employee form data
Employee employee = new Employee();
model.addAttribute("employee", employee);
return "create_employee";
}
#PostMapping("/employees")
public String saveEmployee(#ModelAttribute("employee") Employee employee,
BindingResult bindingResult)
{
//Here, we r using ModelAttribute to directly bind form data to the employee object.
if (bindingResult.hasErrors())
{
return "create_employee";
}
else
{
employeeDao.saveEmployee(employee);
return "redirect:/employees";
}
}
#GetMapping("/employees/edit/{id}")
public String editEmployeeForm(#PathVariable Long id, Model model) //PathVariable Annotation is to get the id.
{
model.addAttribute("employee", employeeDao.getEmployeeById(id));
return "edit_employee";
}
#PostMapping("/employees/{id}")
public String updateEmployee(#PathVariable Long id,
#ModelAttribute("employee") Employee employee, BindingResult bindingResult, Model model)
{
// save updated employee object
if (bindingResult.hasErrors())
{
return "create_employee";
}
else
{
// get employee from database by id
Employee existingEmployee = employeeDao.getEmployeeById(id);
existingEmployee.setId(id);
existingEmployee.setFirstName(employee.getFirstName());
existingEmployee.setLastName(employee.getLastName());
existingEmployee.setEmail(employee.getEmail());
existingEmployee.setGender(employee.getGender());
existingEmployee.setMarriage(employee.getMarriage());
existingEmployee.setBirthday(employee.getBirthday());
existingEmployee.setWorkat(employee.getWorkat());
existingEmployee.setDepartment(employee.getDepartment());
employeeDao.updateEmployee(existingEmployee);
return "redirect:/employees";
}
}
// handler method to handle delete employee request
#GetMapping("/employees/{id}")
public String deleteEmployee(#PathVariable Long id)
{
employeeDao.deleteEmployeeById(id);
return "redirect:/employees";
}
}
DB configuration
package net.javaguides.ems;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
#Configuration
public class DBConfiguration {
#Autowired
private Environment env;
#Bean(name="dataSource")
public DataSource getDatasource() {
DriverManagerDataSource datasource = new DriverManagerDataSource();
//DataSource datasource = new DataSource();
datasource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));//this.dbDriver
datasource.setUrl(env.getProperty("spring.datasource.url"));//this.dbURL
datasource.setUsername(env.getProperty("spring.datasource.username"));//this.dbUserName
datasource.setPassword(env.getProperty("spring.datasource.password"));//this.dbPassword
return datasource;
}
#Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
/*
* #Bean("resourceBundle") public ResourceBundle resourceBundle() {
* ResourceBundle rb = ResourceBundle.getBundle("query"); return rb; }
*/
}
You haven’t included the URL that you are using to make the request, but, having seen your controller’s code, I think that’s the problem.
Judging by the error message, you are making a GET request to something like /employees/{id}(id=1). Your #GetMapping is /employees/{id} so everything after the second / becomes the value of id. Due to you use of #PathVariable, Spring MVC tries to convert "{id}(id=1)" to a Long for your id argument and it fails.
If my assumption about the URL to which you are making the request is correct, you can fix the problem by changing the URL that you’re using. Assuming that the employee’s ID is 1, it should be /employees/1.
The problem is that when you pass a parameter using the URL directly, for example
/employees/1
you are passing a String, whetever you like it or not. So the best solution would be
(this is one of the controllers, similar solutions applies to the others)
#GetMapping("/employees/{id}")
public String deleteEmployee(#PathVariable String id)
{
try {
Long longid = Long.valueOf(id);
catch (Exception e)
{
//Exception Handling here (maybe an error page, idk)
}
employeeDao.deleteEmployeeById(longid);
return "redirect:/employees";
}
Plus, I strongly recommend you to use custom repository, so you don't need to create standard queries like insertion, deletion, and standard selection everytime (look for CrudRepository or JpaRepository)

Upload pdf in HTML and Deserialize json file

I'm trying to upload a file in html and then send it to my database via restangular.
My frontend is a combination of angular with typescript but the upload is a form.
<form enctype="multipart/form-data">
<fieldset class="form-group" ng-repeat="field in $ctrl.metadata.fields">
<label ng-if="field.inputType !== 'hidden'" for="{{field.propertyKey}}"><strong>{{field.name}}</strong></label>
<input ng-if="field.inputType !== 'select' && field.inputType !== 'file'" class="form-control" type="{{field.inputType}}" name="{{field.propertyKey}}" id="{{field.propertyKey}}" ng-model="$ctrl.data[field.propertyKey]"/>
<input ng-if="field.inputType === 'file'" class="form-control" ngf-select type="{{field.inputType}}" name="{{field.propertyKey}}" id="{{field.propertyKey}}" ng-model="$ctrl.data[field.propertyKey]"/>
<sp-dropdown ng-if="field.inputType === 'select'" value="$ctrl.data[field.propertyKey]" api-domain="field.linkedObjectApiDomain" linked-object-name="field.linkedObjectName"></sp-dropdown>
</fieldset>
<button class="btn btn-primary" ng-click="$ctrl.save({item: $ctrl.data})">Save</button>
<button ng-if="$ctrl.metadata.buttons.hasOpen" class="btn btn-primary" ng-click="$ctrl.open()">Open</button>
</form>
I did the databinding of the file with ng-file-upload.
Upon saving we enter this typescript save method.
public save(item: any): any {
console.log("item to save is ", item);
console.log("rapport is ", item["rapport"]);
if (item.id === undefined) {
this.restService.save(this.metadata.apiDomain, item).then((addedItem: any) => {
toastr.success(`${addedItem.naam} successfully created.`, `Overzicht Dossiers Created`);
});
} else {
this.restService.update(this.metadata.apiDomain, item).then((updatedItem: any) => {
toastr.success(`${updatedItem.naam} successfully updated.`, `Overzicht Dossiers Updated`);
});
}
}
The second log with the file gives the json:
lastModified:1463402787393
lastModifiedDate:Mon May 16 2016 14:46:27 GMT+0200 (Romance (zomertijd))
name:"Rapport.pdf"
size:83605
type:"application/pdf"
upload:Promise
webkitRelativePath:""
__proto__:File
On server side I'm using a spring project which I didn't set up myself but the important files are my class which should store this data
Dossier
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.lca.data.entities;
import be.ugent.sherpa.entity.BaseEntity;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
/**
*
* #author Sam
*/
#Entity
//#JsonDeserialize(using = DossierDeserializer.class)
//#JsonSerialize(using = DossierSerializer.class)
public class Dossier extends BaseEntity{
private String externDossierNr;
private String internDossierNr;
private Date datum;
private Boolean doc;
private Date refKlantDatum;
private String refKlantVerwijzing;
private String verantw;
#OneToOne(fetch=FetchType.LAZY, mappedBy="dossier")
private Offerte offerte;
private String status;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "persoon")
private Persoon persoon;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "OrganisatieFirma")
private OrganisatieFirma organisatieFirma;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "OrganisatieIntern")
private OrganisatieIntern organisatieIntern;
#Lob
#Column(length=100000)
private byte[] rapport;
public Offerte getOfferte() {
return offerte;
}
public void setOfferte(Offerte offerte) {
this.offerte = offerte;
}
public byte[] getRapport() {
return rapport;
}
public void setRapport(byte[] rapport) {
this.rapport = rapport;
}
public OrganisatieFirma getOrganisatieFirma() {
return organisatieFirma;
}
public String getExternDossierNr() {
return externDossierNr;
}
public void setExternDossierNr(String externDossierNr) {
this.externDossierNr = externDossierNr;
}
public String getInternDossierNr() {
return internDossierNr;
}
public void setInternDossierNr(String internDossierNr) {
this.internDossierNr = internDossierNr;
}
public void setOrganisatieFirma(OrganisatieFirma organisatieFirma) {
this.organisatieFirma = organisatieFirma;
}
public OrganisatieIntern getOrganisatieIntern() {
return organisatieIntern;
}
public void setOrganisatieIntern(OrganisatieIntern organisatieIntern) {
this.organisatieIntern = organisatieIntern;
}
public Persoon getPersoon() {
return persoon;
}
public void setPersoon(Persoon persoon) {
this.persoon = persoon;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public Date getRefKlantDatum() {
return refKlantDatum;
}
public void setRefKlantDatum(Date refKlantDatum) {
this.refKlantDatum = refKlantDatum;
}
public String getRefKlantVerwijzing() {
return refKlantVerwijzing;
}
public void setRefKlantVerwijzing(String refKlantVerwijzing) {
this.refKlantVerwijzing = refKlantVerwijzing;
}
public String getVerantw() {
return verantw;
}
public void setVerantw(String verantw) {
this.verantw = verantw;
}
public Boolean getDoc() {
return doc;
}
public void setDoc(Boolean doc) {
this.doc = doc;
}
}
and my repository for this class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package be.ugent.lca.data.repository;
import be.ugent.lca.data.entities.Dossier;
import be.ugent.lca.data.query.DossierQuery;
import be.ugent.sherpa.repository.RestRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
/**
*
* #author Sam
*/
#RepositoryRestResource(collectionResourceRel = "dossiers", path = "dossiers")
public interface DossierRepository extends RestRepository<Dossier, DossierQuery<?>>{
}
When trying to save a file to my database the server gives this exception
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of byte[] out of START_OBJECT token
This led me to believe that I have to write my own deserializer for Dossier
Thus:
package be.ugent.lca.data.entities.deserializers;
import be.ugent.lca.data.entities.Dossier;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
public class DossierDeserializer extends JsonDeserializer {
#Override
public Dossier deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode root = oc.readTree(jsonParser);
Dossier dossier = new Dossier();
dossier.setExternDossierNr(root.get("externDossierNr").asText());
dossier.setInternDossierNr(root.get("internDossierNr").asText());
return dossier;
}
}
But my problem is that I don't know how exactly to deserialize the file json, since writing out root.get("rapport") gives back an empty string.
Any help would be much appreciated.
I've worked out the file upload.
First of all I split the file upload from the rest of my data so I won't have to rewrite the automatic deserialization for everything that does work.
this.restService.save(this.metadata.apiDomain, item).then((addedItem: any) => {
toastr.success(`${addedItem.naam} successfully created.`, `Overzicht Dossiers Created`);
console.log("created item ", addedItem);
var fd = new FormData();
fd.append("rapport", item["rapport"]);
this.restService.one('dossiers/' + addedItem.id + '/rapport').withHttpConfig({transformRequest: angular.identity}).customPOST(fd, '', undefined, {'Content-Type': undefined}).then(
(addedDossier: any) => {
console.log("posted dossier ", addedDossier);
}
);
});
In the callback of my normal save I do the custom post to dossiers/{id}/rapport for this I need a custom controller.
#BasePathAwareController
#RequestMapping("/dossiers/{id}")
#ExposesResourceFor(Dossier.class)
public class DossierController {
The BasePathAwawareController makes sure that all automatically generated paths that you don't override keep existing.
#Autowired
private DossierRepository dossierRepository;
With this I inject my repository to connect to my database.
#RequestMapping(path = "/rapport", method = RequestMethod.POST)//,headers = "content-type=multipart/form-data")
public #ResponseBody String postRapport(#PathVariable("id") Long id,#RequestParam("rapport") MultipartFile file) {
String name = "rapport";
System.out.println("Entered custom file upload with id " + id);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
Dossier dossier = dossierRepository.findOne(id);
dossier.setRapport(bytes);
dossierRepository.save(dossier);
return "You successfully uploaded " + name + " into " + name + "-uploaded !";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
} else {
return "You failed to upload " + name + " because the file was empty.";
}
}
Like this I'm able to successfully upload my file.

Delete row from database through Servlet

I had a problem in my servlet regarding deleting record from my database.
Please look over my servlet code and please do correct me. Thank you in advance
DeleteRow servlet is working perfectly right when a single ID is given manually.
Scenario is:
ManageSinger.java servlet displays the records in database along with a "Delete" hyperLink in every row. But problem is whenever i try to press delete button.. it receives a null value for ID in deleterow.java servlet ..
Please guide me from here how can only that corresponding ID can be pass to another servlet.
ManageSinger.java
package com.ea.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class ManageSinger extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
PrintWriter out = res.getWriter();
res.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from singerdetails");
out.println("<form method = \"post\">");
out.println("<table border=1 width=50% height=50%>");
out.println("<tr><th align=\"center\">Singer Name</th><th align=\"center\">StageName</th><th align=\"center\">Language</th><th></th><tr>");
while (rs.next()) {
String singername = rs.getString("singername");
String stagename = rs.getString("stagename");
String language = rs.getString("language");
String id = rs.getString("userID");
HttpSession session = req.getSession(true);
session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
}
out.println("</table>");
out.println("</form");
out.println("</body></html>");
con.close();
}
catch (Exception e) {
e.printStackTrace();
}finally{
}
}
}
DeleteRow.java
package com.ea.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.jws.Oneway;
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.servlet.http.HttpSession;
public class DeleteRow extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Connection con;
PreparedStatement st;
ResultSet rs;
try
{
HttpSession session = req.getSession(true);
Class.forName("com.mysql.jdbc.Driver");
String id = (String) session.getAttribute("id");
System.out.println(id);
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/EATWO","root","");
st= con.prepareStatement("delete from singerdetails where userID = ?");
st.setString(1, id);
st.executeUpdate();
int i = st.executeUpdate();
if(i!=0)
pw.println("Deleting row...");
else if (i==0)
{
pw.println("<br>Row has been deleted successfully.");
}
}
catch(SQLException sx)
{
pw.println(sx);
}
catch(ClassNotFoundException cx)
{
pw.println(cx);
}
}
}
In DeleteRow.java say you should do String id = (String) session.getAttribute("userID"); instead of (String) session.getAttribute("id") .In ManageSinger.java you are setting the attribute as follows session.setAttribute("userID",id);
As per your current ManageSinger.java only the last userID gets set in session, which is why the last userID gets deleted. In ManageSinger.java instead of setting the userID as session attribute you can set it as url parameter for each record.
Following lists the changes:
//HttpSession session = req.getSession(true);
//session.setAttribute("userID",id);
out.println("<tr><td align=\"center\">" + singername + "</td><td align=\"center\">" + stagename + "</td><td align=\"center\">" + language + "</td><td align=\"center\">Delete</td></tr>");
In DeleteRow.java instead of getting the userID from session, you can get it from the url as following:
//HttpSession session = req.getSession(true);
//String id = (String) session.getAttribute("id");
String id = req.getParameter("userID").toString();

Connection pool issue with Bean Datasource - Jasperserver

I have created a bean data source to connect to my database. My objective of creating this datasource is to switch datasource as per a parameter given. But when I run reports using the bean data source, it does not release the connection back into the pool. My connection pool size is 20, so when I run the 21st report, server hangs printing the following message on the JConsole
Name: pool-7-thread-9
State: WAITING on org.apache.commons.pool.impl.GenericObjectPool#1f8ed84
Total blocked: 0 Total waited: 4
Stack trace:
java.lang.Object.wait(Native Method)
java.lang.Object.wait(Object.java:485)
org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:748)
org.apache.commons.dbcp.PoolingDataSource.getConnection(PoolingDataSource.java:95)
com.loits.jasper.ds.SwitchDS.setReportParameterValues(SwitchDS.java:75)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl.fillReport(EngineServiceImpl.java:1725)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl$ReportFill.runWithDataSource(EngineServiceImpl.java:1086)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl$ReportFill.runReport(EngineServiceImpl.java:1015)
com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.EngineServiceImpl$ReportRunnable.run(EngineServiceImpl.java:908)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Here what I have done in my bean
package com.loits.jasper.ds;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.sql.SQLException;
import net.sf.jasperreports.engine.JRParameter;
import org.springframework.security.context.SecurityContextHolder;
import com.jaspersoft.jasperserver.api.metadata.jasperreports.domain.ReportDataSource;
import com.jaspersoft.jasperserver.api.metadata.jasperreports.service.ReportDataSourceService;
import com.jaspersoft.jasperserver.api.metadata.user.domain.Role;
import com.jaspersoft.jasperserver.api.metadata.user.domain.client.ProfileAttributeImpl;
import com.jaspersoft.jasperserver.api.metadata.user.domain.impl.client.MetadataUserDetails;
import com.jaspersoft.jasperserver.api.common.domain.ExecutionContext;
import com.jaspersoft.jasperserver.api.common.service.BeanForInterfaceImplementationFactory;
import com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JdbcDataSourceService;
import com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.JdbcReportDataSourceServiceFactory;
import com.jaspersoft.jasperserver.war.common.JasperServerUtil;
import com.jaspersoft.jasperserver.api.metadata.common.service.RepositoryService;
public class SwitchDS implements ReportDataSourceService {
private JdbcDataSourceService connection;
private RepositoryService repositoryService;
private BeanForInterfaceImplementationFactory dataSourceServiceFactory;
// private DataSourceServiceFactory dataSourceServiceFactory;
public SwitchDS(RepositoryService repositoryService,
BeanForInterfaceImplementationFactory dsServiceFactory) {
super();
this.repositoryService = repositoryService;
this.dataSourceServiceFactory = dsServiceFactory;
System.out.println("repositoryService " + repositoryService);
System.out.println("dataSourceServiceFactory "
+ dataSourceServiceFactory);
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public void setReportParameterValues(Map parametersValue) {
String ds_name = (String) parametersValue.get("P_SCM");
String ds_uri = "";
if(ds_name.equalsIgnoreCase("D_001_S")){
ds_uri = "/datasources/lolc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_005_S")){
ds_uri = "/datasources/lofc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_009_S")){
ds_uri = "/datasources/lomc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_010_S")){
ds_uri = "/datasources/clc_fusion";
}
else if(ds_name.equalsIgnoreCase("D_025_S")){
ds_uri = "/datasources/lofac_fusion";
}
if(connection == null){
connection = getRepositoryDatasource(ds_uri);
}
try {
parametersValue.put(JRParameter.REPORT_CONNECTION, connection
.getDataSource().getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}
public JdbcDataSourceService getRepositoryDatasource(String repositoryURI) {
try {
ExecutionContext context = JasperServerUtil.getExecutionContext();
ReportDataSource datasource = (ReportDataSource) repositoryService
.getResource(context, repositoryURI);
System.out.println("datasource " + datasource.getName());
System.out.println("datasource class " + datasource.getClass());
JdbcReportDataSourceServiceFactory factory = (JdbcReportDataSourceServiceFactory) dataSourceServiceFactory
.getBean(datasource.getClass());
JdbcDataSourceService DSservice = (JdbcDataSourceService) factory
.createService(datasource);
return DSservice;
} catch (Exception ex) {
System.out.println(ex);
return null;
}
}
#Override
public void closeConnection() {
if (connection != null) {
connection.closeConnection();
System.out.println("Connection closed .. ");
}
}
public static void main(String[] args) {
}
}
Seems to me like you're closing the connection instead of returning it to the pool.
Simon

tomcat ported to Google App Engine

I had the period webservice originally tomcat server.
Now I want to segment webservice transplant to GAE.
I transplant was successful.
Implementation, but this error message is displayed.
Will this cause the possibility of error?
MY CODE:
public class LOAD extends HttpServlet{
static String JBx;
static String JBy;
static String JBSx;
static String JBSy;
static String gps;
String a;
int i;
private Connection con = null; //Database objects
private Statement stat = null;
private ResultSet rs = null;
private PreparedStatement pst = null;
private String dropdbSQL = "DROP TABLE User ";
private String createdbSQL = "CREATE TABLE User (" +
" id INTEGER " +
" , name VARCHAR(20) " +
" , passwd VARCHAR(20))";
private String insertdbSQL = "insert into User(id,gps,recopy) " +
"select ifNULL(max(id),0)+1,?,? FROM User";
private String selectSQL = "select * from User ";
public static void main(String[] args)
{
}
public void SelectTable()
{
try
{
stat = con.createStatement();
rs = stat.executeQuery(selectSQL);
while(rs.next())
{
JBSx =rs.getString("gps");
JBSx="<div id=dd>"+JBSx+"</div>";
if(JBx!=null){
JBx=JBx+JBSx;
}else
{
JBx=JBSx;
}
JBSy =rs.getString("recopy");
JBSy="<div id=ff>"+JBSy+"</div>";
if(JBy!=null){
JBy=JBy+JBSy;
}
else
{
JBy=JBSy;
}
}
}
catch(SQLException e)
{
System.out.println("DropDB Exception :" + e.toString());
}
// finally
// {
// Close();
// }
}
private void Close()
{
try
{
if(rs!=null)
{
rs.close();
rs = null;
}
if(stat!=null)
{
stat.close();
stat = null;
}
if(pst!=null)
{
pst.close();
pst = null;
}
}
catch(SQLException e)
{
System.out.println("Close Exception :" + e.toString());
}
}
public LOAD()
{
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://hl2dm.synology.me:3306/teama",
"abc","");
}
catch(ClassNotFoundException e)
{
System.out.println("DriverClassNotFound :"+e.toString());
}
catch(SQLException x) {
System.out.println("Exception :"+x.toString());
}
}
public void doGet(HttpServletRequest rq, HttpServletResponse rp)
throws ServletException, IOException{
JBx=null;
JBy=null;
JBSx=null;
JBSy=null;
rq.setCharacterEncoding("UTF-8");
// String gps = rq.getParameter("gps");
LOAD test = new LOAD();
test.SelectTable();
HttpSession session = rq.getSession();
//session.invalidate();
// session.removeAttribute("reportx");
session.setMaxInactiveInterval(3600);
session.setAttribute("reportx",JBx);
session.setAttribute("reporty",JBy);
rp.sendRedirect(rp.encodeRedirectURL("LOADPOST"));
}
public void doPost(HttpServletRequest rq, HttpServletResponse rp)
throws ServletException, IOException{
doGet(rq, rp);
}
}
Error message:
HTTP ERROR 500
Problem accessing /LOAD. Reason:
INTERNAL_SERVER_ERROR
Caused by:
java.lang.NullPointerException
at a.b.c.LOAD.SelectTable(LOAD.java:52)
at a.b.c.LOAD.doGet(LOAD.java:149)
at a.b.c.LOAD.doPost(LOAD.java:160)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:123)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:61)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.google.appengine.tools.development.BackendServersFilter.doFilter(BackendServersFilter.java:97)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:94)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:409)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:938)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:755)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Powered by Jetty://
To answer your question, yes it will cause definite failure.
There is no MySql instance to connect to on AppEngine. You need instead to use Google Cloud SQL.
It goes something like this:
DriverManager.registerDriver(new AppEngineDriver());
con = DriverManager.getConnection("jdbc:google:rdbms://instance_name/guestbook");
See: this AppEngine guide for the complete set of steps.
Note: To use the development server with a local MySQL instance, see https://developers.google.com/appengine/docs/java/cloud-sql/developers-guide#using_the_java_development_server