• Thế Giới Giải Mã

    Bí ẩn nhân loại Leonardo Da Vinci

  • Thế Giới Giải Mã

    Anh hùng thầm lặng Nikola Tesla

  • Thế Giới Giải Mã

    Thần đèn Thomas Edison

  • Thế Giới Giải Mã

    Người thôi miên Adolf Hitler

Showing posts with label spring. Show all posts
Showing posts with label spring. Show all posts

21 July 2016

Web Service Java Spring Delete to Database - Ajax json - jquery P3


P1: Select
P2: Insert
Tiếp tục >> phần này ta triển khai thêm chức năng Delete
Class DemoService
Java 2016
//delete User RequestBody
@RequestMapping(value="/deleteUser",method = RequestMethod.POST)
 public void  deleteStudentRB(@RequestBody String userId) {
   UserDAO userDAO = new UserDAO();
   userDAO.delStudent(userId);
 }
}
Class UserDAO
Java 2016
public void delStudent(String id){
 try {
  stmt  = conn.prepareStatement("DELETE FROM student.student WHERE id=?");
  stmt.setString(1, id);
  
  stmt.executeUpdate();
 } catch (SQLException e) {
  e.printStackTrace();
 }
}



index.html
Java 2016
<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Demo Hello WebService</title>  
</head>
<body>  
        <script>
  window.jQuery || document.write('<script src="jquery-1.12.0.min.js"><\/script>')
  </script>
        <script>
  (function($){
    $(document).ready(function() {
     selectUser();
     insertUser();
     deleteUser();
    });
    function selectUser(){
     $.get("http://localhost:8080/viewAllUser", function(data){
      $.each(data, function(key, value){
       $(".Student").append("<p> Name: " + value.name + " </br> Age: " + value.age + "</p>");
      });
     });
    }
    
    function insertUser(){
    $("#save").click(function(){
     var name = $("#name").val();
     var age = $("#age").val();

     var data = JSON.stringify({
      "name": name,
      "age": age,
     });

     $.ajax({
      type: "POST",
      url: "http://localhost:8080/addUser",
      data: data,
      dataType: 'appLication/json',
      contentType: 'appLication/json',
      complete: function(){
       $("#name").val("");
       $("#age").val("");
       location.reload();
      }
     });
    });
    }

    function deleteUser(){
    $("#delSubmit").click(function(){
     var id = $("#id").val();

     $.ajax({
      type: "POST",
      url: "http://localhost:8080/deleteUser",
      data: id,
      dataType: "text",
      contentType: 'appLication/json',
      complete: function(){
       
      }
     
     });
    });
    }
    
   })(jQuery);
  </script>
        <div class="Student"> 
            <div class="name"></div>
            <div class="age"></div>
        </div> 
   <div id="form-user">Insert: 
                <input id="name" type="text" name="name" placeholder="Name">
                <input id="age" type="number" name="age" placeholder="Age">
                <button id="save" type="submit">Insert</button>
        </div>
  <div id="deleteUser">Delete:
                <input id="id" type="text" name="id" placeholder="Id">
                <button id="delSubmit" type="submit">Delete</button>
        </div>
</body>
</html>

Web Service Java Spring Insert to Database - Ajax json - jquery P2

P1: Select
Tiếp tục >> phần này ta triển khai thêm chức năng Insert


Class DemoService
Java 2016
//add user
@RequestMapping(value="/addUser",method = RequestMethod.POST)
@Produces(MediaType.APPLICATION_JSON)
public String addUser(@RequestBody User user){
 UserDAO userDAO = new UserDAO();
 userDAO.addStudent(user);
 return "Hello " + user.getName() + "\n" + "Age " + user.getAge();
}

Class UserDAO
Java 2016
public void addStudent(User user){
 try {
  stmt = conn.prepareStatement("INSERT INTO student.student (name, age) VALUES (?, ?)");
  stmt.setString(1, user.getName());
  stmt.setString(2, user.getAge());
  
  stmt.executeUpdate();
 } catch (SQLException e) {
  e.printStackTrace();
 }
}


