大學寫的一個 Java Web 框架

前言

大學剛畢業,專業是電子信息工程。大一開始學Java,準確的說是高三最後的幾周開始的. 果真興趣是最好的老師, 在大一下學期本身從前端到後臺寫了個人我的網站:TODAY BLOG 。 從註冊域名到備案再到網站成功上線,我遇到過的困難不可勝數。由於感興趣因此我堅持了下來。第一個版本使用的純Servlet寫的。後來瞭解到Java有不少開源框架能夠簡化個人開發。因而又投入到新一輪的學習之中...... 學了Struts2後本身學着寫了一個小框架:TODAY WEB,幾百行搞定從解析xml定義的action處處理對應的請求。學了Spring MVC後,我寫了此項目:TODAY WEB 2.0html

簡介

Codacy Badge
today web是一個基於Servlet的高性能輕量級Web框架

安裝

<dependency>
    <groupid>cn.taketoday</groupid>
    <artifactid>today-web</artifactid>
    <version>2.3.6.RELEASE</version>
</dependency>

複製代碼

快速入門

第一步: 新建項目

新建項目

2.png

3.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 文件java

第三步:配置控制器

/** * @author Today <br> * 2018-12-02 22:30 */
@RestController
@RequestMapping("index")
public class IndexController {

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


複製代碼

Freemarker模板git

Freemarker模板

第四步:部署項目到Tomcat

部署項目到Tomcat

查看效果

@GET("{key}")github

7.png

@GETweb

8.png

案例

使用說明

經過 @Controller @RestController 配置控制器json

//@Controller
@RestController
@RequestMapping("/users")
public class UserController {
    
}

複製代碼

配置請求瀏覽器

@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 ;
}

複製代碼

自定義參數轉換器session

@Singleton
public class DateConverter implements Converter<string, date> {
    @Override
    public Date convert(String source) throws ConversionException {
        ...
    }
}

複製代碼

也能夠經過xml文件配置簡單視圖,靜態資源,自定義視圖解析器,文件上傳解析器,異常處理器,參數解析器app

<!--?xml version="1.0" encoding="UTF-8"?-->


<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>

複製代碼

登陸實例

@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
    }
}

複製代碼

文件下載,支持直接返回給瀏覽器圖片

@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>";
}

複製代碼

GitHub

github.com/TAKETODAY/t…

瘋狂暗示 😋

相關文章
相關標籤/搜索