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 ...
随机推荐
- 3:JavaBean,EJB,POJO
JavaBeanJavaBean是公共Java类,但是为了编辑工具识别,需要满足至少三个条件: 有一个public默认构造器(例如无参构造器,) 属性使用public 的get,set方法访问,也就是 ...
- 题解【bzoj1251 序列终结者】
Description 维护三个操作:区间加,区间翻转,区间求最大值.\(n \leq 50000\) Solution fhqtreap大法好! 模板题(我是不会告诉你这篇题解是用来存个代码的 Co ...
- 【Asp.net入门09】第一个ASP.NET 应用程序-处理窗体(1)
我们创建了一个HTML窗体,可以通过它显示受邀参加晚会的嘉宾,但是,当嘉宾单击Submit RSVP按钮时,同一个页面会反复多次显示.为了解决此问题,需要实现一段代码,用于在将窗体数据发布到服务器时执 ...
- error: failed to connect to the hypervisor error: Failed to connect socket to '/var/run/libvirt/libvirt-sock': No such file or directory 解决办法
服务器版本:CentOS Linux release 7.4 Linux lb 3.10.0-693.el7.x86_64 #1 SMP Tue Aug 22 21:09:27 UTC 2017 x8 ...
- P2684 搞清洁
P2684 搞清洁 给定一段区间及若干个线段, 求使区间被完全覆盖所需的最少线段数 错误日志: 菜 Solution 补一下贪心吧 这题最小线段覆盖 首先按照左端点排序 现在对于所有左区间到达目前已覆 ...
- Hadoop生态圈-Hive的自定义函数之UDTF(User-Defined Table-Generating Functions)
Hadoop生态圈-Hive的自定义函数之UDTF(User-Defined Table-Generating Functions) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.
- C语言复习---判断素数
一般 int main01() { ; scanf("%d", &a); n_sqrt = sqrt(a); ; i <= n_sqrt; i++) ) { flag ...
- python---权限管理和菜单生成
一:表结构(共八张表) from django.db import models # Create your models here. class User(models.Model): userna ...
- 手把手教你使用koa2
简介 koa是由express的原班人马打造的web框架.但是相对于express,koa的性能要更高,因为koa通过使用aysnc函数,帮你丢弃回调函数,并有力的增强了错误处理.而且koa没有绑定任 ...
- Rolling in the Deep (Learning)
Rolling in the Deep (Learning) Deep Learning has been getting a lot of press lately, and is one of t ...