1. 程式人生 > >8月12日---URLConnection,HTTPClient

8月12日---URLConnection,HTTPClient

伺服器與資料庫建立連線,將從瀏覽器得到的資訊與資料庫中的資訊相比較,如果有了,就顯示登陸成功,如果沒有,就顯示登入失敗:

package com.lingzhuo.test;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import
javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletTest */ @WebServlet("/ServletTest") public class ServletTest extends HttpServlet { private static final long serialVersionUID = 1
L; /** * @see HttpServlet#HttpServlet() */ public ServletTest() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { // TODO Auto-generated method stub String name = request.getParameter("name"); String password = request.getParameter("password"); // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // name= Encoding.doEncoding(name); // password = Encoding.doEncoding(password); String s = ""; System.out.println("使用者名稱: "+name+" "+"密碼: "+password); Connection con = MySQL.newInstance().getCon(); try { PreparedStatement prea = con.prepareStatement("select * from user where username = ? and password=?"); prea.setString(1, name); prea.setString(2, password); ResultSet set = prea.executeQuery(); set.last(); int num = set.getRow(); if(num==1){ s = "登陸成功"; }else{ s = "登入失敗"; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // response.getWriter().append("Served at: ").append(request.getContextPath()); response.setHeader("Content-type", "text/html;charset=UTF-8"); // response.getWriter().append("使用者名稱: "+name+"密碼: "+password); response.getWriter().append(s); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }