我们先和jsp九大内置对象做一下比较
jsp九大内置对象 servlet
pageContext null
request HttpServletRequest
session HttpServlet(通过HttpServletRequest.getSession())
application ServletContext(ServletContext servletContext=req.getServletContext())
resquest HttpServletResponse
out PrintWriter(resp.getWriter())
page this
config ServletContext(获取Servlet初始化参数的值)
exception exception
servlet接口及简单的用法
WebContent——》login.jsp
<a href="login.do">登录</a>
java Resources——》servlet——》loginServlet.java
public void LoginSerclet implements Servlet{
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
System.out.println("业务逻辑。。。。。");
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
web.xml配置
<!-- 配置 -->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginServlet</servlet-class>
</servlet>
<!--映射 -->
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/log.do</url-pattern>
</servlet-mapping>
GenerIcServlet抽象类 及用法
LoginGenericServlet.java
public class LoginGenericServlet extends GenericServlet{
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// TODO Auto-generated method stub
//TODO 解决乱码问题 返回的事get还是post
req.setCharacterEncoding("UTF-8");
//TODO 强转
HttpServletRequest httpServletRequest=(HttpServletRequest) req;
//TODO 获取请求方式
String type=httpServletRequest.getMethod();
System.out.println("请求方式"+type);
String uname=req.getParameter("uname");
System.out.println("业务逻辑页面。。。。。LoginGenericServlet......."+uname);
}
}
web.xml配置
<!-- 配置 -->
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlet.LoginGenericServlet</servlet-class>
</servlet>
<!--映射 -->
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/log.do</url-pattern>
</servlet-mapping>
HttpServlet是GenericServlet的子类
public class LoginHttpServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
System.out.println("get");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
System.out.println("post");
}
}