By GokiSoft.com| 11:53 15/08/2022|
Spring MVC

[Souce Code] Phát triển dự án bằng Spring MVC - Rest API - Server Side


#persistence.xml


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
  <persistence-unit name="APISpringMVCPU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>com.gokisoft.entities.News</class>
    <class>com.gokisoft.entities.Category</class>
    <class>com.gokisoft.entities.Tours</class>
    <class>com.gokisoft.entities.Users</class>
    <class>com.gokisoft.entities.UserTokens</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/c2010g"/>
      <property name="javax.persistence.jdbc.user" value="root"/>
      <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
      <property name="javax.persistence.jdbc.password" value=""/>
    </properties>
  </persistence-unit>
</persistence>


#TestController.java


/*
 * 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 com.gokisoft.controller;

import com.gokisoft.model.Student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author Administrator
 */
@RestController
@RequestMapping(value = "/api/test")
public class TestController {
    @RequestMapping(value = "/text", method = RequestMethod.GET)
    public String text() {
        return "Sinh vien Aptech 54 Le Thanh Nghi";
    }
    
    @RequestMapping(value = "/students", method = RequestMethod.GET, produces = "application/json")
    public String getStudentList() {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("A", "a@gmail.com"));
        studentList.add(new Student("B", "b@gmail.com"));
        studentList.add(new Student("C", "c@gmail.com"));
        
        Gson gson = new Gson();
        TypeToken<List<Student>> type = new TypeToken<List<Student>>() {};
        String content = gson.toJson(studentList, type.getType());
        
        return content;
    }
    
//    @RequestMapping(value = "/students2", method = RequestMethod.GET, produces = "application/json")
//    public ResponseEntity<List<Student>> getStudentList2() {
//        List<Student> studentList = new ArrayList<>();
//        studentList.add(new Student("A", "a@gmail.com"));
//        studentList.add(new Student("B", "b@gmail.com"));
//        studentList.add(new Student("C", "c@gmail.com"));
//        
//        HttpHeaders headers = new HttpHeaders();
//        headers.add("Content-Type", "application/json");
//        
//        ResponseEntity<List<Student>> res = new ResponseEntity<>(studentList, headers, HttpStatus.OK);
//        return res;
//    }
}


#TourController.java


/*
 * 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 com.gokisoft.controller;

import com.gokisoft.entities.Tours;
import com.gokisoft.model.Message;
import com.gokisoft.model.Student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author Administrator
 */
@RestController
@RequestMapping(value = "/api/tour")
public class TourController {
    EntityManagerFactory factory;
    EntityManager manager;
    
    public TourController() {
        factory = Persistence.createEntityManagerFactory("APISpringMVCPU");
        manager = factory.createEntityManager();
    }
    
    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
    public String list() {
        Query query = manager.createNamedQuery("Tours.findAll", Tours.class);
        List<Tours> tourList = query.getResultList();
        
        Gson gson = new Gson();
        TypeToken<List<Tours>> type = new TypeToken<List<Tours>>() {};
        String content = gson.toJson(tourList, type.getType());
        
        return content;
    }
    
    @RequestMapping(value = "/find", method = RequestMethod.GET, produces = "application/json")
    public String find(@RequestParam HashMap<String, String> formData) {
        int id = Integer.parseInt(formData.get("id"));
        Tours t = manager.find(Tours.class, id);
        
        Gson gson = new Gson();
        TypeToken<Tours> type = new TypeToken<Tours>() {};
        String content = gson.toJson(t, type.getType());
        
        return content;
    }
    
    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
    public String add(@RequestParam HashMap<String, String> formData) {
        String title = formData.get("title");
        String thumbnail = formData.get("thumbnail");
        String address = formData.get("address");
        String tourDate = formData.get("tourDate");
        tourDate = tourDate.replace("T", " ");
        float price = Float.parseFloat(formData.get("price"));
        String content = formData.get("content");
        
        Tours tour = new Tours();
        tour.setTitle(title);
        tour.setThumbnail(thumbnail);
        tour.setAddress(address);
        
        Date mydate; 
        try {
            mydate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(tourDate);
            tour.setTourDate(mydate);
        } catch (ParseException ex) {
            Logger.getLogger(TourController.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        tour.setPrice(price);
        tour.setContent(content);
        
        manager.getTransaction().begin();
        manager.persist(tour);
        manager.getTransaction().commit();
        
        Message msg = new Message(1, "Thanh cong");
        
        Gson gson = new Gson();
        TypeToken<Message> type = new TypeToken<Message>() {};
        String context = gson.toJson(msg, type.getType());
        
        return context;
    }
    
    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = "application/json")
    public String edit(@RequestParam HashMap<String, String> formData) {
        int id = Integer.parseInt(formData.get("id"));
        String title = formData.get("title");
        String thumbnail = formData.get("thumbnail");
        String address = formData.get("address");
        String tourDate = formData.get("tourDate");
        tourDate = tourDate.replace("T", " ");
        float price = Float.parseFloat(formData.get("price"));
        String content = formData.get("content");
        
        Tours tour = manager.find(Tours.class, id);
        
        tour.setTitle(title);
        tour.setThumbnail(thumbnail);
        tour.setAddress(address);
        
        Date mydate; 
        try {
            mydate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(tourDate);
            tour.setTourDate(mydate);
        } catch (ParseException ex) {
            Logger.getLogger(TourController.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        tour.setPrice(price);
        tour.setContent(content);
        
        manager.getTransaction().begin();
        manager.persist(tour);
        manager.getTransaction().commit();
        
        Message msg = new Message(1, "Thanh cong");
        
        Gson gson = new Gson();
        TypeToken<Message> type = new TypeToken<Message>() {};
        content = gson.toJson(msg, type.getType());
        
        return content;
    }
    
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = "application/json")
    public String delete(@RequestParam HashMap<String, String> formData) {
        int id = Integer.parseInt(formData.get("id"));
        
        Tours tour = manager.find(Tours.class, id);
        
        manager.getTransaction().begin();
        manager.remove(tour);
        manager.getTransaction().commit();
        
        Message msg = new Message(1, "Thanh cong");
        
        Gson gson = new Gson();
        TypeToken<Message> type = new TypeToken<Message>() {};
        String content = gson.toJson(msg, type.getType());
        
        return content;
    }
}


#Category.java


/*
 * 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 com.gokisoft.entities;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

/**
 *
 * @author Administrator
 */
@Entity
@Table(name = "category")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c")
    , @NamedQuery(name = "Category.findById", query = "SELECT c FROM Category c WHERE c.id = :id")
    , @NamedQuery(name = "Category.findByName", query = "SELECT c FROM Category c WHERE c.name = :name")})
public class Category implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "name")
    private String name;
    @OneToMany(mappedBy = "idCategory")
    private Collection<News> newsCollection;

    public Category() {
    }

    public Category(Integer id) {
        this.id = id;
    }

    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;
    }

    @XmlTransient
    public Collection<News> getNewsCollection() {
        return newsCollection;
    }

    public void setNewsCollection(Collection<News> newsCollection) {
        this.newsCollection = newsCollection;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Category)) {
            return false;
        }
        Category other = (Category) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.gokisoft.entities.Category[ id=" + id + " ]";
    }
    
}


#News.java


/*
 * 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 com.gokisoft.entities;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Administrator
 */
@Entity
@Table(name = "news")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "News.findAll", query = "SELECT n FROM News n")
    , @NamedQuery(name = "News.findById", query = "SELECT n FROM News n WHERE n.id = :id")
    , @NamedQuery(name = "News.findByTitle", query = "SELECT n FROM News n WHERE n.title = :title")
    , @NamedQuery(name = "News.findByThumbnail", query = "SELECT n FROM News n WHERE n.thumbnail = :thumbnail")
    , @NamedQuery(name = "News.findByCreatedAt", query = "SELECT n FROM News n WHERE n.createdAt = :createdAt")
    , @NamedQuery(name = "News.findByUpdatedAt", query = "SELECT n FROM News n WHERE n.updatedAt = :updatedAt")})
public class News implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "title")
    private String title;
    @Lob
    @Column(name = "content")
    private String content;
    @Column(name = "thumbnail")
    private String thumbnail;
    @Column(name = "created_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @Column(name = "updated_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;
    @JoinColumn(name = "id_category", referencedColumnName = "id")
    @ManyToOne
    private Category idCategory;

    public News() {
    }

    public News(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Category getIdCategory() {
        return idCategory;
    }

    public void setIdCategory(Category idCategory) {
        this.idCategory = idCategory;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof News)) {
            return false;
        }
        News other = (News) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.gokisoft.entities.News[ id=" + id + " ]";
    }
    
}


#Tours.java


/*
 * 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 com.gokisoft.entities;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Administrator
 */
@Entity
@Table(name = "tours")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Tours.findAll", query = "SELECT t FROM Tours t")
    , @NamedQuery(name = "Tours.findById", query = "SELECT t FROM Tours t WHERE t.id = :id")
    , @NamedQuery(name = "Tours.findByTitle", query = "SELECT t FROM Tours t WHERE t.title = :title")
    , @NamedQuery(name = "Tours.findByThumbnail", query = "SELECT t FROM Tours t WHERE t.thumbnail = :thumbnail")
    , @NamedQuery(name = "Tours.findByAddress", query = "SELECT t FROM Tours t WHERE t.address = :address")
    , @NamedQuery(name = "Tours.findByTourDate", query = "SELECT t FROM Tours t WHERE t.tourDate = :tourDate")
    , @NamedQuery(name = "Tours.findByPrice", query = "SELECT t FROM Tours t WHERE t.price = :price")})
public class Tours implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "title")
    private String title;
    @Column(name = "thumbnail")
    private String thumbnail;
    @Column(name = "address")
    private String address;
    @Column(name = "tour_date")
    @Temporal(TemporalType.TIMESTAMP)
    private Date tourDate;
    // @Max(value=?)  @Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
    @Column(name = "price")
    private Float price;
    @Lob
    @Column(name = "content")
    private String content;

    public Tours() {
    }

    public Tours(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getThumbnail() {
        return thumbnail;
    }

    public void setThumbnail(String thumbnail) {
        this.thumbnail = thumbnail;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Date getTourDate() {
        return tourDate;
    }

    public void setTourDate(Date tourDate) {
        this.tourDate = tourDate;
    }

    public Float getPrice() {
        return price;
    }

    public void setPrice(Float price) {
        this.price = price;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Tours)) {
            return false;
        }
        Tours other = (Tours) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.gokisoft.entities.Tours[ id=" + id + " ]";
    }
    
}


#Users.java


/*
 * 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 com.gokisoft.entities;

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Administrator
 */
@Entity
@Table(name = "users")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
    , @NamedQuery(name = "Users.findById", query = "SELECT u FROM Users u WHERE u.id = :id")
    , @NamedQuery(name = "Users.findByFullname", query = "SELECT u FROM Users u WHERE u.fullname = :fullname")
    , @NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email")
    , @NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password")
    , @NamedQuery(name = "Users.findByCreatedAt", query = "SELECT u FROM Users u WHERE u.createdAt = :createdAt")
    , @NamedQuery(name = "Users.findByUpdatedAt", query = "SELECT u FROM Users u WHERE u.updatedAt = :updatedAt")
    , @NamedQuery(name = "Users.findByDeleted", query = "SELECT u FROM Users u WHERE u.deleted = :deleted")
    , @NamedQuery(name = "Users.findByActive", query = "SELECT u FROM Users u WHERE u.active = :active")})
public class Users implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Column(name = "fullname")
    private String fullname;
    @Column(name = "email")
    private String email;
    @Column(name = "password")
    private String password;
    @Column(name = "created_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
    @Column(name = "updated_at")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updatedAt;
    @Column(name = "deleted")
    private Boolean deleted;
    @Column(name = "active")
    private Boolean active;

    public Users() {
    }

    public Users(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Boolean getDeleted() {
        return deleted;
    }

    public void setDeleted(Boolean deleted) {
        this.deleted = deleted;
    }

    public Boolean getActive() {
        return active;
    }

    public void setActive(Boolean active) {
        this.active = active;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Users)) {
            return false;
        }
        Users other = (Users) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.gokisoft.entities.Users[ id=" + id + " ]";
    }
    
}