index.html
Java 2016
<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Demo Hello WebService</title>  
</head>
<body>  
        <script>
  window.jQuery || document.write('<script src="jquery-1.12.0.min.js"><\/script>')
  </script>
        <script>
  (function($){
    $(document).ready(function() {
     selectUser();
     insertUser();
    });
    function selectUser(){
     $.get("http://localhost:8080/viewAllUser", function(data){
      $.each(data, function(key, value){
       $(".Student").append("<p> Name: " + value.name + " </br> Age: " + value.age + "</p>");
      });
     });
    }
    
    function insertUser(){
    $("#save").click(function(){
     var name = $("#name").val();
     var age = $("#age").val();

     var data = JSON.stringify({
      "name": name,
      "age": age,
     });

     $.ajax({
      type: "POST",
      url: "http://localhost:8080/addUser",
      data: data,
      dataType: 'appLication/json',
      contentType: 'appLication/json',
      complete: function(){
       $("#name").val("");
       $("#age").val("");
       location.reload();
      }
     });
    });
    }

    
   })(jQuery);
  </script>
        <div class="Student"> 
            <div class="name"></div>
            <div class="age"></div>
        </div> 
   <div id="form-user">Insert: 
                <input id="name" type="text" name="name" placeholder="Name">
                <input id="age" type="number" name="age" placeholder="Age">
                <button id="save" type="submit">Insert</button>
        </div>
</body>
</html>
Đóng chương trình nút x và ô vuông đỏ ở cửa số console và chạy lại!
Chạy file index.html
Thành công chức năng insert !
P3 Delete

20 July 2016

Web Service Java Spring Select to Database - Ajax json - jquery P1

Download import Maven project demo

Vui lòng kiểu tra phiên bản Java đang chạy trên máy bạn!


Download phần mềm Spring
Cài đặt và chạy tạo project mới 
New Project > Other > Exiting Maven Project
OK
class User
Java 2016
package com.example.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {
 @XmlElement(name = "name")
 private String name;

 @XmlElement(name = "age")
 private String age;

 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }
 public User() {
  super();
  // TODO Auto-generated constructor stub
 }
 public User(String name, String age) {
  this.name = name;
  this.age = age;
 }
}

Class DBUtils
Java 2016
package com.example.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtils {
 private static Connection connection = null;
 static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
 static final String DB_URL = "jdbc:mysql://localhost:3306/student";
 static final String DB_USER = "root"; //user
 static final String DB_PASS = "1234567"; //pass

 public static Connection getConnection() {
  if (connection != null) {
   return connection;
  } else {
   try {
    Class.forName(JDBC_DRIVER);
    connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
   } catch (ClassNotFoundException e) {
    e.printStackTrace();
   } catch (SQLException e) {
    e.printStackTrace();
   }
   return connection;
  }
 }
}
Class DemoService
Java 2016
package com.example.service;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.User;

@CrossOrigin
@RestController
public class DemoService {

 private Connection conn;

 public DemoService() {
  conn = DBUtils.getConnection();
 }
 // view json
 @RequestMapping(value = "/viewAllUser", method = RequestMethod.GET)
 public List<User> viewAllUser() {
  UserDAO userDAO = new UserDAO();
  List<User> list = new ArrayList<User>(userDAO.getAllUser());
  return list;
 }
}
 Tạo database mysql với workbench
Create Database
Java 2016
CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `age` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;



Class UserDAO
Java 2016
package com.example.service;

import java.lang.Thread.State;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.mysql.jdbc.Connection;

import com.example.model.*;

public class UserDAO {
 private Connection conn;
 private PreparedStatement stmt;
 private ResultSet rs;

 public UserDAO() {
  conn = (Connection) DBUtils.getConnection();
 }

