Java Web----baseservlet

Source: Internet
Author: User

1 Effects of Baseservlet

Before we start the customer management system, we first write a tool class: Baseservlet.

We know that writing a project can have more than n Servlets, and generally a servlet has only one method (Doget or Dopost), and if the project is larger, the number of servlets is staggering.

To avoid the "bloat" of the servlet, we write a baseservlet. Its role is to allow a servlet to handle a variety of different requests. Different requests invoke different methods of the servlet. After we have written the Baseservlet, let the other servlets inherit Baseservlet, for example customerservlet inherit Baseservlet, then provide add (), update () in Customerservlet, Delete () methods, each of which corresponds to a different request.



2 Baseservlet Analysis

We know that the method of processing the request in the servlet is the service () method, which means that we need to get the service () method to invoke the other method. For example, call Add (), mod (), Del (), All (), and so on! Which method is called to specify the method name in the request! The service () method then invokes the specified method through the method name.

Whether you click the hyperlink or submit the form, the request must have the method parameter, which is the name of the approach to be requested, so that the Baseservlet service () can invoke the target method through the method name. For example, a link is as follows:

<a href= "/xxx/customerservlet?method=add" > Add Customer </a>


3 Code Examples

<?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-c Lass>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 Servletexception, IOException {/* * 1. Gets the parameter that identifies the method that the user wants to request * 2. Then determine if which method, which one we call, is the */string methodName = Req.getparame ter ("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 invoke! ");} /* Get the method name, can I invoke the method by reflection? * 1. Get the method name, and then get the object of method class by means name! * * need to get class, then call it method to query!  Get method * * We want to query the current class of methods, so we need to get the current class */class C = This.getclass ();//Get the class object of the current classes method = Null;try {method = C.getmethod (MethodName, Httpservletrequest.class, Httpservletresponse.class);} catch (Exception e) {throw new RuntimeException ("The method you want to invoke:" + MethodName + "(Httpservletrequest,httpservletresponse), it does not exist!" ");} /* * Call method */try {String result = (string) Method.invoke (this, req, resp);/* Gets the string returned after the request processing method executes, which represents the path of forwarding or redirection! * Help it to complete forwarding or redirection! *//* * If the user returns a string of NULL, or "", then we do nothing! */if (Result = = NULL | | Result.trim (). IsEmpty ()) {return;} /* * To see if the returned string contains a colon, if not, to forward * if there is, use a colon to split the string, get the prefix and suffix! * Where the prefix is F, forwarding, if R is the redirect, the suffix is the path to be forwarded or redirected! */if (Result.contains (":")) {//using a colon to split the string, get the prefix and suffix int index = result.indexof (":");//Gets the position of the colon string s = result.substring (0 , index);//intercept the prefix, which indicates the operation of the string path = Result.substring (index+1);//intercept the suffix, indicating the path if (S.equalsignorecase ("R")) {//If the prefix is R, So redirect! Resp.sendredirect (Req.getcontextpath () + path);} else if (S.equalsignorecase ("F")) {Req.getrequestdispatcher (path). Forward (req, resp);} else {throw new RuntimeException ("You specified the action:" + S + ", the current version is not supported!) ");}} else {//no colon, default is forward! Req.getrequestdispatcher (Result). Forward (req, resp);}} catch (Exception e) {System.out.println ("You call the method:" + MethodName + ", it throws an exception inside!) "); 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 handling methods are given here * Request processing method: Except for the name, the service method is the same! * @author CXF * */public class Aservlet extends Baseservlet {public void AddUser (HttpServletRequest request, Httpservletre Sponse 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";}}



Java Web----baseservlet

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.