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);
}
}
Tomcat底层实现的更多相关文章
- tomcat底层原理实现
1.首先完成一个server类,用来接收客户端的请求:代码都在一个while(true)循环中,模拟tomcat一直在启动,其中绑定一个端口,用来监听一个端口,然后创建一个输入流,获取请求的输入流,然 ...
- Servlet和Tomcat底层源码分析
Servlet 源码分析 Servlet 结构图 Servlet 和 ServletConfig 都是顶层接口,而 GenericServlet 实现了这两个顶层接口,然后HttpServlet ...
- 【Spring boot】整合tomcat底层原理
本文结论 源码基于spring boot2.6.6 项目的pom.xml中存在spring-boot-starter-web的时候,在项目启动时候就会自动启动一个Tomcat. 自动配置类Servle ...
- Tomcat底层通过全类名创建对象的实现
示例: //com.neuedu.baier.entity.User为User类的全类名 //要求JVM查找并加载指定的类,也就是说JVM会执行该类的静态代码段 Class<?> user ...
- tomcat相关配置技巧梳理
tomcat常用架构:1)nginx+tomcat:即前端放一台nginx,然后通过nginx反向代理到tomcat端口(可参考:分享一例测试环境下nginx+tomcat的视频业务部署记录)2)to ...
- tomcat相关配置技巧梳理 (修改站点目录、多项目部署、限制ip访问、大文件上传超时等)
tomcat常用架构:1)nginx+tomcat:即前端放一台nginx,然后通过nginx反向代理到tomcat端口(可参考:分享一例测试环境下nginx+tomcat的视频业务部署记录)2)to ...
- Tomcat server.xml中Connector配置参数详解
Tomcat中Connector常用配置 Tomcat中server.xml有些配置信息是需要我们了解的,最起码知道如何进行简单的调试. <Connector port="8080&q ...
- Spring Boot2.0之 原理—创建内置Tomcat容器
前面所述的https://www.cnblogs.com/toov5/p/9823728.html 中的第一条先不赘述了,就是玩了maven 重点介绍后两条 首先内置Tomcat: SpringBoo ...
- tomcat 代码集
Tomcat类是整个tomcat的起点,负责加载所有的配置信息以及把配置信息解析转换成tomcat组件对象. Context addWebapp(String contextPath, String ...
随机推荐
- E - Down or Right Codeforces Round #504 (rated, Div. 1 + Div. 2, based on VK Cup 2018 Final)
http://codeforces.com/contest/1023/problem/E 交互题 #include <cstdio> #include <cstdlib> #i ...
- BZOJ 3771 母函数裸题
题目描述 我们讲一个悲伤的故事. 从前有一个贫穷的樵夫在河边砍柴. 这时候河里出现了一个水神,夺过了他的斧头,说: “这把斧头,是不是你的?” 樵夫一看:“是啊是啊!” 水神把斧头扔在一边,又拿起一个 ...
- Docker Swarm 服务编排之命令
一.简介 Docker有个编排工具docker-compose,可以将组成某个应该的多个docker容器编排在一起,同时管理.同样在Swarm集群中,可以使用docker stack 将一组相关联的服 ...
- Git6:Git简单远程仓库部署
目录 一.服务端操作 二.客户端操作 一.服务端操作 1.安装git yum install -y git 2.创建git用户 useradd git 3.创建客户端登录证书 收集所有需要登录的用户的 ...
- Java基础-DButils工具类(QueryRunner)详解
Java基础-DButils工具类(QueryRunner)详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 如果只使用JDBC进行开发,我们会发现冗余代码过多,为了简化JDBC ...
- [IOI2011]Race
2599: [IOI2011]Race Time Limit: 70 Sec Memory Limit: 128 MBhttp://www.lydsy.com/JudgeOnline/problem ...
- python核心编程笔记——Chapter7
Chapter7.映像和集合类型 最近临到期末,真的被各种复习,各种大作业缠住,想想已经荒废了python的学习1个月了.现在失去了昔日对python的触觉和要写简洁优雅代码的感觉,所以临到期末毅然继 ...
- CodeForces - 1040B Shashlik Cooking
Long story short, shashlik is Miroslav's favorite food. Shashlik is prepared on several skewers simu ...
- MFC基于对话框风格按钮控件添加图片的方法(大神止步)
菜鸟还在研究这个东西,大神就不要看了.一直都在觉得用VC或VS建立的对话框总是全灰色感觉太单调了,如果可以在上面添加一些漂亮的图片就好了,今天终于实现了.其实挺简单的,下面就分几个步骤讲一下: 第一步 ...
- opencv的基本数据结构(二)(转)
转自:原文链接,以下代码.图片.内容有点改动,只为转载不降低博客内容的可阅性,版权归原作者所有. OpenCV中强大的Mat类型大家已经比较熟悉了.这里梳理一些在工程中其他经常用到的几种基本数据类型. ...