从本章开始,将进入到JavaWeb开发的基础学习当中,前两部分分别为数据库以及前端的学习。
文章目录
前言
一、HTTP
HTTP:超文本传输协议,规定了浏览器和服务器之间数据传输(请求、响应)的规则。
二、Tomcat
三、Servlet
1、快速入门
package youth.web;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
@WebServlet("/demo1")
public class ServletDemo1 implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("Hello Servlet");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
2、执行流程
3、生命周期
原生Servlet
package youth.web;
@WebServlet(urlPatterns = "/demo1", loadOnStartup = 1)
public class ServletDemo1 implements Servlet {
* 初始化方法
* 1. 调用时机:默认情况下,Servlet被第一次访问时,调用
* * loadOnStartup:
* 2. 调用次数:1次
* @param config
* @throws ServletException
@Override
public void init(ServletConfig config) throws ServletException {
System.out.println("init...");
}
* 提供服务
* 1. 调用时机:每一次Servlet被访问时,调用
* 2. 调用次数:多次
*
*
* @param req
* @param res
* @throws ServletException
* @throws IOException
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// 根据请求方式的不同,进行分别的处理
HttpServletRequest request = (HttpServletRequest) req;
// 1. 获取请求方式
String method = request.getMethod();
// 2. 判断
if("GET".equals(method)) {
// get方式的处理逻辑
}else if("POST".equals(method)){
// post方式的处理逻辑
}
}
* 销毁方法
* 1. 调用时机:内存释放或者服务器关闭的时候,Servlet对象会被销毁,调用
* 2. 调用次数:1次
@Override
public void destroy() {
System.out.println("destroy...");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public ServletConfig getServletConfig() {
return null;
}
}
HttpServlet extends GenericServlet,重写了上述Servlet的方法,方便操作,对HttpServlet只需要重写doGet和doPost方法。
package youth.web;
@WebServlet("/demo2")
public class ServletDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("get");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("post");
}
}
4*、HttpServlet与Servlet
- 原生Servlet有init、service、destroy等方法,service中根据request参数执行getMethod方法获取方法名,根据方法名是get或post进行处理。
- HttpServlet继承了原生的Servlet,复写了上述的方法,因此边可以继承HttpServlet,复写其doGet和doPost方法便可以进行处理。
5、Servlet urlPattern配置
四、Request & Response
request和response是被携带于原生Servlet的service方法中的,根据request的方法名,将这两个参数传递给get和post方法中。
1、Request
package youth.web;
@WebServlet("/req1")
public class RequestDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// String getMethod(); 获取请求方式:GET
String method = req.getMethod();
System.out.println(method);
// String getContextPath(); 获取虚拟目录(项目访问路径):/request-demo
String contextPath = req.getContextPath();
System.out.println(contextPath);
// StringBuffer getRequestURL(): 获取URL(统一资源定位符):http://localhost:8080/request-demo/req1
StringBuffer url = req.getRequestURL();
System.out.println(url.toString());
// String getRequestURI(): 获取URI(统一资源标识符): /request-demo/req1
String uri = req.getRequestURI();
System.out.println(uri);
// String getQueryString(): 获取请求参数(GET方式): username=youth
String queryString = req.getQueryString();
System.out.println(queryString);
//--------------------
// 获取请求头:User-agent:浏览器的版本信息
String agent = req.getHeader("user-agent");
System.out.println(agent);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 获取post 请求体:请求参数
// 1. 获取字符输入流
BufferedReader br = req.getReader();
// 2. 读取数据
String line = br.readLine();
System.out.println(line);
}
}
package youth.web;
@WebServlet("/req2")
public class RequestDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// GET请求逻辑
//System.out.println("get...");
// 1.获取所以参数的Map集合
Map<String, String[]> map = req.getParameterMap();
for(String key : map.keySet()){
System.out.print(key+":");
// 获取值
String[] values = map.get(key);
for(String value: values){
System.out.print(value+" ") ;
}
System.out.println();
}
System.out.println("---------------");
// 2.根据key获取参数数组
String[] hobbies = req.getParameterValues("hobby");
for(String hobby : hobbies){
System.out.println(hobby);
}
// 3.根据key获取单个参数值
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username);
System.out.println(password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
解决乱码:POST.getReader() GET.getQueryString
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 解决乱码:POST.getReader()
request.setCharacterEncoding("UTF-8");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取username
String username = request.getParameter("username");
System.out.println("解决乱码前:"+username);
// 2. GET,获取参数的方式:getQueryString
// 乱码原因:Tomcat进行URL解码,默认的字符集ISO-8859-1
// 2.1 先对乱码数据进行编码:转为字符数组
byte[] bytes = username.getBytes(StandardCharsets.ISO_8859_1);
// 2.2 字节数组解码
username = new String(bytes, StandardCharsets.UTF_8);
System.out.println("解决乱码后: "+username);
}
一个Servlet将需要转发的数据存储到request当中(request.setAttribute),然后通过getRequestDispatcher(“URL”).forward(request,response)转发
@WebServlet("/req4")
public class RequestDemo4 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo4...");
// 存储数据
request.setAttribute("msg","hello");
// 请求转发
request.getRequestDispatcher("/req5").forward(request,response);
}
}
另一个Servlet负责接收转发的数据,通过request.getAttribute(“转发数据的键名”)
@WebServlet("/req5")
public class RequestDemo5 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("demo5...");
// 获取数据
Object msg = request.getAttribute("msg");
System.out.println(msg);
}
}
2、Response
@WebServlet("/resp1")
public class ResponseDemo1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("resp1...");
// // 重定向
// // 1. 设置响应状态码 302
// response.setStatus(302);
//
// // 2. 设置响应头 Location
// response.setHeader("Location", "/tomcat-demo/resp2");
// 简化方式完成重定向
response.sendRedirect("/tomcat-demo/resp2");
}
}
// 动态获取虚拟目录
String contextPath = request.getContextPath();
response.sendRedirect(contextPath+"/resp2");
// 简化方式完成重定向
// response.sendRedirect("/tomcat-demo/resp2");
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
// 1.获取字符输出流,不需要关闭
PrintWriter writer = response.getWriter();
// content-type
// response.setHeader("content-type", "text/html");
writer.write("aaa");
writer.write("<h1>aaa</h1>");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.读取文件
FileInputStream fis = new FileInputStream("C://Users//ThinkPad//Pictures//Camera Roll//background.png");
// 2.获取response字节输出流
ServletOutputStream os = response.getOutputStream();
// 3.完成流的拷贝
// byte[] buff = new byte[1024];
// int len = 0;
// while((len = fis.read(buff)) != -1)
// os.write(buff,0, len);
IOUtils.copy(fis, os);
fis.close();
}
3、LoginServlet-demo
- 数据库内创建用户表,并根据用户表的属性在java.pojo中创建User的java类。
- 编写登录(HTML、CSS)界面,其中用户名和密码的表单form的action属性填写LoginServlet的URL(LoginServlet用@注解改写)。
- java.mapper中的UserMapper.class和resources.mapper的UserMapper.xml对应,UserMapper.class写方法名,xml里写具体的SQL语句(也可以用@注解的方式直接写在.class里),mybatis-config.xml配置JDBC的相关参数以及mapper的扫描(参考MyBatis官网)。
- LoginServlet重写doGet和doPost方法,首先通过request.getParameter方法接收用户名和密码,然后调用Mapper查询用户是否存在(1.获取SqlSessionFactory对象,2.获取SqlSession对象,3.获取Mapper对象,4.调用UserMapper的方法,5.释放资源),最后根据查询的结果执行相应的语句。
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--起别名-->
<typeAliases>
<typeAlias alias="User" type="pojo.User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="mapper"/>
</mappers>
</configuration>
LoginServlet
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.用户名和密码的接收
String username = request.getParameter("username");
String password = request.getParameter("password");
// 2.调用MyBatis查询
// 2.1 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.2 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 2.3 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 2.4 调用方法
User user = userMapper.select(username, password);
// 2.5 释放资源
sqlSession.close();
response.setContentType("text/html; charset=utf-8");
PrintWriter writer = response.getWriter();
// 3.判断User是否为null
if(user != null){
// 登陆成功
writer.write("登陆成功");
}
else{
writer.write("登陆失败");
}
}
}
- 编写注册(HTML、CSS)界面,其中用户名和密码的表单form的action属性填写RegisterServlet的URL(RegisterServlet用@注解)。
- java.mapper中的UserMapper.class和resources.mapper的UserMapper.xml对应,UserMapper.class写方法名,.xml里写具体的SQL语句(也可以用@注解的方式直接写在.class里),mybatis-config.xml配置JDBC的相关参数以及mapper的扫描(参考MyBatis官网)。
- RegisterServlet重写doGet和doPost方法,首先通过request.getParameter方法接收用户名和密码,然后调用Mapper查询用户是否存在,最后根据查询的结果判断是否进行用户的注册,并且通过response返回结果给浏览器。
RegisterServlet
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.用户名和密码的接收
String username = request.getParameter("username");
String password = request.getParameter("password");
// 封装用户对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 2.调用Mapper 根据用户名查询用户对象
// 2.1 获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 2.2 获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
// 2.3 获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 2.4 调用方法
User u = userMapper.selectByUsername(username);
response.setContentType("text/html; charset=utf-8");
// 3. 判断用户对象是否为null
if(u == null){
// 用户名不存在,可以添加用户
userMapper.add(user);
// 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
response.getWriter().write("注册成功");
}
else{
// 用户名存在,给出提示信息
response.getWriter().write("用户名已存在");
}
}
}
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
// 静态代码块会随着类的加载而自动执行,且只执行一次
try{
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
// // 2.调用Mapper查询
// // 2.1 获取SqlSessionFactory对象
// String resource = "mybatis-config.xml";
// InputStream inputStream = Resources.getResourceAsStream(resource);
// SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
五、JSP
<%…%>:编写Java代码
<%=…%>:输出内容或值到页面上
<%!..%>:成员变量或成员方法添加到类中
Servlet
EL表达式
brand.id执行的是getId()方法,而不是直接获取属性值。
<%--
Created by IntelliJ IDEA.
User: ThinkPad
Date: 2022/6/26
Time: 12:00
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--jstl引入--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:if test="${key_true == 1}">
<%= true %>
</c:if>
<c:if test="${key_false == 0}">
<%= false %>
</c:if>
<c:forEach items="${brands}" var = "brand" varStatus="status">
<tr align="center">
<td>${status.count}</td>
<td>${status.id}</td>
</tr>
</c:forEach>
<c:forEach begin="0" end="10" step="1" var="i">
<a href="#">${i} </a>
</c:forEach>
</body>
</html>
1、MVC模型
2*、三层架构
三层架构的数据增删改查案例
项目框架
- 创建数据库以及相应的表,并插入数据。
- 创建与表相对应的POJO类(下划线变量名改为驼峰命名)。
package youth.pojo;
/**
* 品牌实体类
*/
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Brand() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
3.编写Mapper三步骤:(1)编写mybatis-config.xml的核心配置文件(负责JDBC的连接),(2)编写java.youth.mapper.BrandMapper接口(负责调用SQL语句),(3)编写resources.youth.mapper.BrandMapper.xml(负责编写SQL语句)。
mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--起别名-->
<typeAliases>
<package name="youth.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="youth.mapper"/>
</mappers>
</configuration>
resources.youth.mapper.BrandMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="youth.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<!-- 这里没有SQL语句,都在接口中用注解方式实现了。-->
</mapper>
java.youth.mapper.BrandMapper
package youth.mapper;
import org.apache.ibatis.annotations.*;
import youth.pojo.Brand;
import java.util.List;
public interface BrandMapper {
@Select("select * from tb_brand;")
@ResultMap("brandResultMap")
List<Brand> selectAll();
@Insert("insert into tb_brand values(#{id}, #{brandName}, #{companyName}, #{ordered}, #{description}, #{status});")
void add(Brand brand);
@Select("select * from tb_brand where id = #{id};")
@ResultMap("brandResultMap")
Brand selectById(int id);
@Update("update tb_brand set brand_name = #{brandName}, company_name = #{companyName}, description = #{description}, status = #{status}, ordered = #{ordered} where id = #{id};")
void update(Brand brand);
@Delete("delete from tb_brand where id = #{id};")
void delete(int id);
}
4.Service层,负责封装逻辑处理,访问数据库层调用mapper的方法处理数据。
package youth.service;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import youth.mapper.BrandMapper;
import youth.pojo.Brand;
import youth.util.SqlSessionFactoryUtils;
import java.util.List;
public class BrandService {
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
List<Brand> brands = mapper.selectAll();
sqlSession.close();
return brands;
}
public Brand selectById(int id){
//调用BrandMapper.selectAll()
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
Brand brand = mapper.selectById(id);
sqlSession.close();
return brand;
}
public void add(Brand brand){
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.add(brand);
// 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
public void update(Brand brand){
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.update(brand);
// 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
public void delete(int id){
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4.调用方法
mapper.delete(id);
// 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}
}
5.Servlet层,封装浏览器传来的数据,转发给Service层进行数据的处理,并负责视图的展示。
package youth.web;
import youth.pojo.Brand;
import youth.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/addServlet")
public class addServlet extends HttpServlet {
private BrandService service = new BrandService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 处理POST请求的乱码问题
request.setCharacterEncoding("utf-8");
// 1. 接收表单提交的数据,封装为一个Brand对象
String brandName = request.getParameter("brandName");
String companyName = request.getParameter("companyName");
String ordered = request.getParameter("ordered");
String description = request.getParameter("description");
String status = request.getParameter("status");
// 封装为一个Brand对象
Brand brand = new Brand();
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setDescription(description);
brand.setOrdered(Integer.parseInt(ordered));
brand.setStatus(Integer.parseInt(status));
// 2.调用service 完成添加
service.add(brand);
// 3.转发到查询所以Servlet
request.getRequestDispatcher("/selectAllServlet").forward(request, response);
}
}
六、Cookie & Session
1、Cookie
发送Cookie
@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 发送Cookie
// 1. 创建Cookie对象
Cookie cookie = new Cookie("username", "zs");
// 2. 发送Cookie, 通过response
response.addCookie(cookie);
}
}
获取Cookie
@WebServlet("/bServlet")
public class bServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取Cookie
// 1. 获取Cookie数组
Cookie[] cookies = request.getCookies();
// 2. 遍历数组
for(Cookie cookie : cookies){
// 3. 获取数据
String name = cookie.getName();
if("username".equals(name)){
String value = cookie.getValue();
System.out.println(name+":"+value);
break;
}
}
}
}
@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 发送Cookie
// 1. 创建Cookie对象
Cookie cookie = new Cookie("username", "zs");
// 设置存活时间
cookie.setMaxAge(60 * 60 * 24 * 7); // 7 天
// 2. 发送Cookie, 通过response
response.addCookie(cookie);
}
}
2、Session
存储数据到Session
@WebServlet("/aSession")
public class aSession extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 存储到Session中
// 1. 获取Session对象
HttpSession session = request.getSession();
// 2. 存储数据
session.setAttribute("username", "zs");
}
}
获取数据从Session
@WebServlet("/bSession")
public class bSession extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取数据,从Session中
// 1. 获取Session对象
HttpSession session = request.getSession();
// 2. 获取数据
Object username = session.getAttribute("username");
System.out.println(username);
}
}
Cookie 和 Session的区别:
- Cookie是服务器在第一次接收到浏览器发来的request请求时,通过response设置响应返回给浏览器一个Cookie。当浏览器再次访问服务器时,将携带服务器设置给浏览器的Cooike一起发送请求给服务器,服务器获取该id(key,value)便可识别出是哪一个浏览器。
- Session是基于Cookie实现的,用来在一次会话的多次请求之间共享数据。即浏览器的多个请求都执行getSession方法来获取当前浏览器(会话)的Session(同一个),第一个请求使用setAttribute方法将value存储到key中,之后的请求可以使用getAttribute方法代入key的值获取相应的value。
3、注册和登录案例
loginServlet
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private UserService service = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 获取复选框数据
String remember = request.getParameter("remember");
// 2. 调用service查询
User user = service.login(username, password);
// 3. 判断
if(user != null){
// 1. 登录成功,跳转到查询所有的BrandServlet
// 判断用户是否勾选记住我
if("1".equals(remember)){
// 勾选了,发送Cookie
// 1.1 创建Cookie对象
Cookie c_username = new Cookie("username", username);
Cookie c_password = new Cookie("password", password);
// 1.2设置Cookie 的存活时间
c_username.setMaxAge(60 * 60 * 24 * 7);
c_password.setMaxAge(60 * 60 * 24 * 7);
// 1.3 发送
response.addCookie(c_username);
response.addCookie(c_password);
}
// 1.4 将登录成功后的User对象,存储到session
HttpSession session = request.getSession();
session.setAttribute("user", user);
String contextPath = request.getContextPath();
response.sendRedirect("/brand-demo/selectAllServlet");
}else{
// 2. 登录失败
// 2.1 存储错误信息到request
request.setAttribute("login_msg","用户名或密码错误");
// 2.2 跳转到login.jsp
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
}
UserService
public class UserService {
// 1.获取工厂
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
public User login(String username, String password){
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取BrandMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 4.调用方法
User user = mapper.select(username, password);
// 释放资源
sqlSession.close();
return user;
}
}
UserMapper
public interface UserMapper {
/**
* 根据用户名和密码查询用户对象
* @param username
* @param password
* @return
*/
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username,@Param("password") String password);
/**
* 根据用户名查询用户对象
* @param username
* @return
*/
@Select("select * from tb_user where username = #{username}")
User selectByUsername(String username);
/**
* 添加用户
* @param user
*/
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv" style="height: 350px">
<form action="/brand-demo/loginServlet" id="form">
<h1 id="loginMsg">LOGIN IN</h1>
<div id="errorMsg">${login_msg}</div>
<p>Username:<input id="username" name="username" value="${cookie.username.value}"type="text"></p>
<p>Password:<input id="password" name="password" value="${cookie.password.value}"type="password"></p>
<p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p>
<div id="subDiv">
<input type="submit" class="button" value="login in">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?</a>
</div>
</form>
</div>
</body>
</html>
registerServlet
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
private UserService service = new UserService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 获取输入的验证码
String checkCode = request.getParameter("checkCode");
// 程序生成的验证码
HttpSession session = request.getSession();
String checkCodeGen = (String) session.getAttribute("checkCodeGen");
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 比对
if(!checkCodeGen.equalsIgnoreCase(checkCode)){
request.setAttribute("register_msg", "验证码错误");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
// 2. 调用service注册
boolean flag = service.register(user);
// 3. 判断注册成功与否
if(flag){
request.setAttribute("register_msg", "注册成功,请登录");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}else{
request.setAttribute("register_msg", "用户名已存在");
request.getRequestDispatcher("/register.jsp").forward(request,response);
}
}
}
checkCodeServlet
@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response) ;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 生成验证码
ServletOutputStream os = response.getOutputStream();
String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
// 存入Session
HttpSession session = request.getSession();
session.setAttribute("checkCodeGen", checkCode);
}
}
registerService
public boolean register(User user) {
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 4.判断用户是否存在
User u = mapper.selectByUsername(user.getUsername());
if (u == null) {
mapper.add(user);
sqlSession.commit();
}
// 释放资源
sqlSession.close();
return u == null;
}
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="/brand-demo/registerServlet" method="get">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" >${register_msg}</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img id="checkCodeImg" src="/brand-demo/checkCodeServlet">
<a href="#" id="changeImg">看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
document.getElementById("changeImg").onclick = function () {
document.getElementById("checkCodeImg").src = "/brand-demo/checkCodeServlet?new Date().getMilliseconds()";
}
</script>
</body>
</html>
验证码库
package youth.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
/**
* 生成验证码工具类
*/
public class CheckCodeUtil {
public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
*
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 使用系统默认字符源生成验证码
*
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
*
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources) {
// 未设定展示源的字码,赋默认值大写字母+数字
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
*
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
*
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
//文件不存在
if (!dir.exists()) {
//创建
dir.mkdirs();
}
try {
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch (IOException e) {
throw e;
}
}
/**
* 输出指定验证码图片流
*
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建颜色集合,使用java.awt包下的类
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
// 设置边框色
g2.setColor(Color.GRAY);
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
// 设置背景色
g2.setColor(c);
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
// 设置线条的颜色
g2.setColor(getRandColor(160, 200));
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
// 噪声率
float yawpRate = 0.05f;
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
// 获取随机颜色
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
// 添加图片扭曲
shear(g2, w, h, c);
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
/**
* 随机颜色
*
* @param fc
* @param bc
* @return
*/
private static Color getRandColor(int fc, int bc) {
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
七、Flitter
@WebFilter("/*")
public class FilterDemo implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//1. 放行前,对 request数据进行处理
System.out.println("1.FilterDemo...");
//放行
chain.doFilter(request,response);
//2. 放行后,对Response 数据进行处理
System.out.println("5.FilterDemo...");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
loginFilter
@WebFilter("/*")
public class loginFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
String[] urls = {"/login.jsp", "/imgs/", "/css/", "loginServlet", "/register.jsp", "/registerServlet", "/checkCodeServlet"};
// 获取当前访问的资源路径
String url = req.getRequestURL().toString();
for(String u : urls){
if(url.contains(u)){
chain.doFilter(request, response);
return;
}
}
req.setAttribute("login_msg", "您尚未登陆");
req.getRequestDispatcher("/login.jsp").forward(request, response);
}
public void destroy() {
}
public void init(FilterConfig config) throws ServletException {
}
}
八、Listener
public class ContextLoadListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// 加载资源
System.out.println("ContextLoaderListener...");
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// 释放资源
}
}
九、Ajax
前端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
// 1. 创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2. 发送请求
xhttp.open("GET", "http://localhost:8080/brand-demo/ajaxServlet");
xhttp.send();
// 3. 获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
alert(this.responseText);
}
};
</script>
</body>
</html>
后端
@WebServlet("/ajaxServlet")
public class ajaxServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1. 响应数据
response.getWriter().write("hello ajax~");
}
}
前端 register.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="#" method="get">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名已存在</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img src="imgs/a.jpg">
<a href="#" id="changeImg">看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
//1. 给用户名输入框绑定 失去焦点事件
document.getElementById("username").onblur = function () {
//2. 发送ajax请求
// 获取用户名的值
var username = this.value;
//2.1. 创建核心对象
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2.2. 发送请求
xhttp.open("GET", "http://localhost:8080/ajax-demo/selectUserServlet?username="+username);
xhttp.send();
//2.3. 获取响应
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//alert(this.responseText);
//判断
if(this.responseText == "true"){
//用户名存在,显示提示信息
document.getElementById("username_err").style.display = '';
}else {
//用户名不存在 ,清楚提示信息
document.getElementById("username_err").style.display = 'none';
}
}
};
}
</script>
</body>
</html>
后端 SelectUserServlet
@WebServlet("/selectUserServlet")
public class SelectUserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 接收用户名
String username = request.getParameter("username");
//2. 调用service查询User对象
boolean flag = true;
//3. 响应标记
response.getWriter().write("" + flag);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
axios的js文件:Axios.js
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
前端,负责发送请求和页面数据,接收后端response的数据。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="js/axios-0.18.0.js"></script>
<script>
//1. get
axios({
method:"get",
url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
//2. post
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:"username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})
</script>
</body>
</html>
后端,负责接收前端发送的数据,设置响应数据。
@WebServlet("/axiosServlet")
public class AxiosServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("get...");
//1. 接收请求参数
String username = request.getParameter("username");
System.out.println(username);
//2. 响应数据
response.getWriter().write("hello Axios~");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("post...");
this.doGet(request, response);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="js/axios-0.18.0.js"></script>
<script>
//1. get
/* axios({
method:"get",
url:"http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})*/
axios.get("http://localhost:8080/ajax-demo/axiosServlet?username=zhangsan").then(function (resp) {
alert(resp.data);
})
//2. post
/*axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:"username=zhangsan"
}).then(function (resp) {
alert(resp.data);
})*/
axios.post("http://localhost:8080/ajax-demo/axiosServlet","username=zhangsan").then(function (resp) {
alert(resp.data);
})
var jsObject = {name:"zhangsan"};
axios({
method:"post",
url:"http://localhost:8080/ajax-demo/axiosServlet",
data:jsObject
}).then(function (resp) {
alert(resp.data);
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
//1. 定义JSON字符串
var jsonStr = '{"name":"zhangsan","age":23,"addr":["北京","上海","西安"]}';
//alert(jsonStr);
//2. 将JSON字符串转为JS对象
let jsObject = JSON.parse(jsonStr);
//alert(jsObject);
let name = jsObject.name;
//alert(name);
//3. JS对象转为JSON字符串
let jsonStr2 = JSON.stringify(jsObject);
alert(jsonStr2)
</script>
</body>
</html>
JsonServlet
package com.itheima.json;
import com.alibaba.fastjson.JSON;
public class FastJsonDemo {
public static void main(String[] args) {
//1. 将Java对象转为JSON字符串
User user = new User();
user.setId(1);
user.setUsername("zhangsan");
user.setPassword("123");
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString);//{"id":1,"password":"123","username":"zhangsan"}
//2. 将JSON字符串转为Java对象
User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class);
System.out.println(u);
}
}
十、Vue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<input v-model="username">
<!--插值表达式-->
{{username}}
</div>
<script src="js/vue.js"></script>
<script>
//1. 创建Vue核心对象
new Vue({
el:"#app",
data(){
return {
username:""
}
}
/*data: function () {
return {
username:""
}
}*/
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<a v-bind:href="url">点击一下</a>
<a :href="url">点击一下</a>
<input v-model="url">
</div>
<script src="js/vue.js"></script>
<script>
//1. 创建Vue核心对象
new Vue({
el:"#app",
data(){
return {
username:"",
url:"https://www.baidu.com"
}
}
});
</script>
</body>
</html>
1、常用指令
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<input type="button" value="一个按钮" v-on:click="show()"><br>
<input type="button" value="一个按钮" @click="show()">
</div>
<script src="js/vue.js"></script>
<script>
//1. 创建Vue核心对象
new Vue({
el:"#app",
data(){
return {
username:"",
url:"https://www.baidu.com"
}
},
methods:{
show(){
alert("我被点了...");
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<div v-if="count == 3">div1</div>
<div v-else-if="count == 4">div2</div>
<div v-else>div3</div>
<hr>
<div v-show="count == 3">div v-show</div>
<br>
<input v-model="count">
</div>
<script src="js/vue.js"></script>
<script>
//1. 创建Vue核心对象
new Vue({
el:"#app",
data(){
return {
username:"",
url:"https://www.baidu.com",
count:3
}
},
methods:{
show(){
alert("我被点了...");
}
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<div v-for="addr in addrs">
{{addr}} <br>
</div>
<hr>
<div v-for="(addr,i) in addrs">
{{i+1}}--{{addr}} <br>
</div>
</div>
<script src="js/vue.js"></script>
<script>
//1. 创建Vue核心对象
new Vue({
el:"#app",
data(){
return {
username:"",
url:"https://www.baidu.com",
count:3,
addrs:["北京","上海","西安"]
}
},
methods:{
show(){
alert("我被点了...");
}
}
});
</script>
</body>
</html>
2、生命周期
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<div v-for="addr in addrs">
{{addr}} <br>
</div>
<hr>
<div v-for="(addr,i) in addrs">
{{i+1}}--{{addr}} <br>
</div>
</div>
<script src="js/vue.js"></script>
<script>
//1. 创建Vue核心对象
new Vue({
el:"#app",
data(){
return {
username:"",
url:"https://www.baidu.com",
count:3,
addrs:["北京","上海","西安"]
}
},
methods:{
show(){
alert("我被点了...");
}
},
/*mounted:function () {
}*/
mounted(){
alert("加载完成...")
}
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<a href="addBrand.html"><input type="button" value="新增"></a><br>
<hr>
<table id="brandTable" border="1" cellspacing="0" width="100%">
<tr>
<th>序号</th>
<th>品牌名称</th>
<th>企业名称</th>
<th>排序</th>
<th>品牌介绍</th>
<th>状态</th>
<th>操作</th>
</tr>
<!--
使用v-for遍历tr
-->
<tr v-for="(brand,i) in brands" align="center">
<td>{{i + 1}}</td>
<td>{{brand.brandName}}</td>
<td>{{brand.companyName}}</td>
<td>{{brand.ordered}}</td>
<td>{{brand.description}}</td>
<td>{{brand.statusStr}}</td>
<td><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</table>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
<script src="js/vue.js"></script>
<script>
new Vue({
el: "#app",
data(){
return{
brands:[]
}
},
mounted(){
// 页面加载完成后,发送异步请求,查询数据
var _this = this;
axios({
method:"get",
url:"http://localhost:8080/brand-demo/selectAllServlet"
}).then(function (resp) {
_this.brands = resp.data;
})
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="/brand-demo/addServlet" method="post">
品牌名称:<input id="brandName" v-model="brand.brandName" name="brandName"><br>
企业名称:<input id="companyName" v-model="brand.companyName" name="companyName"><br>
排序:<input id="ordered" v-model="brand.ordered" name="ordered"><br>
描述信息:<textarea rows="5" cols="20" id="description" v-model="brand.description" name="description"></textarea><br>
状态:
<input type="radio" v-model="brand.status" name="status" value="0">禁用
<input type="radio" v-model="brand.status" name="status" value="1">启用<br>
<input type="submit" id="btn" @click="submitForm" value="提交">
</form>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
<script src="js/vue.js"></script>
<script>
new Vue({
el: "#app",
data(){
return{
brand:{}
}
},
methods:{
submitForm(){
// 发送ajax请求,添加
// 2. 发送ajax请求
var _this = this;
axios({
method:"post",
url:"http://localhost:8080/brand-demo/addServlet-json",
data:_this.brand
}).then(function (resp) {
// 判断响应是否为success
if(resp.data == "success"){
location.href = "http://localhost:8080/brand-demo/brand.html"
}
})
}
}
})
// 1. 给按钮绑定单击事件
</script>
</body>
</html>
十一、ElementUI
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<el-row>
<!-- <el-button>默认按钮</el-button>
<el-button type="primary">主要按钮</el-button>
<el-button type="success">成功按钮</el-button>
<el-button type="info">信息按钮</el-button>
<el-button type="warning">警告按钮</el-button>-->
<el-button type="danger">删除</el-button>
</el-row>
<!--
<el-row>
<el-button plain>朴素按钮</el-button>
<el-button type="primary" plain>主要按钮</el-button>
<el-button type="success" plain>成功按钮</el-button>
<el-button type="info" plain>信息按钮</el-button>
<el-button type="warning" plain>警告按钮</el-button>
<el-button type="danger" plain>危险按钮</el-button>
</el-row>
<el-row>
<el-button round>圆角按钮</el-button>
<el-button type="primary" round>主要按钮</el-button>
<el-button type="success" round>成功按钮</el-button>
<el-button type="info" round>信息按钮</el-button>
<el-button type="warning" round>警告按钮</el-button>
<el-button type="danger" round>危险按钮</el-button>
</el-row>
<el-row>
<el-button icon="el-icon-search" circle></el-button>
<el-button type="primary" icon="el-icon-edit" circle></el-button>
<el-button type="success" icon="el-icon-check" circle></el-button>
<el-button type="info" icon="el-icon-message" circle></el-button>
<el-button type="warning" icon="el-icon-star-off" circle></el-button>
<el-button type="danger" icon="el-icon-delete" circle></el-button>
</el-row>-->
</div>
<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script>
new Vue({
el:"#app"
})
</script>
</body>
</html>
十二、案例
1、查询所有:SelectAllServlet
@WebServlet("/SelectAllServlet")
public class SelectAllServlet extends HttpServlet {
private BrandService brandService = new BrandServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 调用service查询
List<Brand> brands = brandService.selectAll();
//2. 转为JSON
String jsonString = JSON.toJSONString(brands);
//3. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
}
2、添加:AddServlet
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private BrandService brandService = new BrandServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1. 接受品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();
// 转为Brand对象
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service添加
brandService.add(brand);
//3. 响应成功的标识
response.getWriter().write("success");
}
}
3*、Servlet代码优化:BaseServlet
//替换HttpServlet,根据请求的最后一段路径进行方法分发
@WebServlet("BaseServlet")
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取请求路径
String uri = req.getRequestURI(); // /brand-case/brand/selectAll
// 2.获取最后一段路径(方法名)
int index = uri.lastIndexOf('/');
String methodName = uri.substring(index + 1); // /selectAll -> selectAll
// 3.执行方法
// 3.1 获取BrandServlet / UserServlet 字节码对象 Class
// this 谁调用我,我代表谁,BrandServlet / UserServlet
Class<? extends BaseServlet> cls = this.getClass();
// 3.2 获取方法Method对象
try {
Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
// 3.3 执行方法
method.invoke(this, req, resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
4、批量删除
5、分页查询
6、条件查询
BrandServlet
package com.itheima.web.servlet;
import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Brand;
import com.itheima.pojo.PageBean;
import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{
private BrandService brandService = new BrandServiceImpl();
public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 调用service查询
List<Brand> brands = brandService.selectAll();
//2. 转为JSON
String jsonString = JSON.toJSONString(brands);
//3. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1. 接受品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();
// 转为Brand对象
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service添加
brandService.add(brand);
//3. 响应成功的标识
response.getWriter().write("success");
}
public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1. 接受品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();
// 转为 int[]
int[] ids = JSON.parseObject(params, int[].class);
//2. 调用service添加
brandService.deleteByIds(ids);
//3. 响应成功的标识
response.getWriter().write("success");
}
public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 接收参数
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
//2. 调用Service查询
PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);
//3. 转为JSON
String jsonString = JSON.toJSONString(pageBean);
//4. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//1. 接收参数
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
//获取查询条件对象
// 接受品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用Service查询
PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage, pageSize, brand);
//3. 转为JSON
String jsonString = JSON.toJSONString(pageBean);
//4. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
}
brand.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
</head>
<body>
<div id="app">
<!--搜索表单-->
<el-form :inline="true" :model="brand" class="demo-form-inline">
<el-form-item label="当前状态">
<el-select v-model="brand.status" placeholder="当前状态">
<el-option label="启用" value="1"></el-option>
<el-option label="禁用" value="0"></el-option>
</el-select>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
</el-form-item>
<el-form-item label="品牌名称">
<el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
<!--按钮-->
<el-row>
<el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
<el-button type="primary" plain @click="dialogVisible = true">新增</el-button>
</el-row>
<!--添加数据对话框表单-->
<el-dialog
title="编辑品牌"
:visible.sync="dialogVisible"
width="30%"
>
<el-form ref="form" :model="brand" label-width="80px">
<el-form-item label="品牌名称">
<el-input v-model="brand.brandName"></el-input>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="brand.companyName"></el-input>
</el-form-item>
<el-form-item label="排序">
<el-input v-model="brand.ordered"></el-input>
</el-form-item>
<el-form-item label="备注">
<el-input type="textarea" v-model="brand.description"></el-input>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model="brand.status"
active-value="1"
inactive-value="0"
></el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="addBrand">提交</el-button>
<el-button @click="dialogVisible = false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<!--表格-->
<template>
<el-table
:data="tableData"
style="width: 100%"
:row-class-name="tableRowClassName"
@selection-change="handleSelectionChange"
>
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
type="index"
width="50">
</el-table-column>
<el-table-column
prop="brandName"
label="品牌名称"
align="center"
>
</el-table-column>
<el-table-column
prop="companyName"
label="企业名称"
align="center"
>
</el-table-column>
<el-table-column
prop="ordered"
align="center"
label="排序">
</el-table-column>
<el-table-column
prop="statusStr"
align="center"
label="当前状态">
</el-table-column>
<el-table-column
align="center"
label="操作">
<el-row>
<el-button type="primary">修改</el-button>
<el-button type="danger">删除</el-button>
</el-row>
</el-table-column>
</el-table>
</template>
<!--分页工具条-->
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[5, 10, 15, 20]"
:page-size="5"
layout="total, sizes, prev, pager, next, jumper"
:total="totalCount">
</el-pagination>
</div>
<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script>
new Vue({
el: "#app",
mounted(){
this.selectAll();
},
methods: {
selectAll(){
// var _this = this;
// //当页面加载完成后,发送异步请求,获取数据
// axios({
// method:"post",
// url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
// data:this.brand
// }).then(function (resp) {
// //设置表格数据
// _this.tableData = resp.data.rows;
// _this.totalCount = resp.data.totalCount;
// })
//当页面加载完成后,发送异步请求,获取数据
axios({
method:"post",
url:"http://localhost:8080/brand-case/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
data:this.brand
}).then(resp => {
//设置表格数据
this.tableData = resp.data.rows;
this.totalCount = resp.data.totalCount;
})
},
tableRowClassName({row, rowIndex}) {
if (rowIndex === 1) {
return 'warning-row';
} else if (rowIndex === 3) {
return 'success-row';
}
return '';
},
// 复选框选中后执行的方法
handleSelectionChange(val) {
this.multipleSelection = val;
console.log(this.multipleSelection)
},
// 查询方法
onSubmit() {
this.selectAll();
},
// 添加数据
addBrand(){
var _this = this;
// 发送ajax请求添加数据
axios({
method:"post",
url:"http://localhost:8080/brand-case/brand/add",
data:_this.brand
}).then(function (resp){
if(resp.data == "success"){
// 添加成功关闭窗口
_this.dialogVisible = false;
_this.selectAll();
_this.$message({
message: '恭喜你,添加成功!',
type: 'success'
});
}
})
},
deleteByIds() {
//弹出确认删除的提示框
this.$confirm('此操作将删除该继续, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
// 创建id数组[1,2,3], 从this.multipleSelection 获取即可
for (let i = 0; i < this.multipleSelection.length; i++) {
let selectElement = this.multipleSelection[i];
this.selectedIds[i] = selectElement.id;
}
var _this = this;
// 发送ajax请求添加数据
axios({
method: "post",
url: "http://localhost:8080/brand-case/brand/deleteByIds",
data: _this.selectedIds
}).then(function (resp) {
if (resp.data == "success") {
_this.selectAll();
_this.$message({
type: 'success',
message: '删除成功!'
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
})
},
//分页
handleSizeChange(val) {
//console.log(`每页 ${val} 条`);
this.pageSize = val;
this.selectAll();
},
handleCurrentChange(val) {
//console.log(`当前页: ${val}`);
this.currentPage = val;
this.selectAll();
}
},
data() {
return {
//默认页面大小
pageSize:5,
// 总记录数
totalCount:100,
// 当前页码
currentPage: 1,
// 添加数据对话框是否展示的标记
dialogVisible: false,
//被选中的id数组
selectedIds:[],
// 品牌模型数据
brand: {
status: '',
brandName: '',
companyName: '',
id:"",
ordered:"",
description:""
},
// 复选框选中数据集合
multipleSelection: [],
// 表格数据
tableData: [{
}]
}
}
})
</script>
</body>
</html>
十三、总结
- MVC模型:Model、View、Controller分别对应JavaBean、HTML+AJAX、Servlet技术
- SSM架构:分别对应Spring、SpringMVC、MyBatis三大主流框架以优化开发,其中Spring负责业务逻辑层,MyBatis负责数据访问层,两者对应JavaBean,SpringMVC对应Servlet负责表现层。