标签:
1、我们来试着向一个servlet提交一个表单,现在webcontent下新建一个login.html页面,其中action对应servelt类名,代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>提交表单</title> </head> <body> <form action="LoginServlet" method="post"> 用户名:<input name="username" type="text"><br> 密码:<input name="password" type="password"><br> <input value="提交" name="submit" type="submit"> </form> </body> </html>
2、新建一个servlet类LoginServlet,代码如下:
package servletdemo; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ @WebServlet("/LoginServlet") public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public LoginServlet() { System.out.print("loginservlet..."); // TODO Auto-generated constructor stub } @Override public void init() throws ServletException { // TODO 自动生成的方法存根 System.out.print("init..."); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.print("doget..."); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.print("dopost..."); } @Override public void destroy() { // TODO 自动生成的方法存根 System.out.print("destory..."); } }
注意:右键新建一个servlet不会在web.xml生成对应的配置标签,是因为servlet类里已经有了@WebServlet注解
3、运行login.html,可以验证servlet的生命周期,效果如下:
4、有时候需要获得web.xml里一些配置信息,例如下面的配置,其中name相当于key,value就是对应的值
<context-param>
<param-name>henry</param-name>
<param-value>123</param-value>
</context-param>
用这行代码就可以获得KEY对应的值:String result=this.getServletContext().getInitParameter("henry");
5、servlet在MVC中相当于controller,所以经常需要做一些页面的跳转,下面来看看页面导航的实现
标签:
原文地址:http://www.cnblogs.com/SamFlynn/p/4478166.html