開發環境為
- spring-boot:2.6.5.RELEASE
- tomcat-embed:9.0.60
HelloServlet 繼承原生的 javax.servlet.http.HttpServlet,並依據要支援的行為來覆寫方法,這段並沒有任何與 spring 相關的程式。
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String name = req.getParameter("name") == null ?
"Anonymous" : req.getParameter("name");
resp.setStatus(HttpServletResponse.SC_OK);
resp.getWriter().write("Hello, " + name);
resp.getWriter().flush();
resp.getWriter().close();
}
}
新增 ServletConfiguration,利用 @Configuration 及 @Bean 生成 HelloServlet ,同時設定好 url mapping。@Configuration
public class ServletConfiguration {
@Bean
public ServletRegistrationBean<HelloServlet> helloServlet() {
ServletRegistrationBean<HelloServlet> bean =
new ServletRegistrationBean(new HelloServlet(), "/servlet/hello");
bean.setLoadOnStartup(1);
return bean;
}
}
如果要讓 servlet 回傳 jsp 網頁,WelcomeServlet 一樣繼承 HttpServlet,在覆寫方法中使用 getRequestDispatcher 方法來設定要導向的 jsp 頁面,同時必須新增對應路徑下的 jsp 檔案,路徑為 src/main/webapp/welcome.jsp。public class WelcomeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name") == null ?
"Anonymous" : req.getParameter("name");
req.setAttribute("name", name);
req.getRequestDispatcher("/welcome.jsp").forward(req, resp);
}
}
簡單的 welcome.jsp 範例。<html>
<head>
<title>Welcome</title>
</head>
<body>
Welcome, ${name}
</body>
</html>
當然該 WelcomeServlet 也必須在 ServletConfiguration 註冊為 bean。@Configuration
public class ServletConfiguration {
@Bean
public ServletRegistrationBean<WelcomeServlet> welcomeServlet() {
ServletRegistrationBean<WelcomeServlet> bean =
new ServletRegistrationBean<>(new WelcomeServlet(), "/servlet/welcome");
bean.setLoadOnStartup(1);
return bean;
}
...
}
啟動應用程式後,就可以存取 url 為 /servlet/hello 及 /servlet/welcome 來檢視結果。如果在 url 後攜帶 name 參數,像是 127.0.0.1:8080/servlet/hello?name=Tom,內容就可以顯示為 Hello, Tom。 程式碼:https://github.com/cookieandcoke/spring-boot-guide/tree/native-servlet-jsp
沒有留言:
張貼留言