Java注解复习
Bean.java
@Target(ElementType.TYPE) //可以作用在接口、类、枚举、注解
@Retention(RetentionPolicy.RUNTIME)
public @interface Bean {
public String id();
}
Property.java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
String ref();
}
EmapDao.java
@Bean(id = "empDao")
public class EmpDao {
public void insert() {
System.out.println("insert....");
}
}
EmpService.java
@Bean(id="empService")
public class EmpService {
@Property(ref="empDao")
private EmpDao empDao;
public void addEmp() {
empDao.insert();
}
}
BeanFactory.java
public class BeanFactory {
private static Map<String, Object> map = new HashMap<>();
static {
try {
init();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void init() throws Exception {
// 解析xml为文件,获取包路径
SAXReader reader = new SAXReader();
Document document = reader.read("config/Test0811.xml");
Element root = document.getRootElement();
Element e = root.element("context-scan");
String packageName = e.attributeValue("package");
// 获取该路径下的文件D:\SubjectSoftware\MyEclipse\eclipse-workspace\hhh0810\Demo0811
// Properties p = System.getProperties();
// System.out.println(p);
// System.out.println();
String path = System.getProperty("user.dir") + "\\src\\" + packageName;
// System.out.println(path);
// System.out.println(System.getProperty("user.dir"));//获取工作目录
File file = new File(path);
File[] files = file.listFiles();// 获取所有文件和文件夹
for (File f : files) {
if (f.isFile()) {
// EmpDao.java用点将类名读到
String fileName = f.getName().substring(0, f.getName().indexOf("."));
String className = packageName + "." + fileName;
Class<?> class1 = Class.forName(className);
if (class1.isAnnotationPresent(Bean.class)) {
Bean bean = class1.getAnnotation(Bean.class);
String id = bean.id();
map.put(id, class1.newInstance());
}
}
}
for (File f : files) {
if (f.isFile()) {
// EmpDao.java用点将类名读到
String fileName = f.getName().substring(0, f.getName().indexOf("."));
String className = packageName + "." + fileName;
Class<?> class1 = Class.forName(className);
if (class1.isAnnotationPresent(Bean.class)) {
Bean bean = class1.getAnnotation(Bean.class);
String id = bean.id();
//获取所有成员变量
Field[] fields = class1.getDeclaredFields();
for(Field field:fields) {
if(field.isAnnotationPresent(Property.class)) {
Property p = field.getAnnotation(Property.class);
field.setAccessible(true);
//map.get(id)表示当前类对象
//map.get(p.ref())表示成员变量的类型的对象
field.set(map.get(id),map.get(p.ref()));
}
}
}
}
}
}
public static Object getBean(String key) {
return map.get(key);
}
public static void main(String[] args) {
System.out.println(map);
}
}
Test.java
public class Test {
public static void main(String[] args) {
EmpService empService = (EmpService)BeanFactory.getBean("empService");
empService.addEmp();
}
}
模拟客户端和服务器之间的交互
第一个版本
写服务器端,多线程的服务器端(ClientHandler)
1.包:cn.tedu.core
2.类名:WebServer
3.声明成员变量:
server:ServerSocket
4.方法:
无参的构造方法:WebServer
功能:初始化server,端口号为8080
start方法:
功能:启动服务器
接收客户端请求:accept()
定义线程对象,并启动线程start()
5.定义内部类:ClientHandler
线程类定义成员变量:socket:Socket
定义带参的构造方法初始化:socket
重写run方法:功能:控制台输出处理客户端请求
6.定义main方法:启动服务器
7.测试:打开浏览器客户端:http://localhost:8888
public class WebServer_v1 {
ServerSocket server;
public WebServer_v1() {
try {
server = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
while (true) {
Socket socket;
try {
while (true) {
System.out.println("等待客户端的请求");
socket = server.accept();
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
Socket socket;
public ClientHandler() {
}
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
System.out.println("接收客户端请求");
}
}
public static void main(String[] args) {
new WebServer_v1().start();
}
}
第二个版本
1.读客户端的请求
在run方法处理客户端请求
1)获取InputStream对象
2)使用read方法读取数据,判断如果!=-1,输出
int d = -1;
while((d= in.read())!=-1){
System.out.print((char)d);
}
3)观察打印结果:学习http协议请求头信息格式
2.解析请求行:使用StringBuilder存放
StringBuilder builder = new StringBuilder();
int d = -1;
char c1 = 0,c2=0;
while((d= in.read())!=-1){
c2 = (char)d;
if(c1== 13 && c2 == 10){
break;
}
builder.append(c2);
c1 = c2;
}
System.out.println(builder.toString().trim());
in.close();
2)测试:打开浏览器客户端:http://localhost:8080/myweb/index.html
3.解析url,并打印输出
public class WebServer_v2 {
ServerSocket server;
public WebServer_v2() {
try {
server = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
while (true) {
Socket socket;
try {
while (true) {
System.out.println("等待客户端的请求");
socket = server.accept();
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
Socket socket;
public ClientHandler() {
}
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// \r\n ASCⅡ 13 10
System.out.println("接收客户端请求");
//获取请求状态行
try {
InputStream in = socket.getInputStream();
StringBuilder builder = new StringBuilder();
char c1 = 0,c2 = 0;
int d = -1;
while((d=in.read())!=-1) {
c2 = (char)d;
//解析第一行,遇到 \r\n,break
if(c1 == 13 && c2 == 10) {
break;
}
builder.append(c2);
c1 = c2;
}
String str = builder.toString().trim();//去掉字符串两端的多余的空格,
String[] data = str.split(" ");//用空格分隔开str,并存入数组中
System.out.println(data[0]);//获取请求方式get
System.out.println(data[1]);//url请求
System.out.println(data[2]);//协议名称
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new WebServer_v2().start();
}
}
第三个任务:
1.定义HttpRequest类
1)定义HttpRequest类在com.tedu.http包中
2)定义变量:method,url,protocol;
3)定义带参的构造方法HttpRequest(InputStream in)
4)定义三个变量的get方法
5)定义方法:parseRquestLine(InputStream in):void
方法的功能:解析请求行,给三个变量赋值
在构造方法中调用
2.重构WebServer的run方法
创建HttpRequest对象,调用get方法打印请求的方法,url,protocl
3.测试:打开浏览器客户端:http://localhost:8888/myweb/index.html
public class WebServer {
ServerSocket server;
public WebServer() {
try {
server = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
while (true) {
Socket socket;
try {
while (true) {
System.out.println("等待客户端的请求");
socket = server.accept();
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
Socket socket;
public ClientHandler() {
}
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// \r\n ASCⅡ 13 10
System.out.println("接收客户端请求");
//获取请求状态行
try {
InputStream in = socket.getInputStream();
HttpRequest request =new HttpRequest(in);
System.out.println(request.getMethod());
System.out.println(request.getUrl());
System.out.println(request.getProtocol());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new WebServer().start();
}
]
}
第四个任务
读文件,响应文件到客户端
1.在项目中添加目录webapps,并在里面添加一个子目录myweb,然后在其中存放我们定义的页面index.html
2.响应包括两部分,响应头和响应文件
3.学习掌握响应头信息
4.响应画面到客户端
1)读文件:通过url File file = new File(“webapps”+request.getUrl());
2)获取输出流
3)通过输出流写响应头信息
public class WebServer {
ServerSocket server;
public WebServer() {
try {
server = new ServerSocket(8888);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start() {
while (true) {
Socket socket;
try {
while (true) {
System.out.println("等待客户端的请求");
socket = server.accept();
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ClientHandler implements Runnable {
Socket socket;
public ClientHandler() {
}
public ClientHandler(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// \r\n ASCⅡ 13 10
System.out.println("接收客户端请求");
//获取请求状态行
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
HttpRequest request =new HttpRequest(in);
// System.out.println(request.getMethod());
// System.out.println(request.getUrl());
// System.out.println(request.getProtocol());
File file = new File("webapps"+request.getUrl());
//响应页面
//状态行
out.write("HTTP/1.1 200 OK".getBytes());
out.write(13);
out.write(10);
//响应头信息
out.write("Content-Type:text/html".getBytes());
out.write(13);
out.write(10);
out.write(("Content-Length:"+file.length()).getBytes());
out.write(13);
out.write(10);
//空行
out.write(13);
out.write(10);
//响应的文档内容
FileInputStream fin = new FileInputStream(file);
byte[] buffer = new byte[(int)file.length()];
fin.read(buffer);
out.write(buffer);
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new WebServer().start();
}
}
public class HttpRequest {
public String method;
public String url;
public String protocol;
public HttpRequest() {}
public HttpRequest(InputStream in) {
try {
parseRequestLine(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getMethod() {
return method;
}
public String getUrl() {
return url;
}
public String getProtocol() {
return protocol;
}
public void parseRequestLine(InputStream in) throws IOException {
StringBuilder builder = new StringBuilder();
char c1 = 0,c2 = 0;
int d = -1;
while((d=in.read())!=-1) {
c2 = (char)d;
//解析第一行,遇到 \r\n,break
if(c1 == 13 && c2 == 10) {
break;
}
builder.append(c2);
c1 = c2;
}
String str = builder.toString().trim();
String[] data = str.split(" ");
this.method = data[0];//获取请求方式get
this.url = data[1];//url请求
this.protocol = data[2];//协议名称
}
}