WebService-写简单接口

来源:互联网 发布:php 500错误如何排查 编辑:程序博客网 时间:2024/06/08 19:13

1.写个接口,供外调用

package com.my.service;import java.util.List;import javax.jws.WebService;import com.my.entity.User;@WebService(targetNamespace = "com.my.service")public interface Login {    public List<User> getUser(String username, String password);}

2.写实现类

package com.my.service;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.ArrayList;import java.util.List;import javax.jws.WebService;import com.my.entity.User;@WebService(targetNamespace = "com.my.service")public class LoginImpl implements Login {    @Override    public List<User> getUser() {        List<User> list = new ArrayList<>();        Connection connection = null;        try {            connection = getConnection();            Statement createStatement = connection.createStatement();            ResultSet executeQuery = createStatement.executeQuery("select * from user");            while (executeQuery.next()) {                User user = new User(executeQuery.getInt("id"), executeQuery.getString("name"), executeQuery.getString("password"), true);                list.add(user);            }        } catch (ClassNotFoundException | SQLException e) {            e.printStackTrace();        }        return list;    }    public static Connection getConnection() throws ClassNotFoundException, SQLException {        // 加载MySQL的JDBC的驱动        Class.forName("com.mysql.jdbc.Driver");        String url = "jdbc:mysql://localhost:3306/right";        String username = "root";        String password = "111111";        // 创建与MySQL数据库的连接类的实例        Connection conn = DriverManager.getConnection(url, username, password);        System.out.println("Database connection established");        return conn;    }}

3.发布

package com.my.test;import javax.xml.ws.Endpoint;import com.my.service.Login;import com.my.service.LoginImpl;public class TestPubServ {    public static void main(String[] args) {        String add = "http://localhost:8080/pro";        Login lo = new LoginImpl();        Endpoint.publish(add, lo);        System.out.println("发布成功!");    }}

4.可以直接访问
http://localhost:8080/pro
(通过,杀死进程javaw.exe可以重新发布)