Android终端的服务器验证

服务器端

一.在数据库中新建表

二.为项目添加Add Hibernate Capabilities生成hibernate.cfg.xml和HibernateSessionFactory.java

1.hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

	<session-factory>
		<property name="dialect">
			org.hibernate.dialect.MySQLDialect
		</property>
		<property name="connection.url">
			jdbc:mysql://localhost:3306/test
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<property name="myeclipse.connection.profile">MySql</property>
		<mapping resource="com/fiberhome/hibernate/TbUser.hbm.xml" />

	</session-factory>

</hibernate-configuration>


2.HibernateSessionFactory.java

package com.fiberhome.domain;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateSessionFactory {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
	private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();    
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

	static {
    	try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
    }
    private HibernateSessionFactory() {
    }
	
	/**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

		if (session == null || !session.isOpen()) {
			if (sessionFactory == null) {
				rebuildSessionFactory();
			}
			session = (sessionFactory != null) ? sessionFactory.openSession()
					: null;
			threadLocal.set(session);
		}

        return session;
    }

	/**
     *  Rebuild hibernate session factory
     *
     */
	public static void rebuildSessionFactory() {
		try {
			configuration.configure(configFile);
			sessionFactory = configuration.buildSessionFactory();
		} catch (Exception e) {
			System.err
					.println("%%%% Error Creating SessionFactory %%%%");
			e.printStackTrace();
		}
	}

	/**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

	/**
     *  return session factory
     *
     */
	public static org.hibernate.SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
     *  return session factory
     *
     *	session factory will be rebuilded in the next call
     */
	public static void setConfigFile(String configFile) {
		HibernateSessionFactory.configFile = configFile;
		sessionFactory = null;
	}

	/**
     *  return hibernate configuration
     *
     */
	public static Configuration getConfiguration() {
		return configuration;
	}

}

三.使用Myeclipse完成Hibernate的逆向工程

http://jingyan.baidu.com/article/948f59242b9d18d80ef5f956.html

1.AbstractTbUser.java

package com.fiberhome.hibernate;

/**
 * AbstractTbUser entity provides the base persistence definition of the TbUser
 * entity. @author MyEclipse Persistence Tools
 */

public abstract class AbstractTbUser implements java.io.Serializable {

	// Fields

	private Integer id;
	private String userName;
	private String userPwd;

	// Constructors

	/** default constructor */
	public AbstractTbUser() {
	}