 public List<User> getAllUser() {
  List<User> list = new ArrayList<User>();
  try {
   stmt = conn.prepareStatement("SELECT * FROM student.student");
   rs = stmt.executeQuery();
   while (rs.next()) {
    User user = new User(rs.getString("name"), rs.getString("age"));
    list.add(user);
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
  return list;
 }
}
Tạo 1 file index.html
Tất nhiên là html chạy kết hợp với : jquery-1.12.0.min.jsAjax json
index.html
Java 2016
<!doctype html>
<html class="no-js" lang="">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>Demo Hello WebService</title>  
</head>
<body>  
        <script>
  window.jQuery || document.write('<script src="jquery-1.12.0.min.js"><\/script>')
  </script>
        <script>
  (function($){
    $(document).ready(function() {
     getUser();
    });
    function getUser(){
     $.get("http://localhost:8080/viewAllUser", function(data){
      $.each(data, function(key, value){
       $(".Student").append("<p> Name: " + value.name + " </br> Age: " + value.age + "</p>");
      });
     });
    }
   })(jQuery);
  </script>
        <div class="Student"> 
            <div class="name"></div>
            <div class="age"></div>
        </div> 
</body>
</html>
Chạy Spring Boot App để khởi động kết nối database và chạy service
Chạy thành công!
Chạy file index.html

Thành công select data từ mysql 'Successfully!'
P2: Insert

18 May 2016

Servlet spec - web.xml - Fix lỗi Web-app

Servlet spec - web.xml

Status

Released on (mm/dd/yyyy) : 02/06/2012

Description

JEE web specification provides a way to configure, declaratively in the web deployment descriptor ("web.xml" file), the web app. behavior when an exception occur in a web component.
Behavior can be configured to react on elements below to display a resource:
  • Java exception
  • HTTP response code

Possible configurations

Configuration below redirect user to page "/errorManagement.jsp" when an error occur.
Configuration to react on Java exception
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	
	...
	
	<!-- Define error page to react on Java exception -->
	<error-page>
		<exception-type>java.lang.Throwable</exception-type>
		<location>/errorManagement.jsp</location>
	</error-page>
	
	...	
	
</web-app>
Configuration to react on HTTP response code
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	
	...
	
	<!-- Define error page to react on HTTP response code -->
	<error-page>
		<error-code>500</error-code>
		<location>/errorManagement.jsp</location>
	</error-page>
	
	...	
	
</web-app>

Content of the error management page
<?xml version="1.0" encoding="ISO-8859-1" ?>

<%@ page language="java" 
	contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1" 
	isErrorPage="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Page to manage error</title>
</head>

<body>
	<%-- Log error on server side --%>
	<%
		//When the page attribute "isErrorPage" is set to "true" the exception object is available
		System.err.println("Error : " + exception.getMessage());
	%>

	<%-- Display generic error to client --%>
	<b>An error occur !</b>
</body>
</html>

1. Servlet 3.1 deployment descriptor

Java EE 7 XML schema, namespace is http://xmlns.jcp.org/xml/ns/javaee/
web.xml
Markup
<web-app 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"
         version="3.1">
</web-app>

2. Servlet 3.0 deployment descriptor

Java EE 6 XML schema, namespace is http://java.sun.com/xml/ns/javaee
web.xml
Markup
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	      version="3.0">
</web-app>

3. Servlet 2.5 deployment descriptor

Java EE 5 XML schema, namespace is http://java.sun.com/xml/ns/javaee
web.xml
Markup
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	      http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	      version="2.5">
</web-app>

4. Servlet 2.4 deployment descriptor

J2EE 1.4 XML schema, namespace is http://java.sun.com/xml/ns/j2ee
web.xml
Markup
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	      version="2.4">

  <display-name>Servlet 2.4 Web Application</display-name>
</web-app>

5. Servlet 2.3 deployment descriptor

J2EE 1.3 DTDs schema. This web.xml file is too old, highly recommend you to upgrade it.
web.xml
Markup
<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Servlet 2.3 Web Application</display-name>
</web-app>

 

BACK TO TOP

Xuống cuối trang