JavaWeb规范与初识Servlet

1 javaweb的十三种技术规范

ee开发过程中:java大师总结好的13种模板代码 来解决ee开发种常见的13种问题
1:jdbc:java data connection java连接数据库
2:jndi:Java Naming and Directory Interface,Java命名和目录接口
3: EJB:Enterprise Java Beans,企业级Java Beans、EJB是实现分布式业务逻辑的Java组件。
4: RMI:Remote Method Invocation,远程方法调用
5:IDL:Java Interface Definiyion LanguageJava接口定义语言/公用对象请求代理程序体系结构
6:JSP:Java Server Pages java服务器端页面
7:servlet:java服务器端应用程序
8:XML:Extensible Markup Language,可扩展标记语言
9:JMS:Java Message Service,Java消息服务
10:JTA:Java Transaction API,Java事务API
11:JTS:Java Transaction Service,Java事务服务
12:JavaMail:邮件发送
13:JAF:  JavaBeans Activation Framework javabean的数据处理框架

2 servlet

概念

服务器端的小程序 用于接受客户端请求、处理数据、给予响应的java模板类
动态资源:需要web应用服务器把动态资源解析后 得到一个静态资源才能响应给客户端

创建

方式1:实现接口:javax.servlet.Servlet

package com.zhiyou100.servlet_01;

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 Demo01Create implements 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
		
	}

	@Override//服务
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		//接受请求
		//处理数据
		//给与响应
		System.out.println("Demo01Create执行了");
		arg1.setCharacterEncoding("utf-8");
		arg1.setContentType("text/html;charset=utf-8");
		arg1.getWriter().print("响应成功!");
		
	}
}
  • 在核心配置文件web.xml中配置此servlet的url
<!--每一个servlet对应一个servlet标签和servlet-mapping标签-->
<!--  com.zhiyou100.servlet_01-->
  <servlet>
      <servlet-name>s01</servlet-name><!--值随意:唯一即可::servlet和servlet-mapping的对应关系-->
      <servlet-class>com.zhiyou100.servlet_01.Demo01Create</servlet-class><!--servlet类全称-->
  </servlet>
  <servlet-mapping>
      <servlet-name>s01</servlet-name><!--值随意:唯一即可::servlet和servlet-mapping的对应关系-->
      <url-pattern>/s01</url-pattern><!--servlet接受的请求的url::必须以/开头  当前项目的根目录-->
  </servlet-mapping>
  • 测试

image

方式2:继承抽象类GenericServlet 实现service方法

package com.zhiyou100.servlet_01;

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Demo02Create  extends GenericServlet{

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		//接受请求
		//处理数据
		//给与响应
		System.out.println("Demo01Create执行了");
		arg1.setCharacterEncoding("utf-8");
		arg1.setContentType("text/html;charset=utf-8");
		arg1.getWriter().print("Demo02Create:响应成功!");
	}

}
  • 配置servlet
<servlet>
    <servlet-name>s02</servlet-name>
    <servlet-class>com.zhiyou100.servlet_01.Demo02Create</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>s02</servlet-name>
    <url-pattern>/s02</url-pattern>
</servlet-mapping>
  • 访问:
添加servlet/修改配置文件 都需要重启tomcat

image

方式3:继承HttpServlet 重写doget/dopost方法

package com.zhiyou100.servlet_01;

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

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		  doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("Demo01Create执行了");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().print("Demo03Create::::::::响应成功!");
	}
}
  • 配置servlet
   <servlet>
      <servlet-name>s03</servlet-name>
      <servlet-class>com.zhiyou100.servlet_01.Demo03Create</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>s03</servlet-name>
      <url-pattern>/s03</url-pattern>
  </servlet-mapping>
  • 测试

image

三者的关系

javax.servlet.GenericServlet是javax.servlet.Servlet接口的实现类
javax.servlet.http.HttpServlet继承了javax.servlet.GenericServlet
javax.servlet.http.HttpServlet:专门针对于http请求的接受和响应  提供了更丰富的关于http协议的方法 

3 servlet生命周期

准备工作

  • 创建类实现接口Servlet
