今天接触了Servlet,Servlet 是一个 Java程序,是在服务器上运行以处理客户端请求并做出响应的程序Servlet是早期最初始的一个版本,慢慢形成JSP.介绍一下Servlet的配置。
案例:web项目WebRoot/WEB-INF/web.xml下
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 注册servlet --> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> <!-- 初始化参数:由当前servlet管理 --> <init-param> <param-name>name</param-name> <param-value>小明</param-value> </init-param> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>query</servlet-name> <servlet-class>servlet.query</servlet-class> </servlet> <servlet-mapping> <servlet-name>query</servlet-name> <url-pattern>/servlet/query</url-pattern> </servlet-mapping> <!-- 映射servlet --> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> <!-- 上下文参数:由web容器管理 --> <context-param> <param-name>name</param-name> <param-value>admin</param-value> </context-param> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
JAVA代码:
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.faces.application.Application; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.corba.se.impl.interceptors.PINoOpHandlerImpl; public class HelloServlet extends HttpServlet { /** * servlet生命周期 * 1实例化servlet(web容器实现) * 使用功能 * 1、初始化工作;此方法只执行一次;在第一次访问sersvlet的时候执行(执行init()方法体现) * 2、真正处理客户端请求(执行service()方法) * 输出响应信息 * 3、关闭web容器;只执行一次;在web容器关闭的售后执行销毁servlet(执行destory()方法) */ /* (non-Javadoc) * 重写父类初始化方法 * @see javax.servlet.GenericServlet#init() */ @Override public void init() throws ServletException { // TODO Auto-generated method stub System.out.println("servlet第一个执行的方法!!!"); //得到servlet初始化 System.out.println("初始化参数:"+this.getServletConfig().getInitParameter("name")); //获取上下文参数 System.out.println("上下文参数:"+this.getServletContext().getInitParameter("name")); } /* (non-Javadoc) * 以GET提交方式提交的请求调用该方法 * 默认不指定提交方式的时候执行该方法 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /* (non-Javadoc) * 以POST提交方式提交的请求调用该方法 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub /** * 处理客户端的请求 */ System.out.println("执行service方法处理请求"); //接收参数 String username = request.getParameter("username"); String password = request.getParameter("password"); if(username.equals("admin") && password.equals("123456")){ //相当于jsp页面的session HttpSession session = request.getSession(); Application app = (Application) getServletContext(); request.setAttribute("username", username); //跳转到成功页面 request.getRequestDispatcher("/success.jsp").forward(request, response); } /** * 响应客户端请求 */ //告诉客户端怎么解释返回的内容 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<HTML>"); out.print("<head><title>HelloServlet</title></head>"); out.print("<body>HelloServlet第一个servlet诞生了!!!</body>"); out.print("</HTML>"); out.close(); } /* (non-Javadoc) * servlet(销毁方法) * @see javax.servlet.GenericServlet#destroy() */ @Override public void destroy() { // TODO Auto-generated method stub System.out.println("销毁servlet!!!"); } }
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class query extends HttpServlet { /** * Constructor of the object. */ public query() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the GET method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out .println("<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
JSP代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>登录</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="HelloServlet" method="post"> username:<input type="text" name="username" /><br/> password:<input type="password" name="password" /><br/> <input type="submit" /> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> ${username } 登录成功<br> </body> </html>