本节通过一个简单的javaweb项目来体会gradle的使用
需求
构建一个javaweb项目,搭建jsp+servlet开发环境
可以将需求分解为两步:
- 使用gradle构建一个java项目
- 为该项目构建web视图层
工具
- gradle4.3
- idea
- jdk 1.8
实验过程
首先在idea中创建一个空的gradle项目
创建如下目录-文件结构
在构建脚本中写入如下内容
group 'com.shy'
version '1.0-SNAPSHOT'
apply plugin:'java'
apply plugin:'war'
apply from: 'https://raw.github.com/akhikhl/gretty/master/pluginScripts/gretty.plugin'
jar{
manifest{
attributes 'Main-Class':'com.shy.todo.ToDoApp'
}
}
repositories{
mavenCentral();//对maven central 2仓库访问的快捷方式
}
dependencies{
providedCompile 'javax.servlet:servlet-api:2.5'
runtime 'javax.servlet:jstl:1.2'
}
task wrapper(type:Wrapper ){
gradleVersion = '4.3'
}
- web.xml配置如下
使用一个ToDoServlet来接受所有的请求
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>ToDoServlet</servlet-name>
<servlet-class>com.shy.todo.web.ToDoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ToDoServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- ToDoServlet负责转发请求
public class ToDoServlet extends HttpServlet{
private ToDoRepository toDoRepository = new InMemoryToDoRepository();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String servletPath = req.getServletPath();
String view = processRequest(servletPath,req);
RequestDispatcher dispatcher = req.getRequestDispatcher(view);
dispatcher.forward(req,resp);
System.out.println("hello");
}
private String processRequest(String servletPath,HttpServletRequest request){
if(servletPath.equals("/all")){
return "/jsp/todo-list.jsp";
}else {
return "not-found.jsp";
}
}
}
以上便是项目源码