package com.zhiyou100.servlet_01;

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 Demo04LiveCicle  implements Servlet{
	{
		System.out.println("Demo04LiveCicle 构造代码块!");
	}

	@Override
	public void destroy() {
		System.out.println("销毁方法:public void destroy() ");
		
	}

	@Override
	public ServletConfig getServletConfig() {
		//配置信息
		return null;
	}

	@Override
	public String getServletInfo() {
		//servlet版本信息
		return null;
	}

	@Override
	public void init(ServletConfig arg0) throws ServletException {
		System.out.println("初始化方法:public void init(ServletConfig arg0)");
		
	}

	public void service(ServletRequest arg0, ServletResponse resp) throws ServletException, IOException {
		System.out.println("处理请求的方法:public void service(ServletRequest arg0, ServletResponse arg1) ");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().print("<a href='http://localhost:8080/java37_ee_03_servlet/s04'>请求:java37_ee_03_servlet/s04</a>");		
	}

}
  • 配置servlet
  <servlet>
      <servlet-name>s04</servlet-name>
      <servlet-class>com.zhiyou100.servlet_01.Demo04LiveCicle</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>s04</servlet-name>
      <url-pattern>/s04</url-pattern>
  </servlet-mapping>

注意

1 servlet对象:由tomcat创建
2 servlet是单例:tomcat对于同一个servlet只创建一个对象
3 通过servlet的service方法 来接受请求 处理数据 给与响应

生命周期

1:创建Servlet对象(实例化)

默认情况下:tomcat在接收到对servlet的第一次请求时  实例化对应的servlet
通过在web.xml添加配置<load-on-startup>来指定在tomcat启动时 就实例化servlet

2:Servlet对象初始化

tomcat创建完servlet后  就会立刻调用servlet对象的init方法 对servlet对象进行初始化(加载servlet的配置信息)

3:Servlet对象提供服务

tomcat每次接收到对servlet的url的请求 都会调用servlet对象的service方法:来接受请求 处理数据 给予响应  

tomcat每次接受到请求时 会创建一个ServletRequest类型的对象来装与请求相关的所有信息
                    同时创建一个ServletResponse类型的对象来装与响应相关的所有信息
然后调用请求的url对应的servlet对象的service方法 并传递request和response对象,来接受请求 处理数据 给予响应         

4:Servlet对象销毁

tomcat在关闭之前会调用servlet对象的destroy方法:来销毁对象 释放资源

4 使用servlet实现登录

登录页面:html css js
数据库:mysql
业务逻辑:servlet
访问数据库:jdbc

4.1 创建表(数据库设计)

USE db_11;
SHOW TABLES;
CREATE TABLE tab_user(
    tid INT PRIMARY KEY AUTO_INCREMENT,
    tname VARCHAR(11),
    tpwd VARCHAR(11),
    tage INT,
    tsex CHAR(1)
);
INSERT INTO tab_user VALUES(1001,"张三","123",19,"男");
INSERT INTO tab_user VALUES(1002,"李四","123",29,"女");
INSERT INTO tab_user VALUES(1003,"王五","123",39,"男");
INSERT INTO tab_user VALUES(1004,"赵六","123",49,"女");

4.2 创建项目

设置编码集:
mysql--utf-8
        create database db_11 charset="utf8";
html---utf-8
        <meta charset="UTF-8">
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">   
servlet---utf-8
         request对象设置编码集
         response对象设置编码集
             resp.setCharacterEncoding("utf-8");
		     resp.setContentType("text/html;charset=utf-8");
浏览器设置编码集:        

4.3 分包

源码分包
com.zhiyou100.servlet_02.entity  ::: 实体类包:根据表创建的实体类  数据封装
com.zhiyou100.servlet_02.util    ::: 工具类包:关于指定方面的功能集
com.zhiyou100.servlet_02.dao     :::  data access object 对数据库的增删改查方法
com.zhiyou100.servlet_02.servlet ::: servlet::接受请求 处理数据 给予响应
资源分包
html
js
css
image
jsp

4.4 准备工作

  • 导入jar包
c3p0-0.9.2-pre1.jar
commons-beanutils-1.8.0.jar
commons-dbutils-1.2.jar
mchange-commons-0.2.jar
mysql-connector-java-5.1.15-bin.jar
  • 创建c3p0的配置文件:文件位置/src 文件名字c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?> <!-- 声明区:当前xml页面属性 -->
<c3p0-config>
  <default-config>
    <!--mysql数据库连接的各项参数-->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db_11</property>
    <property name="user">root</property>
    <property name="password">root</property>
    <!--配置数据库连接池的初始连接数、最小链接数、获取连接数、最大连接数、最大空闲时间-->
    <property name="initialPoolSize">10</property>
    <property name="minPoolSize">10</property>
    <property name="acquireIncrement">5</property>
    <property name="maxPoolSize">100</property>
    <property name="maxIdleTime">30</property>
  </default-config>
</c3p0-config>
  • 创建实体类:根据表创建:
public class User  implements Serializable {
//    tid INT PRIMARY KEY AUTO_INCREMENT,
//    tname VARCHAR(11),
//    tpwd VARCHAR(11),
//    tage INT,
//    tsex CHAR(1)
	private Integer tid;
	private String tname;
	private String tpwd;
	private String tsex;
	private Integer tage;
    ...
}
  • 创建工具类