	/** full constructor */
	public AbstractTbUser(String userName, String userPwd) {
		this.userName = userName;
		this.userPwd = userPwd;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

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

	public String getUserName() {
		return this.userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPwd() {
		return this.userPwd;
	}

	public void setUserPwd(String userPwd) {
		this.userPwd = userPwd;
	}

}

2.TbUser.hbm.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.fiberhome.hibernate.TbUser" table="tb_user" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="userName" type="java.lang.String">
            <column name="user_name" length="20" not-null="true" />
        </property>
        <property name="userPwd" type="java.lang.String">
            <column name="user_pwd" length="30" not-null="true" />
        </property>
    </class>
</hibernate-mapping>
3.TbUser.java
package com.fiberhome.hibernate;

/**
 * TbUser entity. @author MyEclipse Persistence Tools
 */
public class TbUser extends AbstractTbUser implements java.io.Serializable {

	// Constructors

	/** default constructor */
	public TbUser() {
	}

	/** full constructor */
	public TbUser(String userName, String userPwd) {
		super(userName, userPwd);
	}

}
4.IBaseHibernateDAO.java
package com.fiberhome.hibernate;

import org.hibernate.Session;


/**
 * Data access interface for domain model
 * @author MyEclipse Persistence Tools
 */
public interface IBaseHibernateDAO {
	public Session getSession();
}

5.BaseHibernateDAO.java

package com.fiberhome.hibernate;

import com.fiberhome.domain.HibernateSessionFactory;

import org.hibernate.Session;


/**
 * Data access object (DAO) for domain model
 * @author MyEclipse Persistence Tools
 */
public class BaseHibernateDAO implements IBaseHibernateDAO {
	
	public Session getSession() {
		return HibernateSessionFactory.getSession();
	}
	
}


6.TbUserDAO.java
package com.fiberhome.hibernate;

import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A data access object (DAO) providing persistence and search support for
 * TbUser entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see com.fiberhome.hibernate.TbUser
 * @author MyEclipse Persistence Tools
 */

public class TbUserDAO extends BaseHibernateDAO {
	private static final Logger log = LoggerFactory.getLogger(TbUserDAO.class);
	// property constants
	public static final String USER_NAME = "userName";
	public static final String USER_PWD = "userPwd";

	public void save(TbUser transientInstance) {
		log.debug("saving TbUser instance");
		try {
			getSession().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void delete(TbUser persistentInstance) {
		log.debug("deleting TbUser instance");
		try {
			getSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public TbUser findById(java.lang.Integer id) {
		log.debug("getting TbUser instance with id: " + id);
		try {
			TbUser instance = (TbUser) getSession().get(
					"com.fiberhome.hibernate.TbUser", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(TbUser instance) {
		log.debug("finding TbUser instance by example");
		try {
			List results = getSession()
					.createCriteria("com.fiberhome.hibernate.TbUser")
					.add(Example.create(instance)).list();
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding TbUser instance with property: " + propertyName
				+ ", value: " + value);
		try {
			String queryString = "from TbUser as model where model."
					+ propertyName + "= ?";
			Query queryObject = getSession().createQuery(queryString);
			queryObject.setParameter(0, value);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List findByUserName(Object userName) {
		return findByProperty(USER_NAME, userName);
	}

	public List findByUserPwd(Object userPwd) {
		return findByProperty(USER_PWD, userPwd);
	}

	public List findAll() {
		log.debug("finding all TbUser instances");
		try {
			String queryString = "from TbUser";
			Query queryObject = getSession().createQuery(queryString);
			return queryObject.list();
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public TbUser merge(TbUser detachedInstance) {
		log.debug("merging TbUser instance");
		try {
			TbUser result = (TbUser) getSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(TbUser instance) {
		log.debug("attaching dirty TbUser instance");
		try {
			getSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(TbUser instance) {
		log.debug("attaching clean TbUser instance");
		try {
			getSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}
}
四.定义Service

1.UserServiceInter.java

package com.fiberhome.service;

import com.fiberhome.hibernate.TbUser;

public interface UserServiceInter {
	public TbUser checkUser(TbUser userInfo);
}


2.IUserServiceInter.java

package com.fiberhome.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.fiberhome.domain.HibernateSessionFactory;
import com.fiberhome.hibernate.TbUser;
import com.fiberhome.hibernate.TbUserDAO;
public class IUserServiceInter implements UserServiceInter {
	
	public TbUser checkUser(TbUser userInfo) {
		
		TbUserDAO tbUserDAO=new TbUserDAO();
		List<TbUser> tbUsers=tbUserDAO.findByUserName(userInfo.getUserName());
		if(tbUsers.size()==0){
			return null;
		}else{
			return tbUsers.get(0);
		}
		
	}
}

五. 定义Servlet

package com.fiberhome.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.fiberhome.hibernate.TbUser;
import com.fiberhome.service.IUserServiceInter;
import com.fiberhome.service.UserServiceInter;

public class Login extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		PrintWriter printWriter=resp.getWriter();
		String userName=req.getParameter("username");
		String userPwd=req.getParameter("userpwd");
		
		TbUser user=new TbUser();
		user.setId(1);
		user.setUserName(userName);
		user.setUserPwd(userPwd);
		
		UserServiceInter userServiceInter=new IUserServiceInter();
		TbUser info=userServiceInter.checkUser(user);
		
		
		if (info!=null) {
			JSONObject jsonObject=new JSONObject();
			jsonObject.accumulate("id", info.getId()+"");
			jsonObject.accumulate("username", info.getUserName());
			jsonObject.accumulate("userpwd", info.getUserPwd());
			printWriter.write(jsonObject.toString());
		}else {
			printWriter.write("null");
		}
	
		printWriter.flush();
		printWriter.close();
	}
	

}
在Web.xml中定义

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
		<servlet-name>Login</servlet-name>
		<servlet-class>com.fiberhome.servlet.Login</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>Login</servlet-name>
		<url-pattern>/Login.do</url-pattern>
	</servlet-mapping>
</web-app>

6.在网页中请求

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!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>用户登陆</title>
</head>
<body>
	<form action="Login.do" method="post">
		用户名: <input type="text" name="username"> <br> 密码:  
		<input type="password" name="userpwd"> <br>
		        <input type="submit"
			value="提交"> <input type="reset" value="重置">
	</form>
</body>
</html>

二Android端

1.布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".LoginActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editTextUserName"
        android:layout_gravity="center_horizontal"
        android:hint="用户名" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/editTextPwd"
        android:layout_gravity="center_horizontal"
        android:hint="密码" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="登录"
        android:id="@+id/buttonLogin"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

2.代码逻辑

package fiberhomecom.admin.application;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivity";
    private android.widget.EditText editTextUserName;
    private android.widget.EditText editTextPwd;
    private Button buttonLogin;

    RequestQueue mVolley;
    Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext=this;
        init(mContext);

    }

    private void init(Context mContext) {
        this.buttonLogin = (Button) findViewById(R.id.buttonLogin);
        this.editTextPwd = (EditText) findViewById(R.id.editTextPwd);
        this.editTextUserName = (EditText) findViewById(R.id.editTextUserName);
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userName=editTextUserName.getText().toString();
                String pwd=editTextPwd.getText().toString();
                login(userName,pwd);
            }
        });
        mVolley=Volley.newRequestQueue(mContext);
    }

    private void login(final String userName,final String userPwd) {
        String url="http://10.0.0.100:8080/LoginDemo/Login.do?username="+userName+"&userpwd="+userPwd;
        JsonRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.i(TAG,jsonObject.toString());
                try {
                    String name=jsonObject.getString("username");
                    String pwd=jsonObject.getString("userpwd");
                    if (userName.equals(name)&&userPwd.equals(pwd)){
                        Toast.makeText(LoginActivity.this,"登陆成功",Toast.LENGTH_SHORT).show();
                        Intent intent=new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(LoginActivity.this,"用户名或密码错误,请重新输入",Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(LoginActivity.this,"用户名或密码错误,请重新输入",Toast.LENGTH_SHORT).show();
            }
        });
        mVolley.add(request);
    }
}

三主要错误总结

1.jdk版本的问题默认的是1.8,后改为1.6

2.myeclipse中构建路径的jar包不会自动复制到外置的Tomcat的lib中

解决办法:Deploment Assembly中加入需要拷到Tomcat的lib中的库







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值