Servlet

Servlet

什么是MVC?

​ 所谓的MVC其实就是一种设计模式,一种思想。就是让程序能够分层架构,降低耦合。让展示UI的视图部分和负责逻辑的部分,包括操作数据的部分做一个解耦,独立到不同的模块中。从而大大提高程序的可维护性、扩展性、和代码可读性。

MVC在JavaWeb开发中的应用

  • JSP (View视图层)
  • Servlet (Controller 控制层)
  • JavaBean (Model层 Dao、Bean、Service, 负责后台逻辑、运算、存储)
servlet快速入门

1.什么是Servlet
Servlet 运行在服务端的Java小程序,是sun公司提供一套规范(接口),用来处理客户端请求、响应给浏览器的动态资源。但servlet的实质就是java代码,通过java的API 动态的向客户端输出内容
servlet规范:包含三个技术点
1)servlet技术
2)filter技术—过滤器
3)listener技术—监听器
实现步骤:
1)创建类实现Servlet接口
2)覆盖尚未实现的方法—service方法
3)在web.xml进行servlet的配置

但在实际开发中,我们不会直接去实现Servlet接口,因为那样需要覆盖的方法太多, 我们一般创建类继承HttpServlet(推荐)
实现步骤:
1)创建类继承HttpServlet类
2)覆盖doGet和doPost
3)在web.xml中进行servlet的配置

Servlet的API(生命周期)
  • 生命周期

从创建到销毁的一段时间

  • 生命周期方法

从创建到销毁,所调用的那些方法。

(1)Servlet接口中的方法

1)init(ServletConfig config)
何时执行:servlet对象创建的时候执行
一个servlet只会初始化一次, init方法只会执行一次
默认情况下是 : 初次访问该servlet,才会创建实例,调用init方法。
ServletConfig : 代表的是该servlet对象的配置信息

2)service(ServletRequest request,ServletResponse response)
何时执行:每次请求都会执行
ServletRequest :代表请求 认为ServletRequest 内部封装的是 http请求的信息
ServletResponse :代表响应 认为要封装的是响应的信息

3)destroy()
何时执行:servlet销毁的时候执行

触发时机:

  1. 该项目从tomcat的里面移除。
  2. 正常关闭tomcat就会执行 shutdown.bat
(2)HttpServlet类的方法

1)init()
2)doGet(HttpServletRequest request,HttpServletResponse response)
3)doPost(HttpServletRequest request,HttpServletResponse response)
4)destroy()
在这里插入图片描述

web.xml中的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>web01</display-name>
  <!-- Servlet全局初始化参数 在所有的servlet中使用ServletContext可以获取 -->
  <context-param>
    <param-name>driver</param-name>
    <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
   <!-- servlet配置1 -->
  <servlet>
    <!-- servlet名称 -->
    <servlet-name>abc</servlet-name>
    <!-- servlet全路径 -->
    <servlet-class>com.itheima.servlet.QuickStratServlet</servlet-class>
    <!-- 配置当前servlet初始化参数  只能在该servlet中使用ServletConfig获取-->
    <init-param>
      <param-name>url</param-name>
      <param-value>jdbc:mysql:///mydb</param-value>
    </init-param>
    <load-on-startup>3</load-on-startup>
  </servlet>
  <!-- servlet配置1  镜像 -->
  <servlet-mapping>
    <!-- servlet名称  跟上面保存一致 -->
    <servlet-name>abc</servlet-name>
    <!-- servlet访问路径 -->
    <url-pattern>/quickStratServlet</url-pattern>
  </servlet-mapping>
  <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>
</web-app>
QuickStratServlet代码实现
package com.itheima.servlet;

import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class QuickStratServlet implements Servlet{

	@Override
	public void destroy() {
		System.out.println("destroy running....");
		
	}

	@Override
	public ServletConfig getServletConfig() {
		
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		// 1、获得servlet的name----<servlet-name>abc</servlet-name>
		String servletName = config.getServletName();
		System.out.println(servletName);// abc
		// 2、获得该servlet的初始化的参数
		String initParameter = config.getInitParameter("url");
		System.out.println(initParameter);
		// 3、获得Servletcontext对象
		ServletContext servletContext = config.getServletContext();
		System.out.println("init running....");

	}

	@Override
	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
		System.out.println("QuickStratServlet running....");
		res.getWriter().write("QuickStratServlet running....");
		
	}
}

启动tomcat在控制台中可以看到
在这里插入图片描述
在浏览器中地址栏中输入
http://localhost:8080/web01/quickStratServlet地址
可以看到在这里插入图片描述
在控制台也可以看到
在这里插入图片描述
关闭服务器tomcat时可以看到
在这里插入图片描述
所以servlet的生命周期就是这样

web.xml中的配置
<servlet>
    <servlet-name>QuickStartServlet2</servlet-name>
    <servlet-class>com.itheima.servlet.QuickStartServlet2</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>QuickStartServlet2</servlet-name>
    <url-pattern>/quickStartServlet2</url-pattern>
  </servlet-mapping>
