一、什么是servlet?
servlet是运行在服务器端的java小程序,是sun公司提供的一套规范(接口),主要用来处理客户端请求、响应给浏览器的web动态资源,实质上就是java代码。
二、Servlet快速入门:
1.创建一个类MyFirstServlet实现Servlet接口;
2.重写service方法;
3.配置web.xml文件
在实际开发中,一般情况下是继承HttpServlet类,然后覆盖doGet和doPost方法。
package com.zl.servlet;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class MyFirstServlet implements Servlet {
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("This is first servlet!!!");
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public ServletConfig getServletConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServletInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public void init(ServletConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
web.xml配置如下:
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>com.zl.servlet.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/myFirstServlet</url-pattern>
</servlet-mapping>
三、Servlet的相关方法:
1.getServletName(): 获得servlet的name
2.getInitParameter("参数的name"): 获得servlet的初始化参数
3.getServletContext(): 获得Servletcontext对象
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
//1、获得servlet的name----<servlet-name>abc</servlet-name>
String servletName = config.getServletName();//MyFirstServlet
System.out.println(servletName);
//2、获得该servlet的初始化的参数
String initParameter = config.getInitParameter("url");
System.out.println(initParameter);
//3、获得Servletcontext对象
ServletContext servletContext = config.getServletContext();
System.out.println(servletContext);
System.out.println("init running !!!");
}
四、Servket的生命周期:
1.Servlet接口中的方法:
(1)Init(ServletConfig config):
何时执行:创建Servlet对象时执行
ServletConfig:代表的是该Servlet对象的配置信息
(2)service(ServletRequest resquest , ServletResponse response):
何时执行:每次请求都会执行
ServletRequest: 代表请求,封装的是Http请求的信息
ServletResponse: 代表响应,封装的是服务器响应的信息
(3)destroy():
何时执行:servlet对象销毁的时候执行,也就是说服务器关闭的时候执行
2.HttpServlet类的方法:
(1)、init()
(2)、doGet(HttpServletRequest request,HttpServletResponse response)
(3)、doPost(HttpServletRequest request,HttpServletResponse response)
(4)、destroy()
3.Servlet的生命周期:
(1)Servlet何时创建:
默认第一次访问servlet时创建该对象
(2)Servlet何时销毁:
服务器关闭,servlet就销毁
(3)每次访问必执行的方法:
service(ServletResquest resquest , ServletResponse response)方法
五、Servlet配置:
1.基本配置
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>com.zl.servlet.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/myFirstServlet</url-pattern>
</servlet-mapping>
其中url-pattern的配置方式:
(1)完全匹配 访问的资源与配置的资源完全相同才能访问到:
<url-pattern>/myFirstServlet</url-pattern>
(2)目录匹配 格式:/虚拟的目录../* *代表任意:
<url-pattern>/aaa/bbb/ccc/*</url-pattern>
(3)扩展名匹配 格式:*.扩展名:
<url-pattern>/*.abcd</url-pattern>
2.服务器启动实例化配置:
Servlet何时创建:默认第一次访问时创建
为什么是默认?
当配置servlet时加上<load-on-startup>
时,servlet对象就在服务器启东市创建。
<load-on-startup>3</load-on-startup>
3.缺省的Servlet:
可以将url-pattern配置一个/,代表该servlet是缺省的servlet。
什么是缺省的servlet?
当你访问资源地址所有的servlet都不匹配时 , 缺省的servlet负责处理
4.欢迎页面:
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
六、案例:用户登录
1.首先准备一个login.html
页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/WEB13A/login" method="post">
用户名:<input type="text" name="username"><br />
密码:<input type="password" name="password"><br />
<input type="submit" value="登录"><br />
</form>
</body>
</html>
2.然后编写LoginServlet
类:
package com.zl.login;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.zl.domain.User;
import com.zl.utils.DataSourceUtils;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.从数据库中验证该用户名密码是否正确
QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
String sql="select * from user where username=? and password=?";
User user =null;
try {
user = qr.query(sql, new BeanHandler<User>(User.class), username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//3、根据返回的结果给用户不同显示信息
if(user!=null){
//登录成功
response.getWriter().write(user.toString());
}else{
//登录失败
response.getWriter().write("username or password error!!!");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
3.写一个User
实体类:
package com.zl.domain;
public class User {
private int id;
private String username;
private String password;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
}
}
4.在WebContent下的WEB-INF下的lib文件夹导入三个包:
5.在src根目录下导入c3p0配置文件:
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">a12345</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///web13</property>
</default-config>
</c3p0-config>
其中,web13是数据库名称。
6.编写DataSourceUtils
类:
package com.zl.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DataSourceUtils {
private static DataSource dataSource = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
// 直接可以获取一个连接池
public static DataSource getDataSource() {
return dataSource;
}
// 获取连接对象
public static Connection getConnection() throws SQLException {
Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
// 开启事务
public static void startTransaction() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.setAutoCommit(false);
}
}
// 事务回滚
public static void rollback() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.rollback();
}
}
// 提交并且 关闭资源及从ThreadLocall中释放
public static void commitAndRelease() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.commit(); // 事务提交
con.close();// 关闭资源
tl.remove();// 从线程绑定中移除
}
}
// 关闭资源方法
public static void closeConnection() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.close();
}
}
public static void closeStatement(Statement st) throws SQLException {
if (st != null) {
st.close();
}
}
public static void closeResultSet(ResultSet rs) throws SQLException {
if (rs != null) {
rs.close();
}
}
}
整体目录结构如下:
七、ServletContext:
1.什么是ServletContext?
ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象内部封装是该web应用的信息,一个web应用只有一个ServletContext对象。
2.ServletContext对象的生命周期?
创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状 态))
销毁:web应用被卸载(服务器关闭,移除该web应用)
3.获得web应用的初始化参数:
首先在web.xml配置<context-param>
:
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
通过context获得参数:
//获取servletcontex对象
ServletContext context = this.getServletContext();
//1、获得初始化参数
String initParameter = context.getInitParameter("driver");
System.out.println(initParameter);
4.获得web应用中任何资源的绝对路径:
方法:String path = context.getRealPath(相对于该web应用的相对地址);
a.txt
在WebContent
下,b.txt
在WEB-INF
下,c.txt
在src
下,d.txt
在WEB13A
下。
//2、获得a b c d.txt的绝对路径
//2.1 获得a.txt
String realPath_A = context.getRealPath("a.txt");
System.out.println(realPath_A);
//2.2 获得b.txt
String realPath_B = context.getRealPath("WEB-INF/b.txt");
System.out.println(realPath_B);
//2.3 获得c.txt
String realPath_C = context.getRealPath("WEB-INF/classes/c.txt");
System.out.println(realPath_C);
//2.4 获得d.txt----获取不到
//在读取src(classes) 下的资源是可以同类加载器----专门加载classes 下的文件的
//getResource() 参数是一个相对地址 相对classes
String path = ContextServlet.class.getClassLoader().getResource("c.txt").getPath();
System.out.println(path);
5.ServletContext是一个域对象:
什么是域对象?什么是域?
存储数据的区域就是域对象
ServletContext域对象的作用范围:整个web应用(所有的web资源都可以随意向servletcontext域中存取数据,数据可以共享)
域对象的通用的方法:
setAtrribute(String name,Object obj);
getAttribute(String name);
removeAttribute(String name);
案例:统计登录次数:
package com.itheima.login;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.itheima.domain.User;
import com.itheima.utils.DataSourceUtils;
public class LoginServlet extends HttpServlet {
@Override
public void init() throws ServletException {
//在Seveltcontext域中存一个数据count
int count = 0;
this.getServletContext().setAttribute("count", count);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//username=zhangsan&password=123
//1、获得用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2、从数据库中验证该用户名和密码是否正确
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
User user = null;
try {
user = runner.query(sql, new BeanHandler<User>(User.class), username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//3、根据返回的结果给用户不同显示信息
if(user!=null){
//从servletcontext中取出count进行++运算
ServletContext context = this.getServletContext();
Integer count = (Integer) context.getAttribute("count");
count++;
//用户登录成功
response.getWriter().write(user.toString()+"---you are success login person :"+count);
context.setAttribute("count", count);
}else{
//用户登录失败
response.getWriter().write("sorry your username or password is wrong");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Servlet模板:
package ${enclosing_package};
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ${primary_type_name} extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("hello haohao...");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
网友评论