Java web ---- BaseServlet, web ---- baseservlet

Source: Internet
Author: User

Java web ---- BaseServlet, web ---- baseservlet

1. Role of BaseServlet

Before starting the customer management system, we should first write a tool class: BaseServlet.

As we know, writing a project may produce N or more Servlets, and generally a Servlet has only one method (doGet or doPost). If the project is larger, then the number of servlets will be amazing.

To avoid Servlet expansion, we write a BaseServlet. It enables a Servlet to process multiple different requests. Different requests call different methods of Servlet. After writing the BaseServlet, let other servlets inherit the BaseServlet. For example, CustomerServlet inherits the BaseServlet, and then provides add (), update (), delete (), and other methods in CustomerServlet, each method corresponds to a different request.



2 BaseServlet Analysis

We know that the method used to process requests in the Servlet is the service () method, which indicates that we need the service () method to call other methods. For example, you can call add (), mod (), del (), all (), and other methods! The name of the method to be called must be provided in the request! Then the service () method calls the specified method through the method name.

Whether you click a hyperlink or submit a form, the request must contain the method parameter. The value of this parameter is the name of the method to be requested. In this way, the BaseServlet service () you can call the target method by using the method name. For example, a link is as follows:

<A href = "/xxx/mermerservlet? Method = add "> add customer </a>


3. code example

<?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">  <display-name></display-name>  <servlet>    <servlet-name>AServlet</servlet-name>    <servlet-class>cn.itcast.web.servlet.AServlet</servlet-class>  </servlet>  <servlet>    <servlet-name>BServlet</servlet-name>    <servlet-class>cn.itcast.web.servlet.BServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>AServlet</servlet-name>    <url-pattern>/AServlet</url-pattern>  </servlet-mapping>  <servlet-mapping>    <servlet-name>BServlet</servlet-name>    <url-pattern>/BServlet</url-pattern>  </servlet-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

Package cn. itcast. web. servlet; import java. io. IOException; import java. lang. reflect. method; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public abstract class BaseServlet extends HttpServlet {public void service (HttpServletRequest req, HttpServletResponse resp) throws ServletExcepti On, IOException {/** 1. obtain parameters to identify the method that the user wants to request * 2. then determine whether or not a method is called. */String methodName = req. getParameter ("method"); if (methodName = null | methodName. trim (). isEmpty () {throw new RuntimeException ("You have not passed the method parameter! Unable to determine the method you want to call! ");}/** Get the method name. Can I call the method through reflection? * 1. Get the Method name. Use the Method name to get the Method class object! ** You need to obtain the Class and then call its method to query it! To obtain Method **, we want to query the Method of the current Class. Therefore, we need to obtain the Class */Class c = this of the current Class. getClass (); // obtain the class Object of the current class Method = null; try {method = c. getMethod (methodName, HttpServletRequest. class, HttpServletResponse. class);} catch (Exception e) {throw new RuntimeException ("the method you want to call:" + methodName + "(HttpServletRequest, HttpServletResponse), it does not exist! ");}/** Call the method Representation */try {String result = (String) method. invoke (this, req, resp);/** get the string returned after the request processing method is executed, which indicates the path of the forwarding or redirection! * Complete forwarding or redirection for it! * // ** If the string returned by the user is null or "", we will not do anything! */If (result = null | result. trim (). isEmpty () {return;}/** check whether the returned string contains a colon. If not, it indicates forwarding. * If yes, use a colon to separate the string and obtain the prefix and suffix! * If the prefix is f, it indicates forwarding. If the prefix is r, it indicates redirection. If the prefix is f, it indicates the path for forwarding or redirection! */If (result. contains (":") {// use a colon to separate the string and get the prefix and suffix int index = result. indexOf (":"); // obtain the position of the colon String s = result. substring (0, index); // extract the prefix, indicating the operation String path = result. substring (index + 1); // extract the suffix, indicating the path if (s. equalsIgnoreCase ("r") {// If the prefix is r, redirect! Resp. sendRedirect (req. getContextPath () + path);} else if (s. equalsIgnoreCase ("f") {req. getRequestDispatcher (path ). forward (req, resp);} else {throw new RuntimeException ("the operation you specified:" + s + ", not supported in the current version! ") ;}} Else {// No colon, forwarding by default! Req. getRequestDispatcher (result ). forward (req, resp) ;}} catch (Exception e) {System. out. println ("method you call:" + methodName + ", it throws an internal exception! "); Throw new RuntimeException (e );}}}

Package cn. itcast. web. servlet; import java. io. IOException; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** multiple request processing methods are provided here * request processing method: all methods except the name are the same as the service method! * @ Author cxf **/public class AServlet extends BaseServlet {public void addUser (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System. out. println ("addUser ()... "); throw new IOException (" test ");} public void editUser (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("editUser ()... ");} public void deleteUser (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("deleteUser ()... ");} public void loadUser (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("loadUser ()... ");} public void findAll (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System. out. println ("findAll ()... ");}}

package cn.itcast.web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class BServlet extends BaseServlet {public String fun1(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("fun1()...");return "/index.jsp";}public String fun2(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("fun2()...");return "r:/index.jsp";}public String fun3(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {System.out.println("fun3()...");return "d:/WEB-INF/files/a.rmvb";}}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.