1.servletConfig对象和servletContext对象
servlet 容器使用的 servlet 配置对象,该对象在初始化期间将信息传递给 servlet
ServletConfig servletConfig = getServletConfig();
//获取servlet的名字
String servletName = servletConfig.getServletName();
System.out.println("servletName:"+servletName);
//获取servletcontext对象 (代表当前的web应用)
String username= getServletConfig().getInitParameter("username");
System.out.println("username"+username);
//获取servlet的配置 参数的实例 代表当前的web应用
ServletContext servletContext = getServletContext();
//有些数据不适合在程序中写死 这个数据是共有的 全局的
String name = servletContext.getInitParameter("name");
System.out.println("name:"+name);
//拿到当前web应用可以实现数据的共享
servletContext.setAttribute("wdj", "hahha");
//获取项目中的真实路径
String realPath = servletContext.getRealPath("aa");
下面是一个登陆的小案例:
首先配置服务器端,就是要对服务器端进行一个数据的初始化
1、在mysql中新建一个数据库
2、创建一个表,字段有id,用户名、密码
3、在表中添加用户名和密码
4、在javaee中新建一个servlet
服务器代码如下:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String name = request.getParameter("username");
String pwd = request.getParameter("password");
try {
//注册驱动
DriverManager.registerDriver(new Driver()); //另外一种方式注册驱动可以用类的字节码,通过反射获取
//获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "root");
//准备要执行的sql语句
String sql = "select * from login where username = ? and password =?";
//获取statement对象 执行sql语句
// Statement statement = connection.createStatement();
PreparedStatement statement = connection.prepareStatement(sql);
//设置? 占位的内容 1代表第一个?
statement.setString(1, name);
statement.setString(2, pwd);
//执行sql语句
ResultSet resultSet = statement.executeQuery();
//如果根据我们写sql语句查询出结果 就证明登录成功
//System.out.println("-------------");
if (resultSet.next()) {
response.getOutputStream().write("sucess".getBytes());
}else {
//System.out.println("登录失败");
response.getOutputStream().write("fail".getBytes());
}
resultSet.close();
statement.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
客服端代码如下:
这里实现了get请求和post请求
package com.wdj.login;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText et_name;
private EditText et_pwd;
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_name = (EditText) findViewById(R.id.et_name);
et_pwd = (EditText) findViewById(R.id.et_pwd);
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
String content = (String) msg.obj;
Toast.makeText(getApplication(), content, 0).show();
}
};
}
//get请求
public void click_get(View v){
String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)){
Toast.makeText(getApplication(), "用户名或密码不能为空", 0).show();
return;
}
final String path = "http://192.168.80.212:8080/login/LoginServlet?username="+name+"&password="+pwd+"";
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(5000);
int code = con.getResponseCode();
if(code == 200){
InputStream inputStream = con.getInputStream();
String content = UtilsToos.getInputStream(inputStream);
showToast(content);
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
//实现post请求
public void click_post(View v){
String name = et_name.getText().toString().trim();
String pwd = et_pwd.getText().toString().trim();
if(TextUtils.isEmpty(name) || TextUtils.isEmpty(pwd)){
Toast.makeText(getApplication(), "用户名或密码不能为空", 0).show();
return;
}
final String path = "http://192.168.80.212:8080/login/LoginServlet";
//创建DefaultHttpClient对象
final HttpClient client = new DefaultHttpClient();
//将请求路径封装成一个HttpPost对象
final HttpPost post = new HttpPost(path);
//将请求要提交的参数封装成一个BasicNameValuePair对象
BasicNameValuePair nameValuePair = new BasicNameValuePair("username", name);
BasicNameValuePair pwdValuePair = new BasicNameValuePair("password", pwd);
//创建一个集合,用于存放封装后的提交的数据
final ArrayList list = new ArrayList();
//将封装后的数据添加到集合中
list.add(nameValuePair);
list.add(pwdValuePair);
new Thread(){
public void run() {
try {
//创建一个UrlEncodedFormEntity实体,指定要传输数据的编码格式
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
//设置post的请求实体
post.setEntity(entity);
//调用client的方法获取响应请求
HttpResponse response = client.execute(post);
if(response.getStatusLine().getStatusCode() == 200){
InputStream inputStream = response.getEntity().getContent();
String content = UtilsToos.getInputStream(inputStream);
//showToast(content); //用runOnuiThread实现ui的更新
Message msg = Message.obtain();
msg.obj = content;
handler.sendMessage(msg); //用handler发送消息机制更新ui
}
} catch (Exception e) {
e.printStackTrace();
}
};
}.start();
}
public void showToast(final String content){
runOnUiThread(new Runnable(){
@Override
public void run() {
Toast.makeText(getApplication(), content, 0).show();
}
});
}
}
用到的工具类:
package com.heima.login;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class UtilsToos {
public static String getInputStream(InputStream in) throws Exception {
ByteArrayOutputStream boas = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) != -1){
boas.write(buffer, 0, len);
}
String str = boas.toString();
return str;
}
}