Tomcat底层实现

package myserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
public MyServer() {
try {
ServerSocket socket = new ServerSocket(8089);
while (true) {
Socket s = socket.accept();
new SocketThread(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new MyServer();
}
}

 

 

package myserver;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import service.AddService;
import service.FindAllService;
import service.LoginService;

public class SocketThread implements Runnable{
private Socket socket;

public SocketThread(Socket socket) {
this.socket = socket;

Thread th = new Thread(this);
th.start();
}

@Override
public void run() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();//获取文件读取流
out = socket.getOutputStream();//获取文件写入流
Response response = new Response(out);//相应数据到浏览器
Request request = new Request(in);//从网页获取数据
System.out.println("********"+request);
String url = request.getUrl();//获取URL路径
//response.sendMessage("hello");
if ("login".equals(url)) {
LoginService login = new LoginService();
try {
login.service(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}else if("findAll".equals(url)){
FindAllService all = new FindAllService();
try {
all.service(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}else if("add".equals(url)){
AddService add = new AddService();
try {
add.service(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}else{
response.sendFile(url);
}

out.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

 

 

package myserver;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class Request {
private String url;
//封装表单数据
private Map<String,String> paramMap = new HashMap<String,String>();

public Request(InputStream in) {
byte[] by = new byte[1024];
try {
in.read(by);
String str = new String(by).trim();//去掉两边空格
System.out.println(str);

if (str.startsWith("GET")){//GET开头的流数据
this.getGet(str);
}else{//POST开头的流数据
this.getPOST(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}

private void getPOST(String str) {//获取POST的URL和表单数据
String[] s = str.split("\\s+");//按空格割分字符串为字符串数组
this.url = s[1].substring(1);//表单的POST提交
getMap(s[s.length-1]);//获取表单数据
}

private void getGet(String str) {//获取GET的URL和表单数据
String[] s = str.split("\\s+");//按空格割分字符串为字符串数组
if (s[1].indexOf("?") == -1){
this.url = s[1].substring(1);//文本的GET提交
}else{
String s1 = s[1];
//表单的GET提交
this.url = s1.split("[?]")[0].substring(1);
this.getMap(s1.split("[?]")[1]);//获取表单数据
}
}
//GET /url POST|GET /url?userName=""&pwd=""&age=""&sex=""
private Map<String,String> getMap(String string) {//获取表单数据
String[] s = string.split("[&]");
for (String str : s) {
this.paramMap.put(str.split("[=]")[0], str.split("[=]")[1]);
}
return this.paramMap;
}

public String getUrl() {
return this.url;
}

public String getParameter(String key){
return this.paramMap.get(key);
}

@Override
public String toString() {
return "Request [url=" + url + ", paramMap=" + paramMap + "]";
}
}

 

 

package myserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Response {
private OutputStream out;

public Response(OutputStream out) {
this.out = out;
}

//发送消息到浏览器
public void sendMessage(String msg) {
try {
out.write(msg.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public void sendFile(String filePath) throws IOException {
File f = new File(filePath);
if (f.exists() == false) {//判断文件是否存在
System.out.println("文件不存在,请自行建立");
return;
}
InputStream in = null;
try {
in = new FileInputStream(filePath);
byte[] by = new byte[1024];
int len = 0;
while ((len=in.read(by)) != -1) {
out.write(by, 0, len);//读取1024字节并写入到浏览器
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
in.close();
}
}
}

 

 

package bean;

public class UserBean {
/**编号*/
private int id;
/**用户名*/
private String userName;
/**密码*/
private String pwd;
/**等级*/
private String grade;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}

public UserBean() {}

public UserBean(String userName, String pwd, String grade) {
this.userName = userName;
this.pwd = pwd;
this.grade = grade;
}

@Override
public String toString() {
return "UserBean [id=" + id + ", userName=" + userName + ", pwd=" + pwd
+ ", grade=" + grade + "]";
}
}

 

 

package dao;

import java.util.List;

import bean.UserBean;

public interface IUserDao {
/**
* 登录接口
* @param name 登录用户名
* @param pwd 登录密码
* @return 拥有用户名和密码的用户对象,没有返回null
* @throws Exception
*/
public UserBean login(String name,String pwd) throws Exception;
/**
* 添加用户
* @param bean 用户对象
* @throws Exception
*/
public void add(UserBean bean) throws Exception;
/**
* 删除用户
* @param id 用户ID
* @throws Exception
*/
public void del(int id) throws Exception;
/**
* 按ID修改密码
* @param id
* @param pwd 新密码
* @throws Exception
*/
public void update(int id, String pwd) throws Exception;
/**
* 根据ID查询
* @param id 用户ID
* @return 用户对象
* @throws Exception
*/
public UserBean findById(int id) throws Exception;
/**
* 查询所有用户
* @return 用户集合
* @throws Exception
*/
public List<UserBean> findAll() throws Exception;
}

 

 

package dao.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 父类DAO持久层
* @author Administrator
*
*/
public class BaseDao {
/**连接对象*/
protected Connection con;
/**预编译SQL语句对象*/
protected PreparedStatement ps;
/**结果集对象*/
protected ResultSet rs;

public void setConnection(){
try {
Class.forName("org.gjt.mm.mysql.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8","root","199212");
} catch (Exception e) {
e.printStackTrace();
}
}

public void closeConnection(){
try {
if (rs != null){
rs.close();
}
if (ps != null){
ps.close();
}
if (con != null){
con.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}

// public static void main(String[] args) {
// BaseDao dao = new BaseDao();
// dao.setConnextion();
// System.out.println(dao.con);
// }
}

 

 

package dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import bean.UserBean;
import dao.IUserDao;

public class UserDaoImpl extends BaseDao implements IUserDao {
public static void main(String[] args) {
UserDaoImpl dao = new UserDaoImpl();
try {
//dao.add(new UserBean("123","123","employee"));
// Scanner sc = new Scanner(System.in);
// int id = sc.nextInt();
// UserBean bean = dao.findById(id);
// System.out.println(bean);
// if (bean.getId() == 0){
// System.out.println("第"+id+"个记录不存在");
// }else{
// //dao.update(id, "666666");
// dao.del(id);
// }
//System.out.println(dao.findAll());
List<UserBean> list = dao.findAll();
for (UserBean bean : list){
System.out.println(bean);
}
UserBean bean = dao.login("123", "1231");
if (bean == null){
System.out.println("该用户不存在");
}else{
System.out.println(bean);
}
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public UserBean login(String name, String pwd) throws Exception {
this.setConnection();
ps = con.prepareStatement("select * from t_user where userName=? and pwd=?");
ps.setString(1, name);
ps.setString(2, pwd);
rs = ps.executeQuery();
UserBean bean = null;
if (rs.next()){
bean = new UserBean();
bean.setGrade(rs.getString("grade"));
bean.setId(rs.getInt("id"));
bean.setPwd(rs.getString("pwd"));
bean.setUserName(rs.getString("userName"));
}
this.closeConnection();
return bean;
}

@Override
public void add(UserBean bean) throws Exception {
this.setConnection();
ps = con.prepareStatement("insert into t_user(userName,pwd,grade) values(?,?,?)");
ps.setString(1, bean.getUserName());
ps.setString(2, bean.getPwd());
ps.setString(3, bean.getGrade());
ps.executeUpdate();//必须跟新不然添加不进去
this.closeConnection();
}

@Override
public void del(int id) throws Exception {
this.setConnection();
ps = con.prepareStatement("delete from t_user where id = ?");
ps.setInt(1, id);
ps.executeUpdate();//必须跟新不然删除不掉
this.closeConnection();
}

@Override
public void update(int id, String pwd) throws Exception {
this.setConnection();
ps = con.prepareStatement("update t_user set pwd=? where id = ?");
ps.setString(1, pwd);
ps.setInt(2, id);
ps.executeUpdate();
this.closeConnection();
}

@Override
public UserBean findById(int id) throws Exception {
this.setConnection();
ps = con.prepareStatement("select * from t_user where id = ?");
ps.setInt(1, id);
rs = ps.executeQuery();
UserBean bean = new UserBean();
if (rs.next()){
bean.setId(rs.getInt("id"));
bean.setGrade(rs.getString("grade"));
bean.setPwd(rs.getString("pwd"));
bean.setUserName(rs.getString("userName"));
}
this.closeConnection();
return bean;
}

@Override
public List<UserBean> findAll() throws Exception {
this.setConnection();
ps = con.prepareStatement("select * from t_user");
rs = ps.executeQuery();
List<UserBean> list = new ArrayList<UserBean>();
while (rs.next()){
UserBean bean = new UserBean();
bean.setId(rs.getInt("id"));
bean.setGrade(rs.getString("grade"));
bean.setPwd(rs.getString("pwd"));
bean.setUserName(rs.getString("userName"));
list.add(bean);
}
this.closeConnection();
return list;
}
}

 

package service;

import bean.UserBean;
import dao.IUserDao;
import dao.impl.UserDaoImpl;
import myserver.Request;
import myserver.Response;

/**
* 处理登录业务
* @author Administrator
*
*/
public class LoginService {
private IUserDao dao = new UserDaoImpl();
//servlet底层实现
public void service(Request request, Response response) throws Exception{
String nameTxt = request.getParameter("userName");
String pwdTxt = request.getParameter("pwd");
UserBean bean = dao.login(nameTxt, pwdTxt);
if (bean!=null){
response.sendMessage("<html><meta charset='utf-8'><span style='color:blue'>登录成功</span></html>");
}else{
response.sendMessage("<html><meta charset='utf-8'><span style='color:red'>登录失败</span></html>");
}
}
}

 

 

package service;

import java.util.List;

import bean.UserBean;
import dao.IUserDao;
import dao.impl.UserDaoImpl;
import myserver.Request;
import myserver.Response;

public class FindAllService {
/**用户持久对象*/
private IUserDao dao = new UserDaoImpl();

public void service(Request request, Response response) throws Exception{
List<UserBean> list = dao.findAll();

response.sendMessage("<html><meta charset='utf-8'><table border='1' cellspacing='0' width='60%'>");
response.sendMessage("<thead><tr><th>用户名</th><th>等级</th></tr></thead><tbody>");
for (UserBean bean : list){
response.sendMessage("<tr><td>"+bean.getUserName()+"</td><td>"+bean.getGrade()+"</td></tr>");
}

response.sendMessage("</tbody></table></html>");
}
}

 

 

package service;

import bean.UserBean;
import dao.IUserDao;
import dao.impl.UserDaoImpl;
import myserver.Request;
import myserver.Response;

public class AddService {
private IUserDao dao = new UserDaoImpl();

public void service(Request request, Response response) throws Exception{
String userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String grade = request.getParameter("grade");

UserBean bean = new UserBean(userName,pwd,grade);
dao.add(bean);
//调用查询所有业务方法,重新显示所有用户
FindAllService findAll = new FindAllService();
findAll.service(request, response);
}
}

posted @ 2017-10-18 22:01  沉迷学习,日渐消瘦  阅读(883)  评论(0编辑  收藏  举报