天天看点

BaseServlet (2) | 学习笔记

开发者学堂课程【Servlet 入门:BaseServlet (2)】学习笔记,与课程紧密联系,让用户快速学习知识。

课程地址:

https://developer.aliyun.com/learning/course/34/detail/760

BaseServlet (2)

内容介绍

一、BaseServlet (2)

一、BaseServlet

package cn.itcast. web. ervlet;

import java.io.IOException;

public class BServlet extends HttpServlet

public void fun1 (HttpservletRequest request, HttpServletResponse response)

throws servletException, IOException {

system. out.println("fun1()...")

request.getRequestDispatcher ("/xxx") . forward (request,

response.sendRedirect (request.getContextPath() + "/xxx.jsp");

public void fun2 (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException (

System. out.println("fun2()...");

public void fun3 (HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException (

System.out.println("fun3()..");

调用

method

表示的方法

try{

string result = (String) method. invoke (this, req, resp);

*获取请求处理方法执行后返回的字符串,它表示转发或者重定向的路径

*帮它完成转发或重定向!

*如果用户返回的是字符串为 null ,或为"”,那么就什么也不做!

.查看返回的字符串中是否包含冒号,如果没有,表示转发

如果有,使用冒号分割字符串,得到前缀和后缀

其中前缀如果是f,表示转发,如果是r表示重定向,后缀就是要转发或重定向的路径了 

if (result.contains(":"))_ {

//使用冒号分割字符串,得到前缀和后缀 

int index = result. indexOf(":");//获取冒号的位置 

string s = result. substring(0, index);//截取出前缀, 表示操作

string path = result. substring (index+1);//截取出后缀,表示路径

if (s.equalsIgnoreCase("x")) {//如果前缀是

r,

那么重定向

!

resp. sendRedirect (req.getContextPath() + path) ;

else if (s. equalsIgnoreCase("ft)) {

req. getRequestDispatcher (path) .forward(req, resp);

throw new Runt imeException("你指定的操作

:

+ s +

”,当前版本还不支持

! p;

else {//没有冒号,默认为转发

!

req.getRequestDispatcher (result) .forward(req, resp);

catch (Exception e) { 

System.out.println("调用的方法

:

+ methodName + ",

它内部抛出了异常! ");

throw new Runt imeException(e) ;

继续阅读