package com.zhiyou100.servlet_02.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUtil {
	 //获取池对象
	 private static DataSource ds=new ComboPooledDataSource();
	 //获取连接
	 public static Connection getCon(){
		 try {
			 return ds.getConnection();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	 }
	 //归还连接
	 public static void release(ResultSet set,Statement sta,Connection con){
		 try{
			  if(set!=null){set.close();}
			  if(sta!=null){sta.close();}
			  if(con!=null){con.close();}
		 }catch (Exception e) {
			 throw new RuntimeException(e);
		}
	 }
     public static void main(String[] args) {
		   System.out.println(getCon());
	 }
}

4.6 创建dao

package com.zhiyou100.servlet_02.dao;

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

import com.zhiyou100.servlet_02.entity.User;
import com.zhiyou100.servlet_02.util.JdbcUtil;

public class UserDao {
	//对tab_user标进行增删改查
	public User  getOneByTnameTpwd(String tname,String tpwd){
		User user=null;
		//获取连接
		Connection con=JdbcUtil.getCon();
		//准备sql模板
		String sql="select * from tab_user where tname=? and tpwd=?";
		//获取预处理对象 并关联sql模板
		PreparedStatement sta=null;
		ResultSet set=null;
		try {
			sta=con.prepareStatement(sql);
			//给占位符赋值
			sta.setString(1, tname);
			sta.setString(2, tpwd);
			//执行execute方法 访问数据库 获取结果集
			set=sta.executeQuery();
			//处理结果集
			if(set.next()){
				int tage=set.getInt("tage");
				int tid=set.getInt("tid");
				String tsex=set.getString("tsex");
				user=new User(tid, tname, tpwd, tsex, tage);
			}
		} catch (Exception e) {
			 throw new RuntimeException(e);
		}finally{
			//释放连接
			 JdbcUtil.release(set, sta, con);
		}
		return user;
	}
}

4.7 创建页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>登录页面</title>
<style  type="text/css">
    table{
        border:1px solid blue;
        width:400px;
        margin:200px auto;
        border-collapse: collapse;
    }
    td,th{
        border:1px solid blue;
        padding:10px;
    }
</style>
</head>
<body>
     <form  action="" method="post">
          <table>
              <tr>
                  <th colspan="2">用户登录</th>
              </tr>
              <tr>
                   <th>用户昵称:</th>
                   <td><input type="text" name="tname"/></td>
              </tr>
               <tr>
                   <th>用户密码:</th>
                   <td><input type="password" name="tpwd"/></td>
              </tr>
               <tr>
                   <th colspan="2">
                        <input type="reset"  value="重置"/>
                        &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
                        <input type="submit"  value="登录"/>
                   </th>
              </tr>
          </table>
     </form>
</body>
</html>

4.8 创建servlet

  • 创建类继承httpservlet 重写doget、dopost方法
package com.zhiyou100.servlet_02.servlet;

import java.io.IOException;

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

import com.zhiyou100.servlet_02.dao.UserDao;
import com.zhiyou100.servlet_02.entity.User;

public class UserLoginServlet  extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//接受请求:获取请求参数:通过request对象(对请求信息的封装);parameter
		String tname=req.getParameter("tname");
		String tpwd=req.getParameter("tpwd");
		System.out.println(tname+"::::"+tpwd);
		//处理数据
		UserDao dao=new UserDao();
		User dbUser=dao.getOneByTnameTpwd(tname, tpwd);
		//给与响应
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		if(dbUser!=null){
			resp.getWriter().print("<font  color='blue' size='7'>用户"+dbUser+"登录成功!</font>");
		}else{
			resp.getWriter().print("<font  color='red' size='7'>密码或者账号错误,登录失败!<a href='http://localhost:8080/java37_ee_03_servlet/day02/login.html'>回到登录页面</a></font>");
		}
	}
}
  • 在web.xml中配置servlet的url
    <!--  com.zhiyou100.servlet_02-->
  <servlet>
      <servlet-name>s21</servlet-name>
      <servlet-class>com.zhiyou100.servlet_02.servlet.UserLoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>s21</servlet-name>
      <url-pattern>/login</url-pattern>
  </servlet-mapping>
  • 设置登录表单的action
<form  action="http://localhost:8080/java37_ee_03_servlet/login" method="post">
</form>

4.9 测试

4.10 错误:出现乱码

??????::::123
  • 设置request的编码集 必须在获取请求参数之前
req.setCharacterEncoding("UTF-8");
String tname=req.getParameter("tname");
String tpwd=req.getParameter("tpwd");
posted @ 2021-09-29 16:28  RenVei  阅读(44)  评论(0编辑  收藏  举报