概念:Java Server Pags,java服务端页面
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
<scope>providedscope>
dependency>
案例:
<html>
<head>
<title>Titletitle>
head>
<body>
<h1>JSP,helloh1>
<%
System.out.println("hello jsp");
%>
body>
html>
<%...%>
:内容会直接放到_jspService()方法之中<%=...%>
:内容会放到out.print()中,作为out.print()的参数<%!..%>
:内容会放到_jspService()方法之外,被类直接包含例子:
注意使用maven插件的tomcat7运行时最好对应的jdk版本为1.8,如果jdk版本太高可能会出现jsp编译不了的情况(500报错之一)
解决方案:
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/7/31
Time: 9:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>JSP,hello</h1>
<%
out.println("hello,jsp");
int i = 3;
%>
<%="hello"%>
<%=i%>
<%!
void show(){}
String name = "zhangsan";
%>
</body>
</html>
package com.itheima.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 Brand(Integer id, String brandName, String companyName, String description) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.description = description;
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
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 +
'}';
}
}
brand.jsp:
<%@ page import="com.itheima.pojo.Brand" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %><%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/1
Time: 12:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
//查询数据库
List<Brand> brands = new ArrayList<Brand>();
brands.add(new Brand(1,"三只松鼠","三只松鼠",100,"三只松鼠,好吃不上火",1));
brands.add(new Brand(2,"优衣库","优衣库",200,"优衣库,服适人生",0));
brands.add(new Brand(3,"小米","小米科技有限公司",1000,"为发烧而生",1));
%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
<tr>
<th>序号</th>
<th>品牌名称</th>
<th>企业名称</th>
<th>排序</th>
<th>品牌介绍</th>
<th>状态</th>
<th>操作</th>
</tr>
<%
for (int i = 0; i < brands.size(); i++) {
Brand brand = brands.get(i);
%>
<tr align="center">
<td><%=brand.getId()%></td>
<td><%=brand.getBrandName()%></td>
<td><%=brand.getCompanyName()%></td>
<td><%=brand.getOrdered()%></td>
<td><%=brand.getDescription()%></td>
<%
if(brand.getStatus()==1){
//显示启用
%>
<td><%="启用"%></td>
<%
}else {
//显示禁用
%>
<td><%="禁用"%></td>
<%
}
%>
<td><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
<%
}
%>
</table>
</body>
</html>
由于JSP页面内,既可以定义HTML标签,又可以定义Java代码,造成了以下问题:
Expression Language表达式语言,用于简化JSP页面内的Java代码
语法:${expression}
${brands}
:获取域中存储的key为brands的数据
JavaWeb中的四大域对象:
例子:
ServletDemo1:
@WebServlet("/demo1")
public class ServletDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.准备数据
List<Brand> brands = new ArrayList<Brand>();
brands.add(new Brand(1,"三只松鼠","三只松鼠",100,"三只松鼠,好吃不上火",1));
brands.add(new Brand(2,"优衣库","优衣库",200,"优衣库,服适人生",0));
brands.add(new Brand(3,"小米","小米科技有限公司",1000,"为发烧而生",1));
//2.储存到request域中
request.setAttribute("brands",brands);
//3.转发到el-demo.jsp
request.getRequestDispatcher("/el-demo.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
el-demo.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${brands}
</body>
</html>
如果只是显示 ${brands}的话,在头部加上isELIgnored="false"
即可
JSP标准标签库(Jsp Standarded Tag Library),使用标签取代JSP页面上的Java代码
例如:
<c:if test="${flag ==1}">
男
</c:if>
<c:if test="${flag == 2}">
女
</c:if>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstl<lartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
<%@ taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %>
例子:
ServletDemo1类修改部分:
jstl-if.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<head>
<title>Title</title>
</head>
<body>
<%--
c:if 来完成逻辑判断,替换java if else
--%>
<%-- <c:if test="true">--%>
<%-- <h1>true</h1>--%>
<%-- </c:if>--%>
<%-- <c:if test="false">--%>
<%-- <h1>false</h1>--%>
<%-- </c:if>--%>
<c:if test="${status ==1}">
启用
</c:if>
<c:if test="${status ==0}">
禁用
</c:if>
</body>
</html>
显示如果空白的话,添加:isELIgnored=“false”
:相当于for循环
例子:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="800">
<tr>
<th>序号</th>
<th>品牌名称</th>
<th>企业名称</th>
<th>排序</th>
<th>品牌介绍</th>
<th>状态</th>
<th>操作</th>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<%-- <td>${brand.id}</td>--%>
<td>${status.count}</td>
<td>${brand.brandName}</td>
<td>${brand.companyName}</td>
<td>${brand.ordered}</td>
<td>${brand.description}</td>
<c:if test="${brand.status==1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status != 1}">
<td>禁用</td>
</c:if>
<td><a href="#">修改</a> <a href="#">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
例子:
<c:forEach begin="1" end="10" step="1" var="i">
<%-- ${i}<br>--%>
<a href="#">${i}</a>
</c:forEach>
MVC是一种分层开发的模式,其中:
MVC好处:
MVC和三层架构的区别:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>org.examplegroupId>
<artifactId>brand-demoartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<properties>
<maven.compiler.source>17maven.compiler.source>
<maven.compiler.target>17maven.compiler.target>
properties>
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.30version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>taglibsgroupId>
<artifactId>standardartifactId>
<version>1.1.2version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.mavengroupId>
<artifactId>tomcat7-maven-pluginartifactId>
<version>2.2version>
plugin>
plugins>
build>
project>
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
-- id 主键
id int primary key auto_increment,
-- 品牌名称
brand_name varchar(20),
-- 企业名称
company_name varchar(20),
-- 排序字段
ordered int,
-- 描述信息
description varchar(100),
-- 状态:0:禁用 1:启用
status int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1);
SELECT * FROM tb_brand;
package com.itheima.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 Brand(Integer id, String brandName, String companyName, String description) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.description = description;
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.status = status;
}
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 +
'}';
}
}
DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.itheima.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="root"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.itheima.mapper"/>
mappers>
configuration>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">
mapper>
package com.itheima.mapper;
public interface BrandMapper {
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/2
Time: 9:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<input type="button" value="新增"><br>
<hr>
<table border="1" cellspacing="0" width="80%">
<tr>
<th>序号th>
<th>品牌名称th>
<th>企业名称th>
<th>排序th>
<th>品牌介绍th>
<th>状态th>
<th>操作th>
tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<%-- <td>${brand.id}td>--%>
<td>${status.count}td>
<td>${brand.brandName}td>
<td>${brand.companyName}td>
<td>${brand.ordered}td>
<td>${brand.description}td>
<c:if test="${brand.status==1}">
<td>启用td>
c:if>
<c:if test="${brand.status != 1}">
<td>禁用td>
c:if>
<td><a href="#">修改a> <a href="#">删除a>td>
tr>
c:forEach>
table>
body>
html>
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName">result>
<result column="company_name" property="companyName">result>
resultMap>
mapper>
package com.itheima.mapper;
import com.itheima.pojo.Brand;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
}
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;
}
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<a href="/brand-demo/selectAllServlet">查询所有a>
body>
html>
ublic 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;
}
}
@WebServlet("/selectAllServlet")
public class selectAllServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.调用BrandService完成查询
List<Brand> brands = service.selectAll();
//2.存入request域中
request.setAttribute("brands",brands);
//3.转发到brand.jsp
request.getRequestDispatcher("/brand.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/2
Time: 9:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<input type="button" value="新增" id="add"><br>
<hr>
<table border="1" cellspacing="0" width="80%">
<tr>
<th>序号th>
<th>品牌名称th>
<th>企业名称th>
<th>排序th>
<th>品牌介绍th>
<th>状态th>
<th>操作th>
tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<%-- <td>${brand.id}td>--%>
<td>${status.count}td>
<td>${brand.brandName}td>
<td>${brand.companyName}td>
<td>${brand.ordered}td>
<td>${brand.description}td>
<c:if test="${brand.status==1}">
<td>启用td>
c:if>
<c:if test="${brand.status != 1}">
<td>禁用td>
c:if>
<td><a href="#">修改a> <a href="#">删除a>td>
tr>
c:forEach>
table>
<script>
document.getElementById("add").onclick = function (){
location.href="/brand-demo/addBrand.jsp ";
}
script>
body>
html>
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
}
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 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();
}
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/2
Time: 21:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加品牌title>
head>
<body>
<h3>添加品牌h3>
<form action="/brand-demo/AddServlet" method="post">
品牌名称:<input name="brandName"><br>
企业名称:<input name="companyName"><br>
排序:<input name="ordered"><br>
描述信息:<textarea rows="5" cols="20" name="description">textarea><br>
状态:
<input type="radio" name="status" value="0">禁用
<input type="radio" name="status" value="1">启用<br>
<input type="submit" value="提交">
form>
body>
html>
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
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.setOrdered(Integer.parseInt(ordered));
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//2.调用service 完成添加操作
service.add(brand);
//3.转发到查询所有Servlet
request.getRequestDispatcher("/selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
//根据id查询
@Select("select * from tb_brand where id = #{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/2
Time: 21:22
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>修改品牌title>
head>
<body>
<h3>修改品牌h3>
<form action="/brand-demo/AddServlet" method="post">
品牌名称:<input name="brandName" value="${brand.brandName}"><br>
企业名称:<input name="companyName" value="${brand.companyName}"><br>
排序:<input name="ordered" value="${brand.ordered}"><br>
描述信息:<textarea rows="5" cols="20" name="description"> value="${brand.description}"textarea><br>
状态:
<c:if test="${brand.status == 0}">
<input type="radio" name="status" value="0" checked>禁用
<input type="radio" name="status" value="1">启用<br>
c:if>
<c:if test="${brand.status == 1}">
<input type="radio" name="status" value="0">禁用
<input type="radio" name="status" value="1" checked>启用<br>
c:if>
<input type="submit" value="提交">
form>
body>
html>
WebServlet("/selectByIdServlet")
public class selectByIdServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.接收id
String id = request.getParameter("id");
//2.调用serivce查询
Brand brand = service.selectById(Integer.parseInt(id));
//3.存储到request中
request.setAttribute("brand",brand);
//4.转发到update.jsp
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
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 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();
}
//根据id查询
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 interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
//根据id查询
@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},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}")
void update(Brand brand);
}
@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {
private BrandService service = new BrandService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理post请求乱码问题
request.setCharacterEncoding("utf-8");
//1.结束表单提交的数据,封装为一个Brand妒忌心
String id = request.getParameter("id");
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.setId(Integer.parseInt(id));
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//2.调用service 完成添加操作
service.update(brand);
//3.转发到查询所有Servlet
request.getRequestDispatcher("/selectAllServlet").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
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 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();
}
//根据id查询
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 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();
}
}
实现方式:
Cookie
Session
Cookie:客户端会话技术,将数据保存到客户端,以后每次请求都携带Cookie数据进行访问
基本使用:
发送Cookie:
Cookie cookie = new Cookie("key","value");
response.addCookie(cookie);
例如:
@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
@Override
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);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
获取Cookie:
Cookie[] cookies = request.getCookies();
cookie.getName();
cookie.getName();
cookie.getValue();
例子:
@WebServlet("/bServlet")
public class bServlet extends HttpServlet {
@Override
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;
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
cookie的实现是基于HTTP协议的:
Cookie存活时间:
例子:
@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//发送cookie
//1.创建cookie对象
Cookie cookie = new Cookie("username", "vanwot");
//设置存活时间 7天
cookie.setMaxAge((60*60*24*7));
//2.发送Cookie.response
response.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
Cookie存储中文:
//编码
value = URLDecoder.encode(value,"UTF-8");
//解码
value = URLDecoder.decode(value,"UTF-8");
例子:
aServelt:
@WebServlet("/aServlet")
public class aServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//发送cookie
//1.创建cookie对象
String value= "麻瓜";
//URL编码
value = URLEncoder.encode(value,"utf-8");
System.out.println("储存数据:"+value);
Cookie cookie = new Cookie("username", value);
//设置存活时间 7天
cookie.setMaxAge((60*60*24*7));
//2.发送Cookie.response
response.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
bServlet:
@WebServlet("/bServlet")
public class bServlet extends HttpServlet {
@Override
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);
//URL解码
value = URLDecoder.decode(value,"utf-8");
System.out.println(name+":"+value);
break;
}
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
服务端会话跟踪技术:将数据保存到服务端
JavaEE提供HttpSession接口,来实现一次会话的多次请求间数据共享功能
使用:
HttpSession session = request.getSession();
例子:
SessionDemo1:
@WebServlet("/demo1")
public class SessionDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//存储到Session中
//1.获取Session对象
HttpSession session = request.getSession();
//2.存储数据
session.setAttribute("username","vanwot");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
SessionDemo2:
@WebServlet("/demo2")
public class SessionDemo2 extends HttpServlet {
@Override
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);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
Session钝化、活化:
Seesion销毁:
<session-config>
<session-timeout>30session-timeout>
session-config>
Cookie和Session都是完成一次会话内多次请求间数据共享的
其区别:
在brand-demo的webapp下导入原来的:
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);
}
User实体类:
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
UserMapper.xml
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.UserMapper">
mapper>
UserService:
public class UserService {
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
//登录方法
public User login(String username,String password){
//2.获取SqlSession
SqlSession sqlSession = factory.openSession();
//3.获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//4.调用方法
User user = mapper.select(username, password);
sqlSession.close();
return user;
}
}
loginServlet:
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private UserService service = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2.调用service查询
User user = service.login(username,password);
//3.判断
if(user !=null){
//登录成功,跳转到查询所有的BrandServlet
//将登录成功后的user对象,储存到Session中
HttpSession session = request.getSession();
session.setAttribute("user",user);
String contextPath = request.getContextPath();
response.sendRedirect(contextPath+"/selectAllServlet");
}else {
//登录失败
//存储错误信息到request
request.setAttribute("login_msg","用户名或密码错误");
//跳转到login.jsp
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/4
Time: 23:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logintitle>
<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 INh1>
<div id="errorMsg">${login_msg}div>
<p>Username:<input id="username" name="username" type="text">p>
<p>Password:<input id="password" name="password" 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 up">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?a>
div>
form>
div>
body>
html>
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
private UserService service = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//获取复选框数据
String remenber = request.getParameter("remenber");
//2.调用service查询
User user = service.login(username,password);
//3.判断
if(user !=null){
//登录成功,跳转到查询所有的BrandServlet
//判断用户是否勾选记住我
if ("1".equals(remenber)){
//勾选了,发送cookie对象
//1.创建cookie对象
Cookie c_username = new Cookie("username",username);
Cookie c_password = new Cookie("password",password);
//设置cookie存活时间
c_username.setMaxAge(60*60*24*7);
c_password.setMaxAge(60*60*24*7);
//2.发送
response.addCookie(c_username);
response.addCookie(c_password);
}
//将登录成功后的user对象,储存到Session中
HttpSession session = request.getSession();
session.setAttribute("user",user);
String contextPath = request.getContextPath();
response.sendRedirect(contextPath+"/selectAllServlet");
}else {
//登录失败
//存储错误信息到request
request.setAttribute("login_msg","用户名或密码错误");
//跳转到login.jsp
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
刷新后:
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/4
Time: 23:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logintitle>
<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 INh1>
<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 up">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?a>
div>
form>
div>
body>
html>
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/5
Time: 10:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
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="post">
<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 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>
body>
html>
package com.itheima.web;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
private UserService service = new UserService();
@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.调用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);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/4
Time: 23:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>logintitle>
<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 INh1>
<div id="errorMsg">${login_msg}${register_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 up">
<input type="reset" class="button" value="reset">
<a href="register.jsp">没有账号?a>
div>
form>
div>
body>
html>
CheckCodeUtil类:
package com.itheima.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
/**
* 生成验证码工具类
*/
public class CheckCodeUtil {
public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random random = new Random();
public static void main(String[] args) throws IOException {
OutputStream fos = new FileOutputStream("E://JSP-demo1/brand-demo/src/main/webapp/imgs/a.jpg");
String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
System.out.println(checkCode);
}
/**
* 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
*
* @param width 图片宽度
* @param height 图片高度
* @param os 输出流
* @param verifySize 数据长度
* @return 验证码
* @throws IOException
*/
public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(width, height, 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);
}
}
}
}
<%--
Created by IntelliJ IDEA.
User: 19148
Date: 2023/8/5
Time: 10:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
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="post">
<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>
@WebServlet("/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletOutputStream os = response.getOutputStream();
String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
private UserService service = new UserService();
@Override
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");
//程序生成的验证码,从Session获取
HttpSession session = request.getSession();
String checkCodeGen = (String) session.getAttribute("checkCodeGen");
User user = new User();
user.setUsername(username);
user.setPassword(password);
//2.调用service 注册
boolean flag = service.register(user);
//3.判断注册成功与否
if(flag){
//注册成功,跳转登录页面
request.setAttribute("register_msg","注册成功,请登录");
request.getRequestDispatcher("/login.jsp").forward(request,response);
//比对验证码
if(!checkCodeGen.equalsIgnoreCase(checkCode)){
request.setAttribute("register_msg","验证码错误");
request.getRequestDispatcher("/register.jsp").forward(request,response);
//不允许注册
return;
}
}else{
//注册失败
request.setAttribute("register_msg","用户已经存在");
request.getRequestDispatcher("/register.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}