写在前面
整个项目基于servlet 3.0开发,纯粹用于学习spring mvc框架原理的。框架设计的使用方式也尽量是参考spring mvc的,配置全部使用注解做,不要xml。由于作者本人水平有限(第二次写博客),代码若有错误或是遗漏,欢迎指正,再或是有更好的实现,更是跪求指教了。(联系qq1455066227@gmail.com)
- 项目实现功能
webmvc大部分功能aop(其实只是controller的aop手动划掉,哈哈)- 统一异常处理
- 集成模板引擎
thymeleaf
- 项目使用jdk8做开发。项目使用到的库
servlet 3.0: servletlog4j: 日志commons-fileupload: 文件上传gson: jsonthymeleaf: 模板引擎
使用效果如下(具体细节请参考之后的版本)
import cn.isaxon.iservlet.annation.*;
import cn.isaxon.iservlet.aspect.annotion.Intercept;
import cn.isaxon.iservlet.bean.HttpMethod;
import cn.isaxon.iservlet.bean.ThymeleafMap;
import cn.isaxon.iservlet.gson.GsonFilter;
import cn.isaxon.iservlet.z_test.User;
import cn.isaxon.iservlet.z_test.aspect.WebAspect;
import org.apache.log4j.Logger;
import javax.servlet.http.Part;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* <p></p>
* <p>Copyright:@isaxon.cn</p>
*
* @author saxon/isaxon
* Create 2017-12-19 10:29 By qq145
*/
@Controller
@CrossOrigin//(methods = {HttpMethod.POST})
@Intercept(type = WebAspect.class)
@RequestMapping({"/isaxon", "/test"})
public class TestController
{
private static Logger logger = Logger.getLogger(TestController.class);
@GetMapping({"/hello", "h"})
public String hello()
{
return "Hello";
}
@GetMapping("/hello/result")
public User result(@RequestParam("test") String test)
{
logger.info(test);
User user = new User();
user.name = test;
return user;
}
@RequestMapping(value = "/world", method = {HttpMethod.OPTIONS})
public int world()
{
return 15;
}
@PostMapping("/upload")
public void upload(@RequestParam("image") List<Part> fileItems,
@RequestParam("file") String file)
{
logger.info(fileItems.size());
logger.info(file);
fileItems.forEach(TestController::saveFile);
}
private static void saveFile(Part part)
{
try
{
logger.info(part.getSubmittedFileName());
part.getHeaderNames().forEach(logger::info);
part.write("/home/isaxon/Downloads/" + part.getSubmittedFileName());
} catch (Exception e)
{
logger.error(e.getMessage(), e);
}
}
@GetMapping("/home")
public ThymeleafMap thymeleafTest(@RequestParam("text") String text)
{
ThymeleafMap thymeleafMap = new ThymeleafMap("index.html");
thymeleafMap.put("val", text);
return thymeleafMap;
}
@GetMapping("/exception")
public String exception(@RequestParam("id") Integer id)
{
if (id == 0)
throw new NullPointerException("Id is not can be zero");
return "Hello World!";
}
private class GsonFilterTest
{
public Integer test = 15;
public Integer age = 10;
public String name = "11";
public String nsf = "sdf";
}
@GsonFilter({
@GsonFilter.GsonFieldFilter(type = User.class, include = {"name", "id"}),
@GsonFilter.GsonFieldFilter(type = GsonFilterTest.class, exclude = {"name", "nsf"}),
})
@GetMapping("/gosnfilter")
public Map<String, Object> gosnfilter()
{
User user = new User();
user.name = "@isaxon.cn";
user.age = 15;
Map<String, Object> result = new HashMap<>();
result.put("USer", user);
result.put("GsonFilterTest", new GsonFilterTest());
return result;
}
}