FlyFish源码讲解3.0 Java
时间: 2023-11-27 11:49:41 浏览: 164
FlyFish 3.0 是一个基于 Java 开发的轻量级 Web 框架,它采用了 MVC 设计模式,具有简单易用、灵活高效、扩展性强等特点。下面我们来讲解一下 FlyFish 3.0 的源码。
1. 核心配置文件
FlyFish 3.0 的核心配置文件是 flyfish.properties,它位于 src/main/resources 目录下。该文件中定义了一些框架的基本配置信息,如数据库连接信息、视图文件存放路径、路由器类名等。以下是 flyfish.properties 文件的示例:
```
# 数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=123456
# 视图文件存放路径
view.path=/WEB-INF/views/
# 路由器类名
router.class=com.flyfish.mvc.router.DefaultRouter
```
2. 核心类
FlyFish 3.0 的核心类是 com.flyfish.mvc.DispatcherServlet,它是一个 Servlet 类,负责接收客户端请求并进行分发处理。该类的 doGet 方法中首先获取请求的 URI,然后根据 URI 获取对应的控制器类和方法,最后调用该方法并返回处理结果。
```
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uri = request.getRequestURI();
Method method = router.route(uri);
if (method != null) {
try {
Object result = method.invoke(controllerFactory.getController(method.getDeclaringClass()), request, response);
if (result instanceof String) {
request.getRequestDispatcher(viewResolver.resolve((String) result)).forward(request, response);
} else if (result instanceof ModelAndView) {
ModelAndView modelAndView = (ModelAndView) result;
request.getRequestDispatcher(viewResolver.resolve(modelAndView.getViewName())).forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
```
3. 控制器类
控制器类是 FlyFish 3.0 的核心组件之一,它们负责接收客户端请求并进行处理。控制器类必须实现 com.flyfish.mvc.Controller 接口,并且通常以 Controller 结尾。以下是一个示例控制器类:
```
public class UserController implements Controller {
private UserService userService = new UserService();
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
String action = request.getParameter("action");
if ("list".equals(action)) {
List<User> userList = userService.getUserList();
ModelAndView modelAndView = new ModelAndView("user/list");
modelAndView.addAttribute("userList", userList);
return modelAndView;
} else if ("add".equals(action)) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
User user = new User(username, password, email);
userService.addUser(user);
return new ModelAndView("redirect:/user?action=list");
} else {
return new ModelAndView("redirect:/user?action=list");
}
}
}
```
4. 视图解析器
视图解析器是负责将控制器返回的逻辑视图名称解析成实际的视图文件路径的组件。FlyFish 3.0 中提供了两种视图解析器:InternalResourceViewResolver 和 JspViewResolver。以下是 InternalResourceViewResolver 的示例代码:
```
public class InternalResourceViewResolver implements ViewResolver {
private String prefix;
private String suffix;
public InternalResourceViewResolver(String prefix, String suffix) {
this.prefix = prefix;
this.suffix = suffix;
}
@Override
public String resolve(String viewName) {
return prefix + viewName + suffix;
}
}
```
5. 路由器
路由器是负责将请求 URI 映射到控制器类和方法的组件。FlyFish 3.0 中提供了 DefaultRouter 和 AnnotationRouter 两种路由器,其中 DefaultRouter 是默认的路由器实现。以下是 DefaultRouter 的示例代码:
```
public class DefaultRouter implements Router {
private Map<String, Method> routeMap = new HashMap<>();
public DefaultRouter(List<Class<?>> controllerClassList) {
for (Class<?> controllerClass : controllerClassList) {
Method[] methods = controllerClass.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
String uri = requestMapping.value();
routeMap.put(uri, method);
}
}
}
}
@Override
public Method route(String uri) {
return routeMap.get(uri);
}
}
```
6. 数据库访问
FlyFish 3.0 中提供了 JdbcTemplate 类来简化数据库访问操作。以下是 JdbcTemplate 的示例代码:
```
public class JdbcTemplate {
private Connection connection;
public JdbcTemplate(String jdbcUrl, String jdbcUsername, String jdbcPassword) throws SQLException {
connection = DriverManager.getConnection(jdbcUrl, jdbcUsername, jdbcPassword);
}
public <T> List<T> queryForList(String sql, RowMapper<T> rowMapper, Object... params) throws SQLException {
List<T> resultList = new ArrayList<>();
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
resultList.add(rowMapper.mapRow(resultSet));
}
return resultList;
}
public int update(String sql, Object... params) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
preparedStatement.setObject(i + 1, params[i]);
}
return preparedStatement.executeUpdate();
}
public void close() throws SQLException {
connection.close();
}
}
```
7. 安全过滤器
FlyFish 3.0 中提供了 SecurityFilter 类来实现基本的安全过滤功能。SecurityFilter 可以通过配置文件进行配置,支持白名单和黑名单两种模式。以下是 SecurityFilter 的示例代码:
```
public class SecurityFilter implements Filter {
private Set<String> excludeSet = new HashSet<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String mode = filterConfig.getInitParameter("mode");
if ("white".equals(mode)) {
String excludeList = filterConfig.getInitParameter("exclude");
String[] excludeArray = excludeList.split(",");
excludeSet.addAll(Arrays.asList(excludeArray));
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
String uri = httpRequest.getRequestURI();
if (excludeSet.contains(uri)) {
chain.doFilter(request, response);
} else {
httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
}
}
@Override
public void destroy() {
// do nothing
}
}
```
阅读全文