从零开始写javaweb框架 pdf_大学写的一个 Java Web 框架

简介

today-web是一个基于Servlet的高性能轻量级Web框架。

安装

<dependency>
    <groupId>cn.taketoday</groupId>
    <artifactId>today-web</artifactId>
    <version>2.3.6.RELEASE</version>
</dependency>
Maven Central today-web​search.maven.org

快速入门

  • 第一步:新建项目

cb4c3e7048bfffc5b050c3c1beba06bd.png
选择Maven项目

bd455c5ae719d755157f0844621af1c0.png
选择类型

b5b7385496d69c4ace7b4f62d9ce0b51.png
设置坐标

6a57988f7ac8355b1043b8c93b7ff020.png
项目结构
  • 第二步:引入依赖
<dependency>
    <groupId>cn.taketoday</groupId>
    <artifactId>today-web</artifactId>
    <version>2.3.6.RELEASE</version>
</dependency>

<dependency>
    <groupId>cn.taketoday</groupId>
    <artifactId>today-context</artifactId>
    <version>2.1.5.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.28</version>
</dependency>

到此项目建立完毕,并不需要去管 web.xml 文件

  • 第三步:配置控制器
/**
 * @author TODAY <br>
 *         2018-12-02 22:30
 */
@RestController
@RequestMapping("index")
public class IndexController {

    @GET("{key}")
    public String index(@PathVariable String key) {
    	return key;
    }
	
    @GET
    @ResponseBody(false)
    public String index() {
    	return "index";
    }
}

使用模板引擎渲染页面

7d54c51f8544f8816f47c79c7d5b1234.png
Freemarker模板
  • 第四步:部署

fdd30806cb9665bc872bd5cbf6e9eda8.png
部署到Tomcat

8f6e74084ab7c5608f6b1577814f9f1c.png
@GET({key})

e299095b8633523ee15430c3ab390e8c.png
@GET

案例

TAKETODAY/today-web-demo​github.com
095884e56752a82debba07f4dd883327.png

使用说明

  • 通过 @Controller @RestController 配置控制器
//@Controller
@RestController
@RequestMapping("/users")
public class IndexController {
    
}
  • 配置请求
@GET("index")
@POST("post")
@PUT("articles/{id}")
......
@RequestMapping("/users/{id}")
@RequestMapping(value = "/users/**", method = {RequestMethod.GET})
@RequestMapping(value = "/users/*.html", method = {RequestMethod.GET})
@RequestMapping(value = {"/index.action", "/index.do", "/index"}, method = RequestMethod.GET)
@Interceptor({LoginInterceptor.class, ...})
public (String|List<?>|Set<?>|Map<?>|void|File|Image|...) w+ (request, request, session,servletContext, str, int, long ,
    byte, short, boolean, @Session("loginUser"),
   @Header("User-Agent"), @Cookie("JSESSIONID"), @PathVariable("id"), 
   @RequestBody("users"), @Multipart("uploadFiles") MultipartFile[]) {
    service...
    return </>;
}
  • 自定义参数转换器
@ParameterConverter 
public class DateConverter implements Converter<String, Date> {
    @Override
    public Date doConvert(String source) throws ConversionException {
        ...
    }
}

可以通过xml文件配置简单视图,静态资源,自定义视图解析器,文件上传解析器,异常处理器,参数解析器

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Web-Configuration PUBLIC 
		"-//TODAY BLOG//Web - Configuration DTD 2.0//CN"
			"https://taketoday.cn/framework/web/dtd/web-configuration-2.3.3.dtd">

<Web-Configuration>

    <controller prefix="/error/">
        <action resource="400" name="BadRequest" status="400" />
        <action resource="403" name="Forbidden" status="403" />
        <action resource="404" name="NotFound" status="404" />
        <action resource="500" name="ServerIsBusy" status="500" />
        <action resource="405" name="MethodNotAllowed" status="405" />
    </controller>

    <controller>
        <action resource="redirect:http://pipe.b3log.org/blogs/Today" name="today-blog-pipe" />
        <action resource="redirect:https://taketoday.cn" name="today" />
        <action resource="redirect:https://github.com" name="github" />
        <action resource="redirect:/login" name="login.do" />
    </controller>

    <controller class="cn.taketoday.web.demo.controller.XMLController" name="xmlController" prefix="/xml/">
        <action name="obj" method="obj" />
        <action name="test" resource="test" method="test"/>
    </controller>

</Web-Configuration>
  • 文件下载,支持直接返回给浏览器图片
@RequestMapping(value = {"/download"}, method = RequestMethod.GET)
public File download(String path) {
    return new File(path);
}
@GET("/display")
public final BufferedImage display(HttpServletResponse response) throws IOException {
    response.setContentType("image/jpeg");
    return ImageIO.read(new File("D:/taketoday.cn/webapps/upload/logo.png"));
}

@GET("captcha")
public final BufferedImage captcha(HttpServletRequest request) throws IOException {
    BufferedImage image = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_RGB);
    Graphics graphics = image.getGraphics();
    graphics.setColor(Color.WHITE);
    graphics.fillRect(0, 0, IMG_WIDTH, IMG_HEIGHT);
    Graphics2D graphics2d = (Graphics2D) graphics;
    drawRandomNum(graphics2d, request);
    return image;
}
  • 文件上传,支持多文件
@RequestMapping(value = { "/upload" }, method = RequestMethod.POST)
public final String upload(@Multipart MultipartFile uploadFile) throws IOException {

    String upload = "D:/www.yhj.com/webapps/upload/";
    String path = upload + uploadFile.getFileName();
    File file = new File(path);
    uploadFile.save(file);

    return "/upload/" + uploadFile.getFileName();
}

@POST({"/upload/multi"})
public final String multiUpload(HttpServletResponse response, @Multipart MultipartFile[] files) throws IOException {

    String upload = "D:/www.yhj.com/webapps/upload/";
    
    for (MultipartFile multipartFile : files) {
        String path = upload + multipartFile.getFileName();
        File file = new File(path);
        System.out.println(path);
        if (!multipartFile.save(file)) {
            return "<script>alert('upload error !')</script>";
            //response.getWriter().print("<script>alert('upload error !')</script>");
        }
    }
    //response.getWriter().print("<script>alert('upload success !')</script>");
    return "<script>alert('upload success !')</script>";
}
  • 登录实例
@Controller
public class UserController {

/* 
    <controller prefix="/WEB-INF/view/" suffix=".ftl">
        <action resource="login" name="login" />
        <action resource="register" name="register" />
    </controller> */
    
    // @GET("login")
    @RequestMapping(value = "/login" , method = RequestMethod.GET)
    public String login() {
        return "/login/login";//支持jsp,FreeMarker,Thymeleaf,自定义视图
    }
    
    // @POST("login")
    @ResponseBody
    @RequestMapping(value = "/login" , method = RequestMethod.POST)
    public String login(@RequestParam(required = true) String userId, @RequestParam(required = true) String passwd) {
        // service...
        if(userId.equals(passwd)) {
            return "{"msg":"登录成功"}";
        }
        return "{"msg":"登录失败"}";//支持pojo转json
    }
}

开源

请查看

TAKETODAY/today-web​github.com
095884e56752a82debba07f4dd883327.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值