#UserTokens.java


/*
 * 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 com.gokisoft.entities;

import java.io.Serializable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Administrator
 */
@Entity
@Table(name = "user_tokens")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "UserTokens.findAll", query = "SELECT u FROM UserTokens u")
    , @NamedQuery(name = "UserTokens.findByIdUser", query = "SELECT u FROM UserTokens u WHERE u.userTokensPK.idUser = :idUser")
    , @NamedQuery(name = "UserTokens.findByToken", query = "SELECT u FROM UserTokens u WHERE u.userTokensPK.token = :token")})
public class UserTokens implements Serializable {

    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected UserTokensPK userTokensPK;

    public UserTokens() {
    }

    public UserTokens(UserTokensPK userTokensPK) {
        this.userTokensPK = userTokensPK;
    }

    public UserTokens(int idUser, String token) {
        this.userTokensPK = new UserTokensPK(idUser, token);
    }

    public UserTokensPK getUserTokensPK() {
        return userTokensPK;
    }

    public void setUserTokensPK(UserTokensPK userTokensPK) {
        this.userTokensPK = userTokensPK;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (userTokensPK != null ? userTokensPK.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserTokens)) {
            return false;
        }
        UserTokens other = (UserTokens) object;
        if ((this.userTokensPK == null && other.userTokensPK != null) || (this.userTokensPK != null && !this.userTokensPK.equals(other.userTokensPK))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.gokisoft.entities.UserTokens[ userTokensPK=" + userTokensPK + " ]";
    }
    
}


#UserTokensPK.java


/*
 * 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 com.gokisoft.entities;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 *
 * @author Administrator
 */
@Embeddable
public class UserTokensPK implements Serializable {

    @Basic(optional = false)
    @Column(name = "id_user")
    private int idUser;
    @Basic(optional = false)
    @Column(name = "token")
    private String token;

    public UserTokensPK() {
    }

    public UserTokensPK(int idUser, String token) {
        this.idUser = idUser;
        this.token = token;
    }

    public int getIdUser() {
        return idUser;
    }

    public void setIdUser(int idUser) {
        this.idUser = idUser;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) idUser;
        hash += (token != null ? token.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof UserTokensPK)) {
            return false;
        }
        UserTokensPK other = (UserTokensPK) object;
        if (this.idUser != other.idUser) {
            return false;
        }
        if ((this.token == null && other.token != null) || (this.token != null && !this.token.equals(other.token))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.gokisoft.entities.UserTokensPK[ idUser=" + idUser + ", token=" + token + " ]";
    }
    
}


#Message.java


/*
 * 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 com.gokisoft.model;

/**
 *
 * @author Administrator
 */
public class Message {
    int status;
    String message;

    public Message() {
    }

    public Message(int status, String message) {
        this.status = status;
        this.message = message;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "Message{" + "status=" + status + ", message=" + message + '}';
    }
}


#Student.java


/*
 * 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 com.gokisoft.model;

import java.io.Serializable;

/**
 *
 * @author Administrator
 */
public class Student implements Serializable{
    String fullname;
    String email;

    public Student() {
    }

    public Student(String fullname, String email) {
        this.fullname = fullname;
        this.email = email;
    }

    public String getFullname() {
        return fullname;
    }

    public void setFullname(String fullname) {
        this.fullname = fullname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Student{" + "fullname=" + fullname + ", email=" + email + '}';
    }
}


#Utility.java


/*
 * 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 com.gokisoft.utils;

/**
 *
 * @author Administrator
 */
public class Utility {
}


#applicationContext.xml


<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context">
    
    <context:component-scan base-package="com.gokisoft.controller"></context:component-scan>
    <mvc:annotation-driven/>
    <!--bean id="propertyConfigurer"
          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
          p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" /-->

    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>


#dispatcher-servlet.xml


<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.html">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp" />

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController"
          p:viewName="index" />

</beans>


#web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>


Tags:

Phản hồi từ học viên

5

(Dựa trên đánh giá ngày hôm nay)