Webservice use Axis-2 with MySQL


Hôm nay mình viết một ứng dụng login thao tác giữa Webservice và MySQL trong JSP.

Chúng ta tạo một CSDL trong mySQL với table có 2 column là userId, password

d1

OK h chúng ta đả có csdl

Chúng ta viết tạo project WS_Serive và tạo ra 1 class LoginService


package com.wordpress.thaihoanghai;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class LogInService {
 Connection connect = null;
 Statement stmt = null;
 ResultSet rs = null;

/**
 * Check Driver connect to MySQL
 */
 protected void hasDriver() throws Exception{
 try {
 Class.forName("com.mysql.jdbc.Driver");
 } catch (ClassNotFoundException ex) {
 throw new Exception ("Invalid Driver!!Please check this drver....");
 }
 }

/**
 * Function used to get the connection to the Database
 * Step 1 - I check my connection or not!!
 * Step 2 - If not, it will be null and initialization.
 * Step 3 - Then it return
 * @return Connection
 */
 protected Connection openConnect() throws Exception{
 if(connect == null){
 hasDriver();
 String url = "jdbc:mysql://localhost/LogonWS";
 try {
 this.connect = DriverManager.getConnection(url,"root","");
 } catch (SQLException e) {
 throw new Exception(e.getMessage() + "Connect failed to database .... ");
 }
 }
 return connect;
 }
 /**
 * Make a Statement to execute the SQL statement
 * @return Statement
 */
 protected Statement getStatement() throws SQLException, Exception{
 if(stmt == null){
 stmt = openConnect().createStatement();
 }
 return stmt;
 }
 /**
 * Used to execute the Select statement
 * @param strSQL Query VD: Select * from Employee
 * @return ResultSet
 */
 public ResultSet executeQuery(String strSQL) throws Exception{
 try {
 rs = getStatement().executeQuery(strSQL);
 } catch (Exception e) {
 throw new Exception(e.getMessage() +" Error at : " + strSQL);
 }
 return rs;
 }
 /**
 * Used to execute the Insert, Update, Delete statement
 * @param strSQL Query VD: Insert into TableName values ('??','??')
 * @return The number of lines affected by the command
 */
 public int executeUpdate(String strSQL) throws Exception{
 int result = 0;
 try {
 result = getStatement().executeUpdate(strSQL);
 } catch (Exception ex) {
 throw new Exception(ex.getMessage() + " Error at: " + strSQL);
 }finally{
 this.closeConnet();
 }
 return result;
 }
 /**
 * A method to close the connection.
 * @throws SQLException
 */
 public void closeConnet() throws SQLException{
 if(rs != null && !rs.isClosed())
 rs.close();
 if(stmt != null)
 stmt.close();
 if(connect != null)
 connect.close();
 }

public int Logon(String userName, String pass){
 int result = -9999;
 try {
 ResultSet rs = executeQuery("select * from Users where UserID='" + userName + "'");
 //String id = rs.getString("UserID");
 //
 if(!rs.next()){
 result = -1;// userid invalid
 }else{
 String password = rs.getString("Password");
 if(!password.equalsIgnoreCase(pass)){
 result = 0; // Password fail
 }
 else{
 result = 1; // login success
 }
 }

 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }

}

Tiếp đến chúng ta chuột phải vào Class Service vừa tạo , New -> Orther ->Webservice như hình sau

d1 d1

Sau đó chúng ta run index.jsp trong thưc mục asix2 được kết quả như sau

d1

Chúng ta thử test lại service wsdl của chúng ta

d1

 

 

Ok zậy là chúng ta đả có 1 webservice kết nối CSDL rồi. Bước tiếp theo chúng ta sẻ tạo JSP Webservice Client để sữ dụng webservice này

Chúng ta tạo ra 1 project new Web WS_Client

Sau đó chúng ta vào right click vào New -> Orther -> Webservice Client như hình sau và nhấn finish

d1

 

 

Refresh lại project và ta thấy xuất hiện 1 số file sau đây

d1

 

ok h chúng ta thử test nào tạo ra 3 trang index.jsp, success.jsp va fail.jsp,  và 1 servlet cho việc xữ lí .

index.jsp như sau :


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log In</title>
</head>
<body>
 <form action=LogInServlet€>
 <table align="center">
 <tr>
 <td align="right">User Name:</td>
 <td><input type="text" name="txtUserName" value=""/></td>
 </tr>
 <tr>
 <td align="right">Password:</td>
 <td><input type="password" name="txtPassword" value=""/></td>
 </tr>
 <tr>
 <td><input type="submit" title="Logon" /></td>
 <td><input type="reset" title="Reset" /></td>
 </tr>
 </table>
 </form>
</body>
</html>

 

trang success.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log in successful</title>
</head>
<body>
<h1>You are log in success</h1>
 <ul>
 <li> User name : <%=request.getAttribute("username") %>
 <li> Passwrod_ : <%=request.getAttribute("password") %>
 </ul>
</body>
</html>

 

trang fail.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log in fail</title>
</head>
<body>
<h1>Login Fail</h1>

</body>
</html>

 

Servlet của chúng ta như sau mình thao tác trong doGet nha


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 String userName = request.getParameter("txtUserName");
 String pass = request.getParameter("txtPassword");
 request.setAttribute("username", userName);
 request.setAttribute("password", pass);

 // process with webservice
 LogInServiceStub stub = new LogInServiceStub();
 LogInServiceStub.Logon lg = new LogInServiceStub.Logon();

 lg.setUserName(userName);
 lg.setPass(pass);

 LogInServiceStub.LogonResponse res = stub.logon(lg);

 int result = res.get_return();
 String address = "";

if(result == 1){
 address = "success.jsp";
 }else{
 address = "fail.jsp";
 }


 RequestDispatcher dispatcher = request.getRequestDispatcher(address);
 dispatcher.forward(request, response);
 }

 

Ok như vậy là thành công. Hy vọng bài viết giúp ích các bạn.

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: