掌握Annotation的使用和解析
重新回顾反射的使用
初步了解MVC框架的运
转机制
1.Annotation
在JDK5之后,增加Annotation注解的基本语法,通 过注解可以省略XML的配置信息,简化代码的编写形式。
语法:
@Target(ElementType.xxxx)
@Retention(RetentionPolicy.xxxx)
public @interface 注解名 {
}
Target:对应的是当前的注解能够定义在哪个位置上
ElementType.Type -- 类ElementType.Field -- 字段
两个
Annotation:
@Controller
package com.csi.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
}
@RequestMapping
package com.csi.annotation;
importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;
importjava.lang.annotation.RetentionPolicy;
importjava.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)public@interfaceRequestMapping{
Stringvalue()default"";
}
2. 解析Annotation
2.1 将所有包含了@Controller类进
行遍历
扫描包的工具类
public class ClassLoaderContextListener implements servletcontextlistener {
@Override
public void contextinitialized(ServletContextEvent sce) {
initClassLoader();
}
private void initClassLoader() {
//根据包找到包下面所有的类
List<Class<?>> classList = ClassScanner.getClasssFromPackage("com.csi.controller");
for (Class<?> clazz : classList) {
//如果点给钱类上存在Controller,就要获取方法啊
if (clazz.isAnnotationPresent(Controller.class)){
Method[] methods = clazz.getmethods();
//遍历当前包含了Controller注解的所有方法
for (Method method : methods) {
//判断方法上是否添加了RequestMapping注解
if (method.isAnnotationPresent(RequestMapping.class)){
//获取到包含RequestMapping注解的value值
String urlPath = method.getAnnotation(RequestMapping.class).value();
//将值作为键,将方法作为值,存储在map集合中
WebApplicationContext.methodMap.put(urlPath,method);
}
}
}
}
}
2.2
解析用户的请求路径
public class dispatcherServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws servletexception, IOException {
//步骤1:获取到用户的请求URL
String urlPath = req.getServletPath() ;
Method method = WebApplicationContext.methodMap.get(urlPath);
if (method != null){
//步骤2:调用对应的Method方法
//2-1:如何找到要对应的类
Object instance = null;
try {
instance = method.getDeclaringClass().newInstance();
} catch (InstantiationException e) {
e.printstacktrace();
} catch (illegalaccessexception e) {
e.printstacktrace();
}
//2-2:如何传输参数:request,response
try {
method.invoke(instance,req,resp) ;
} catch (illegalaccessexception e) {
e.printstacktrace();
} catch (InvocationTargetException e) {
e.printstacktrace();
}
}else {
resp.sendRedirect("failure.jsp");
}
}
}
3.
使用
需要在工程下建立
com.csi.controller
的包
package com.csi.controller;
import com.alibaba.fastjson.JSON;
import com.csi.annotation.Controller;
import com.csi.annotation.RequestMapping;
import com.csi.domain.Product;
import com.csi.domain.Result;
import com.csi.service.ProductService;
import com.csi.service.impl.ProductServiceImpl;
import javax.servlet.servletexception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@Controller
public class ProductController {
@RequestMapping("/product/toshowpage.do")
public void to_show_page(HttpServletRequest request, HttpServletResponse response)throws servletexception, IOException {
request.setAttribute("hello","world");
request.getRequestdispatcher("/show.jsp").forward(request,response);
}
@RequestMapping ("/product/list.do")
public void list(HttpServletRequest request,HttpServletResponse response) throws IOException {
response.setContentType("application/json;charset=utf-8");
int categoryId = Integer.parseInt(request.getParameter("categoryId")) ;
ProductService productService = new ProductServiceImpl() ;
List<Product> products = productService.listByCategory4Index(categoryId);
Result result = new Result() ;
if(products.size() != 0) {
result.setMsg("success");
result.setCode(200);
result.setData(products);
}else{
result.setCode(400);
result.setMsg("数据为空!");
}
String jsonStr = JSON.toJSONString(result) ;
PrintWriter out = response.getWriter() ;
out.println(jsonStr);
}
}
jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$.get("/product/list.do?categoryId=548",function(data) {
if(data.code == 200) {
$(data.data).each(function(i,o) {
var divTag = "<div class='product_info'><img src='" + o.fileName + "'></img><p>" + o.name + "</p><p>¥" + o.price + "</p></div>" ;
$("#data_show").append(divTag) ;
}) ;
}else{
$("#data_show").html(data.msg) ;
}
}) ;
})
</script>
<style type="text/css">
.product_info{
border: 1px solid #c2e0d9;
float: left;
width: 200px;
}
</style>
</head>
<body>
<div id="data_show">
</div>
</body>
</html>