QuickStartServlet2
package com.itheima.servlet;

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 QuickStartServlet2 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.getWriter().write("hello servlet...");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

在浏览器中访问http://localhost:8080/web01/quickStartServlet2就可以看到以下的效果图
在这里插入图片描述
两种不同的servlet入门到此结束

ServletContext对象

1.什么是ServletContext对象
ServletContext代表是一个web应用的环境(上下文)对象,ServletContext对象 内部封装是该web应用的信息,ServletContext对象一个web应用只有一个
ServletContext对象的生命周期?
创建:该web应用被加载(服务器启动或发布web应用(前提,服务器启动状 态))
销毁:web应用被卸载(服务器关闭,移除该web应用)

2.怎样获得ServletContext对象
1)ServletContext servletContext = config.getServletContext();
2)ServletContext servletContext = this.getServletContext();(重点)
3.ServletContext的作用
(1)获得web应用全局的初始化参数
web.xml中配置初始化参数

  <context-param>
    <param-name>driver</param-name>
    <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>

通过context对象获得参数
xml中的servlet配置

<servlet>
    <description></description>
    <display-name>ContextServlet</display-name>
    <servlet-name>ContextServlet</servlet-name>
    <servlet-class>com.itheima.context.ContextServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ContextServlet</servlet-name>
    <url-pattern>/context</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>ContextServlet2</display-name>
    <servlet-name>ContextServlet2</servlet-name>
    <servlet-class>com.itheima.context.ContextServlet2</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ContextServlet2</servlet-name>
    <url-pattern>/context2</url-pattern>
  </servlet-mapping>
package com.itheima.context;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ContextServlet extends HttpServlet{
	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		//获取ServletContext对象
		ServletContext context = getServletContext();
		//1.获得初始化参数
		String initParameter = context.getInitParameter("driver");
		System.out.println(initParameter);
		//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);
		//3、域对象---向servletContext中存数据
		context.setAttribute("name", "zhangsan");
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

在浏览器地址栏中输入http://localhost:8080/web01/context
控制台中的显示
在这里插入图片描述

package com.itheima.context;

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 ContextServlet2 extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//域对象---从servletContext中取数据
		String attribute = (String) this.getServletContext().getAttribute("name");
		System.out.println(attribute);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}

在浏览器中输入http://localhost:8080/web01/context2见上图获取到域中的数据
(2)获得web应用中任何资源的绝对路径(重要 重要 重要)
方法:String path = context.getRealPath(相对于该web应用的相对地址);

(3)ServletContext是一个域对象(重要 重要 重要)
什么是域对象?什么是域?
存储数据的区域就是域对象

ServletContext域对象的作用范围:整个web应(所有的web资源都可以随意向 servletcontext域中存取数据,数据可以共享)

域对象的通用的方法:
setAtrribute(String name,Object obj);
getAttribute(String name);
removeAttribute(String name);

实例做一个登录功能
第一步:导包

在这里插入图片描述
右键bulid path–>小奶瓶

做一个c3p0连接池utils
package com.itheima.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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<>();
	//直接获取一个连接池
	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 closePreparedStatement(PreparedStatement st) throws SQLException {
		if (st != null) {
			st.close();
		}
	}
	public static void closeResultSet(ResultSet rs) throws SQLException {
		if (rs != null) {
			rs.close();
		}
	}

}
在src下创建c3p0-config.xml

这一步最重要的是数据库中一定要有你要连接的数据库在该数据库中创建所需要的表中的字段一定要与domain中的属性一样

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb</property>
	</default-config> 
</c3p0-config> 

domian中的实体类

package com.itheima.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 + "]";
	}
	
}
LoginServlet
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 {
		//在servletContext域中存入一个数据count
		int count = 0;
		this.getServletContext().setAttribute("count", count);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//username=zhangsan && password=123
		//1.获取用户名和密码
				String username = req.getParameter("username");
				System.out.println(username);
				String password = req.getParameter("password");
				System.out.println(password);
				//从数据库中验证该用户名和密码是否正确
				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();
				}
				if(user!=null) {
					//从servletcontext中取出count进行++运算
					ServletContext context = getServletContext();
					Integer count =(Integer) context.getAttribute("count");
					count++;
					//用户登录成功
					resp.getWriter().write(user.toString()+"---you are success login person:"+count);
					context.setAttribute("count", count);
				}else {
					//用户登录失败
					resp.getWriter().write("sorry your username or password is wrong");
				}
	}
}

web.xml中的配置

<servlet>
    <description></description>
    <display-name>LoginServlet</display-name>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.itheima.login.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>

login.html中的配置

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>	
	<form action="/web01/login" method="post">
		用户名:<input type="text" name="username"><br/>
		密码:<input type="password" name="password"><br/>
		<input type="submit" value="登录"><br/>
	</form>
</body>
</html>

浏览器中输入http://localhost:8080/web01/login.html
在这里插入图片描述
输入数据库中存储的zhangsan 密码123
在这里插入代码片
点击登录就可以得到如图所示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值