Я сейчас работаю над проектом веб-разработчика, используя netbeans 8.2 + glassfish 4.1
Мой код кажется хорошим, так как он не показывает никаких типов ошибок.Однако, когда я пытаюсь запустить его и вставить код в почтальон Google, мой ответ будет выглядеть так:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<clubss></clubss>
Просто чтобы убедиться, что мой проект предназначен для футбольных команд.В настоящее время у меня есть стол только с 3 командами, просто чтобы он был коротким.Странная вещь, которую я заметил, это последняя строка - "clubss".Я искал свой код и нигде не смог найти слово «clubss» - у меня есть куча «club» + «club», но нигде нет «clubss».
Однако, самое важное для меня намомент - запустить все это и показать 3 команды в почтальоне.
Если вам нужен какой-либо код, просто дайте мне знать.Во-первых, я их не вставлял, потому что: а) может оказаться, что в этом нет необходимости; б) они довольно длинные, и сообщение будет выглядеть плохо.Однако, если вам это нужно, я обновлю его немедленно.
Заранее спасибо, любая помощь приветствуется.ОБНОВЛЕНИЕ
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="clubs")
// define the field order
@XmlType(propOrder={"id", "name", "year", "country", "league",
"picture", "description"})
public class Clubs {
private int id;
private String name, year, country, league, picture, description;
// JAXB requires a default ctor
public Clubs(){
}
public Clubs(int id, String name, String year, String country, String league, String picture, String description) {
this.id = id;
this.name = name;
this.country = country;
this.year = year;
this.league = league;
this.picture = picture;
this.description = description;
}
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
@XmlElement
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@XmlElement
public String getLeague() {
return league;
}
public void setLeague(String league) {
this.league = league;
}
@XmlElement
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
@XmlElement
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Clubs{" + "id=" + id + ", name=" + name + ", country=" + country + ", league=" + league + ", year=" + year + ", picture=" + picture + ", description=" + description + '}';
}
}
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClubsDAO {
private Connection con = null;
public static void main(String[] args) {
ClubsDAO dao = new ClubsDAO();
int nextId = dao.getNextClubId();
System.out.println(nextId);
}
public ClubsDAO() {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/CD_WD3_DB",
"sean", "sean");
System.out.println("OK");
} catch (ClassNotFoundException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("ClassNotFoundException");
ex.printStackTrace();
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
}
public int updateClubs(Clubs clubs){
int rowsUpdated=0;
try{
PreparedStatement ps = con.prepareStatement(
"UPDATE APP.CLUB SET NAME=?, YR=?, COUNTRY=?,"
+ "LEAGUE=?, DESCRIPTION=?, PICTURE=? WHERE "
+ "ID = ?");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
rowsUpdated = ps.executeUpdate();
}catch (Exception e){
System.err.println("Exception in executeUpdate()");
e.printStackTrace();
return -1;
}
return rowsUpdated;// 1
}
public int addClubs(Clubs clubs){
int numRowsInserted=0;
try{
PreparedStatement ps = con.prepareStatement(
"INSERT INTO APP.CLUB " // CLUBS??
+ "(ID, NAME, YR, COUNTRY, "
+ "LEAGUE, DESCRIPTION, PICTURE) "
+ "VALUES (?,?,?,?,?,?,?)");
ps.setString(1, clubs.getName());
ps.setString(2, clubs.getYear());
ps.setString(4, clubs.getCountry());
ps.setString(5, clubs.getLeague());
ps.setString(6, clubs.getDescription());
ps.setString(7, clubs.getPicture());
ps.setInt(8, clubs.getId());
numRowsInserted = ps.executeUpdate();
}catch (Exception e){
e.printStackTrace();
return -1;
}
return numRowsInserted;
}
public int getNextClubId(){
int nextClubId = -1;
try{
PreparedStatement ps =
con.prepareStatement(
"SELECT MAX(ID) AS MAX_ID FROM APP.CLUB");
ResultSet rs = ps.executeQuery();
if(!rs.next()){ // set the db cursor
return -1;
}
nextClubId = rs.getInt("MAX_ID") + 1;
}catch(Exception e){
e.printStackTrace();
return -1;
}
return nextClubId;
}
public List<Clubs> findAll() {
List<Clubs> list
= new ArrayList<>();
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB ORDER BY ID");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
//Logger.getLogger(ClubsDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return list;
}
public Clubs processRow(ResultSet rs) throws SQLException {
Clubs clubs = new Clubs();
clubs.setId(rs.getInt("id"));
clubs.setName(rs.getString("name"));
clubs.setCountry(rs.getString("country"));
clubs.setLeague(rs.getString("league"));
clubs.setYear(rs.getString("yr"));
clubs.setPicture(rs.getString("picture"));
clubs.setDescription(rs.getString("description"));
return clubs;
}
public Clubs findById(int clubId) {
Clubs club = null;
try {
PreparedStatement pstmt
= con.prepareStatement("SELECT * FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) { // !F => T
return null;
}
// we have a record
club = processRow(rs);
} catch (SQLException ex) {
//Logger.getLogger(ClubDAO.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("SQLException");
ex.printStackTrace();
}
return club;
}
public List<Clubs> findByName(String name) {
List<Clubs> list
= new ArrayList<Clubs>();
try {
PreparedStatement pstmt
= con.prepareStatement(
"SELECT * FROM APP.CLUB "
+ "WHERE UPPER(NAME) "
+ "LIKE ? ORDER BY NAME");
pstmt.setString(1, "%" + name.toUpperCase() + "%");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
list.add(processRow(rs));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return list;
}
public int deleteById(int clubId){
int numRowsDeleted=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB WHERE ID=?");
pstmt.setInt(1, clubId);
numRowsDeleted = pstmt.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}
return numRowsDeleted; // 0 == failure; 1 == success
}
public int deleteAllClubs(){
int result=0;
try{
PreparedStatement pstmt =
con.prepareStatement("DELETE FROM APP.CLUB");
result = pstmt.executeUpdate(); // 0 == failure; >=1 == success
}catch (Exception e){
e.printStackTrace();
}
return result; // 0 == failure; >=1 == success
}
}
package rest.clubs;
// link into JAX-RS
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("/rest")
public class RestConfig extends Application{
@Override
public Set<Class<?>> getClasses(){
final Set<Class<?>> classes =
new HashSet<Class<?>>();
classes.add(ClubsResource.class);
return classes;
}
}
package rest.clubs;
import dao.Clubs;
import dao.ClubsDAO;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.OPTIONS;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.GenericEntity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Path("/clubs")
public class ClubsResource {
// this class responds to ".../rest/clubs"
private static ClubsDAO dao = new ClubsDAO();
@Context
private UriInfo context;
public ClubsResource() {
}
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getAllClubs() {
System.out.println("get all");
List<Clubs> clubList
= dao.findAll();
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
@POST
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response addClubs(Clubs newClubs) {
System.out.println("POST - " + newClubs);
// the 'id' field in the request entity body is ignored!
int nextClubId = dao.getNextClubId();
newClubs.setId(nextClubId);
System.out.println("POST: nextClubId == " + nextClubId);
// now, our Clubobject is set up; insert into db
dao.addClubs(newClubs);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",
String.format("%s%s",
context.getAbsolutePath().toString(),
newClubs.getId()))
.header("Access-Control-Allow-Origin", "*")
.entity(newClubs)
.build();
}
@OPTIONS
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForAllClubs() {
System.out.println("OPTIONS for all");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get all
api.add("POST");// add
api.add("DELETE");// delete all
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
@OPTIONS
@Path("{clubId}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response optionsForOneClub() {
System.out.println("OPTIONS for one");
// what is the verb set for this URI?
// what is the API supported?
Set<String> api = new TreeSet<>();
api.add("GET");// get one
api.add("PUT");// update (or add)
api.add("DELETE");// delete one
api.add("HEAD");// get with no entity body
return Response
.noContent()
.allow(api)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "DELETE, PUT, GET")
.header("Access-Control-Allow-Headers", "Content-Type")
.build();
}
@PUT
@Path("{clubId}")
@Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response updateOneClub(Clubs updateClub, @PathParam("clubId") int clubId) {
System.out.println("PUT - " + updateClub);
if (clubId == updateClub.getId()) {
// entity body id == id in URI
if (dao.findById(clubId) == null) {
// id not in db, create
dao.addClubs(updateClub);
// now set up the HTTP response as per the HTTP spec
return Response
.status(Response.Status.CREATED)
.header("Location",context.getAbsolutePath().toString())
.header("Access-Control-Allow-Origin", "*")
.entity(updateClub)
.build();
} else {
// id in db, update
dao.updateClubs(updateClub);
return Response
.status(Response.Status.OK)
.entity(updateClub)
.build();
}
} else {
// id in xml <> id in URI
return Response
.status(Response.Status.CONFLICT)
.entity("<conflict idInURI='"+clubId+"' idInEntityBody='"+updateClub.getId()+"' />")
.build();
}
}
@HEAD
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForAllClubs() {
System.out.println("HEAD");
return Response
.noContent()
.build();
}
@HEAD
@Path("{clubId}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response headerForOneClub(@PathParam("clubId") String clubId) {
return Response
.noContent()
.build();
}
@DELETE
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteAllClubs() {
System.out.println("delete all");
int rowsDeleted = dao.deleteAllClubs();
if (rowsDeleted > 0) { // success
// now set up the HTTP response message
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {
// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<error rowsDeleted='" + rowsDeleted + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
@GET
@Path("{clubId}")
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getOneClub(@PathParam("clubId") String clubId) {
System.out.println("getOneClub::" + clubId);
Clubs club
= dao.findById(Integer.parseInt(clubId));
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(club)
.build();
}
@GET
@Path("search/{name}") // /clubs/search/Real
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response getByName(@PathParam("name") String name) {
System.out.println("getByName: " + name);
List<Clubs> clubList
= dao.findByName(name);
GenericEntity<List<Clubs>> entity;
entity = new GenericEntity<List<Clubs>>(clubList) {
};
return Response
.status(Response.Status.OK)
.header("Access-Control-Allow-Origin", "*")
.entity(entity)
.build();
}
@DELETE
@Path("{clubId}") // Path Param i.e. /clubs/1
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response deleteOneClub(@PathParam("clubId") String clubId) {
System.out.println("deleteOneClub(): " + clubId);
// delete the row from the db where the id={clubId}
int numRowsDeleted = dao.deleteById(Integer.parseInt(clubId));
if (numRowsDeleted == 1) { // success
return Response
.noContent()
.status(Response.Status.NO_CONTENT)
.header("Access-Control-Allow-Origin", "*")
.build();
} else {// error
return Response
.status(Response.Status.NOT_FOUND)
.entity("<idNotInDB id='" + clubId + "' />")
.header("Access-Control-Allow-Origin", "*")
.build();
}
}
}