Analysis on the running problem of Servlet
Development stage: Configure the Tomcat plug-in in the idea, and run the idea directly after writing the code (the same process as a normal project).
Deployment stage: The developer makes a war, and then deploys the war to run on Tomcat (if it is in the development stage, it will be a little troublesome, and it needs to be packaged and released every time)
How IDEA configures the Tomcat plugin
Specific steps:
Step 1: Click Add Configuration
Step 2: Click the "+" sign, select Tomcat, and then select local
Step 3: Click configure to select the local Tomcat installation package, where to put your Tomcat, just select it directly
Step 4: Click the Deployment option, select the Servlet project
Step 5: Select the project to be deployed, then click ok
Step 6: Configure the url site (modify the access path), then click ok, the configuration is complete
General preview
After configuring the Tomcat plugin, test it
- Write Servlet backend class
- Configure the web.xml file
Specific implementation steps:
1. Write the Servlet backend class
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
public class MyResponseServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//刷新操作,设置成1s刷新一次
resp.setIntHeader("Refresh",1);
//设置响应类型
resp.setContentType("text/html");
//设置编码格式,如果不设置会出现乱码
resp.setCharacterEncoding("utf-8");
//写入body信息
PrintWriter writer = resp.getWriter();
writer.println(String.format("<h1>当前时间: %s</h1>",new Date()));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2. Configure the web.xml file
<servlet>
<servlet-name>myResponseServlet</servlet-name>
<servlet-class>MyResponseServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myResponseServlet</servlet-name>
<url-pattern>/response</url-pattern>
</servlet-mapping>
3. Run the back-end class code in the idea, click to run, and
a browser page will pop up by itself.
(1) When entering the url we set, a Hello World! page will appear. This page is under WEB-INF The index.jsp, this is in our project. Instead of the one that comes with Tomcat
(2) When we enter our custom url, a new interface will appear, that is, the refresh page we write, which is refreshed every second