-
Notifications
You must be signed in to change notification settings - Fork 1
/
ServletGenerator.java
77 lines (67 loc) · 2.72 KB
/
ServletGenerator.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package lib;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class ServletGenerator {
private String result = "";
private static String dependency = "C:\\Users\\王星校\\IdeaProjects\\AtomCat\\lib\\javax.servlet.jar";
private static String docRoot = "C:\\Users\\王星校\\Desktop\\Test\\";
public String generate(String className,String importPart,String declarationPart,String initPart,String doGetPart,String doPostPart,String destoryPart){
result += importPart +
"import java.io.*;\n" +
"import javax.servlet.*;\n" +
"import javax.servlet.http.*;\n\n"+
"public class "+ className +" extends HttpServlet {\n\n";
result += declarationPart+"\n";
result += ("public void init() throws ServletException" +
"{\n"+
initPart+
"}\n\n");
result += ("public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n"+
"PrintWriter out = response.getWriter();\n"+
"HttpSession session = request.getSession();\n"+
doGetPart+
"}\n\n"
);
result += ("public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n"+
"PrintWriter out = response.getWriter();\n"+
"HttpSession session = request.getSession();\n"+
doPostPart+
"}\n\n"
);
result += ("public void destroy() {\n"+
destoryPart+
"}\n");
result += "}";
File f = createJavaFile(className,result);
excuteCompile("javac -cp "+ dependency + " " + f.getPath());
return result;
}
public File createJavaFile(String className,String result) {
String dir = docRoot;
String fileName= dir + className + ".java";
File file = new File(fileName);
if(!file.exists()) {
try {
file.createNewFile();
PrintStream ps = new PrintStream(new FileOutputStream(file));
ps.println(result);
CodePretty.pretty(file,file);
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
public static void excuteCompile(String cmd) {
System.out.println("cmd command: "+cmd);
try {
Runtime.getRuntime().exec(cmd).waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}