C层实现1——UserController

创建Service

package com.foot.mvcpro.controller;

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 class UserController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("这里是Post请求的处理方法!");
        System.out.println(req.getServletPath());
        String mn = req.getServletPath();
        mn = mn.substring(1);
        mn = mn.substring(0, mn.length()-4);
        System.out.println(mn);
        //利用反射
        try {
            Method method = this.getClass().getDeclaredMethod(mn, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

注意点

1,首先我们需要将请求发往这里的请求统一命名为*.udo,这样方便管理。
2,利用反射机制,可以将所有的请求进行统一的处理。

web.xml配置该servlet


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" 
    id="WebApp_ID" version="3.1" >

    <servlet>
        <servlet-name>UserControllerservlet-name>
        <servlet-class>com.foot.mvcpro.controller.UserControllerservlet-class>
    servlet>

    
    <servlet-mapping>
        <servlet-name>UserControllerservlet-name>
        <url-pattern>*.udourl-pattern>
    servlet-mapping>

web-app>

udo

*.udo 使用udo将所有的以udo结尾的请求发送到该servlet。

学习路径 ##

腾讯课堂 钟洪发 Java技术之Javaaweb入门。

你可能感兴趣的:(C层实现1——UserController)