标签:style lang for eth 最新 extend extends text rate
完成功能:登陆后直接进入index.jsp界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body>
<jsp:forward page="/index"></jsp:forward> //在web.xml </body> </html>
package com.louis.web.servlet; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 通用servlet */ public class BaseServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { //1获取子类,创建子类或调用子类的时候,this代表的是子类对象 Class clazz = this.getClass(); System.out.println(this); //2获取请求方法 String m = request.getParameter("method"); //如果方法为空。默认为index。于是每个servlet都要又index() if(m==null) { m = "index"; } System.out.println(m); //3获取方法对象 Method method = clazz.getDeclaredMethod(m, HttpServletRequest.class,HttpServletResponse.class); //4让方法执行,返回值为请求转发的路径 String s = (String)method.invoke(this, request,response); //5判断s是否为空 if(s!=null) { request.getRequestDispatcher(s).forward(request, response); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } } public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { return null; } }
package com.louis.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 和首页相关的servlet */ public class IndexServlet extends BaseServlet { public String index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 去数据库中查询最新商品和热门商品,将他们放入request域中请求转发 return "/jsp/index.jsp"; } }
说明:
1、url中不带方法即可进入首页,所以在BaseServlet中要加一个判断条件,如果没有method方法就调用index函数
2、IndexServlet中的index重写了BaseServlet中的index方法
问题:<jsp:forward>能自动请求么?
打断点看调用的是那个index
标签:style lang for eth 最新 extend extends text rate
原文地址:http://www.cnblogs.com/Michael2397/p/7634567.html