文章目录
- servlet
- servlet介绍
- servlet的生命周期
- MVC模式
servlet
servlet介绍
servlet是一个小程序,可以直接部署在服务器上直接运行,servlet最底层是一个接口,是sun公司提供的一套规范。当前的HttpServlet的直接父类是GenericServlet,GenericServlet是servlet接口的实现类。HttpServlet类提供了一些抽象的方法,用于加载当前小程序
servlet的生命周期
init()方法 第一次访问这个控制器的时候 初始化方法
service()用于分发请求的方法 比如请求类型的不同,执行不同的操作
doGet()处理get请求
doPost()处理post请求
destory()当服务器关闭销毁当前的小程序
第一次访问的时候先执行初始化init()方法
执行service()方法
根据不同的请求执行doGet()或者doPost()方法
关闭服务器执行destory()方法
- 新建一个LoginServlet.java文件
package com.javaweb.Servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "LoginServlet", value = "/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("servlet初始化");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("开始处理请求");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("开始处理get请求");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("开始处理post请求");
}
@Override
public void destroy() {
System.out.println("servlet销毁");
}
}
启动tomcat服务器,访问http://localhost:8080/项目名/LoginServlet,看控制台输出的内容。
package com.javaweb.Servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init()方法控制器初始化");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("service()方法开始处理请求");
super.service(req, res);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet()方法处理get请求");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost()方法处理post请求");
}
@Override
public void destroy() {
System.out.println("destroy()方法控制器销毁");
}
}
用IDEA新建servlet的时候会默认使用注解的方式。
在之前没有注解方式是怎样运行的呢?
package com.javaweb.Servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
//@WebServlet(name = "TestOldServlet", value = "/TestOldServlet")
public class TestOldServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init()方法控制器初始化");
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
System.out.println("service()方法开始处理请求");
super.service(req, res);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet()方法处理get请求");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost()方法处理post请求");
}
@Override
public void destroy() {
System.out.println("destroy()方法控制器销毁");
}
}
在没有使用注解的方式配置servlet控制器访问路径时,使用的是配置文件的方式,在项目的WEB-INF文件夹下有一个web.xml文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>oldServlet</servlet-name>
<servlet-class>com.javaweb.Servlet.TestOldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>oldServlet</servlet-name>
<url-pattern>/ordServlet</url-pattern>
</servlet-mapping>
</web-app>
重启tomcat服务器,访问http://localhost:8080/day01_war_exploded/oldServlet
- JDBC+JSP+Servlet实现用户的登录操作
用户输入用户名和密码登录的操作其实就是在mysql数据库中的查询操作,首先在mysql中创建一个表:
show databases;
use demo1125;
show tables;
create table test01(
pid int auto_increment not null primary key ,
pname varchar(30),
pwd varchar(30)
);
编写一个StuLoginServlet:
package com.javaweb.Servlet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;
@WebServlet(name = "StuLoginServlet", value = "/StuLoginServlet")
public class StuLoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//一次完整的请求包括请求和响应
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
System.out.println(name);
System.out.println(pwd);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo1125", "root", "root");
String sql = "select * from test01 where pname=? and pwd=?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, pwd);
ResultSet rs = ps.executeQuery();
boolean flag = false;
while (rs.next()) {
flag = true;
}
if (flag) {
System.out.println("登录成功");
} else {
System.out.println("登录失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
编写一个JSP页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
//先定义一个用于获取本项目根路径的一个地址
String path = request.getContextPath();
out.print(path);
%>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="<%=path%>/StuLoginServlet" method="post">
用户名:<input type="text" name="name">
密码:<input type="password" name="pwd">
<input type="submit" value="登录">
</form>
</body>
</html>
重启Tomcat服务器,在浏览器中尝试登录数据库中存在的用户。
MVC模式
M是model模型,V是view视图,controller控制器 servlet
model模型 entity pojo 实体类(这一层编写的是与数据库的表意义对应的java类)
dao层 database access object dao层是负责数据库增删改查的接口
service层 是真正的业务逻辑层 调用dao层,来具体使用哪些方法
view视图 JSP 显示数据用的视图 显示给用户看的
之前编写的用户登录页面的代码在StuLoginServlet中把链接数据库的代码部分抽取出来,单独放到一个类中:
package com.javaweb.entity;
public class Person {
private int pid;
private String pname;
private String pwd;
@Override
public String toString() {
return "Person{" +
"pid=" + pid +
", pname='" + pname + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
public Person() {
}
public Person(int pid, String pname, String pwd) {
this.pid = pid;
this.pname = pname;
this.pwd = pwd;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
}
package com.javaweb.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnUtil {
public static Connection getConn() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/demo1125", "root", "root");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
}
package com.javaweb.util;
public class BaseDao {
}
编写Person的Dao层
package com.javaweb.Dao;
public interface PersonDao {
//这里写入的全是抽象方法
public boolean login();
}
package com.javaweb.DaoImpl;
import com.javaweb.Dao.PersonDao;
public class PersonDaoImpl implements PersonDao {
@Override
public boolean login() {
return false;
}
}
package com.javaweb.Service;
public interface PersonService {
public boolean login();
}
package com.javaweb.ServiceImpl;
import com.javaweb.Dao.PersonDao;
import com.javaweb.DaoImpl.PersonDaoImpl;
import com.javaweb.Service.PersonService;
public class PersonServiceImpl implements PersonService {
private PersonDao pd = new PersonDaoImpl();
@Override
public boolean login() {
return pd.login();
}
}
package com.javaweb.Dao;
public interface PersonDao {
//这里写入的全是抽象方法
public boolean login();
}