关于如何设置IDEA中的servlet的模板
-
点击左上角的File: Setting --> Editor --> File and Code Templates --> Other --> web -->Servlet Annotated Class.java
-
进行如图中的设置
由于我已经设置了java文件的作者信息相关格式,所以不需要在这里面再加入文件头信息
模板代码如下:
#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end
#parse("File Header.java")
@javax.servlet.annotation.WebServlet(name = "${Entity_Name}", urlPatterns="/${Entity_Name}")
public class ${Class_Name} extends javax.servlet.http.HttpServlet {
@Override
protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
// 处理post请求乱码问题
request.setCharacterEncoding("utf-8");
// 处理响应乱码问题:字节流需getBytes("UTF-8")
response.setContentType("text/html;charset=utf-8");
}
@Override
protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
doPost(request,response);
}
}
-
测试的效果如下:新建servlet时,选择 Create New Servlet
这样生成的一个servlet的代码模板如下:
package com.luwanglin.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * @author luwanglin * @email 1769862620@qq.com * @Date 2020/9/1 21:51 * @Version 1.0 */ @WebServlet(name = "HelloServlet", urlPatterns = "/HelloServlet") public class HelloServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 处理post请求乱码问题 request.setCharacterEncoding("utf-8"); // 处理响应乱码问题:字节流需getBytes("UTF-8") response.setContentType("text/html;charset=utf-8"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }