当前位置: 首页 > news >正文

建一个网站大约多少钱网站建设 青少年宫

建一个网站大约多少钱,网站建设 青少年宫,做外贸的人经常用什么网站,我的网站在百度搜不到JavaWeb入门5.0 1. JSP1.1 JSP快速入门1.2 JSP原理1.3 JSP脚本1.3.1 JSP缺点 1.4 EL 表达式1.5 JSTL 标签1.5.1 JSTL 快速入门1.5.1 - I JSTL标签if1.5.1 - II JSTL标签forEach 1.6 MVC模式1.7 三层架构1.8 实现案例1.8.1 环境准备1.8.2 查询所有1.8.3 添加数据1.8.4 修改1.8.4… JavaWeb入门5.0 1. JSP1.1 JSP快速入门1.2 JSP原理1.3 JSP脚本1.3.1 JSP缺点 1.4 EL 表达式1.5 JSTL 标签1.5.1 JSTL 快速入门1.5.1 - I JSTL标签if1.5.1 - II JSTL标签forEach 1.6 MVC模式1.7 三层架构1.8 实现案例1.8.1 环境准备1.8.2 查询所有1.8.3 添加数据1.8.4 修改1.8.4 - I 修改回显数据1.8.4 - II 修改数据 2. 会话跟踪技术2.1 Cookie2.1.1 Cookie基本使用2.1.2 Cookie原理2.1.3 Cookie使用细节 2.2 Session2.2.1 Session基本使用2.2.2 Session原理2.2.3 Session使用细节 2.3 小结2.4 案例2.4.1 用户登录2.4.2 记住用户2.4.2 - I 写cookie2.4.2 - II 获取cookie 2.4.3 用户注册2.4.4 验证码2.4.4 - I 校验验证码 1. JSP 概念Java Server Pagsjava服务端页面 一种动态的网页接收其中即可以定义HTML、JS、CSS等静态内容还可以定义Java代码的动态内容JSP HTML Java 1.1 JSP快速入门 导入JSP坐标 dependencygroupIdjavax.servlet.jsp/groupIdartifactIdjsp-api/artifactIdversion2.2/versionscopeprovided/scope/dependency创建JSP文件 编写HTML标签和Java代码 案例 html headtitleTitle/title /head bodyh1JSP,hello/h1%System.out.println(hello jsp);% /body /html1.2 JSP原理 JSP本质上就是一个ServletJSP在被访问时由JSP容器(Tomcat)将其转换为Java文件(Servlet)在由JSP容器(Tomcat)将其编译最终对外提供服务的其实就是这个字节码文件 1.3 JSP脚本 JSP脚本用于在JSP页面内定义Java代码.JSP脚本分类: 1、 %...%:内容会直接放到_jspService()方法之中 2、%...%:内容会放到out.print()中作为out.print()的参数 3、%!..%:内容会放到_jspService()方法之外被类直接包含 例子 注意使用maven插件的tomcat7运行时最好对应的jdk版本为1.8如果jdk版本太高可能会出现jsp编译不了的情况500报错之一 解决方案 1.在设置里面Build-创建工具-Maven-运行程序下找到JRE条件jdk版本2.自行在创建项目时使用低版本的jdk3.具体分析java语法变换下例情况去掉System %--Created by IntelliJ IDEA.User: 19148Date: 2023/7/31Time: 9:46To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava % html headtitleTitle/title /head bodyh1JSP,hello/h1%out.println(hello,jsp);int i 3;%%hello%%i%%!void show(){}String name zhangsan;% /body /html练习 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;}Overridepublic String toString() {return Brand{ id id , brandName brandName \ , companyName companyName \ , ordered ordered , description description \ , status status };} } brand.jsp: % page importcom.itheima.pojo.Brand % % page importjava.util.List % % page importjava.util.ArrayList %%--Created by IntelliJ IDEA.User: 19148Date: 2023/8/1Time: 12:19To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %%//查询数据库ListBrand brands new ArrayListBrand();brands.add(new Brand(1,三只松鼠,三只松鼠,100,三只松鼠好吃不上火,1));brands.add(new Brand(2,优衣库,优衣库,200,优衣库服适人生,0));brands.add(new Brand(3,小米,小米科技有限公司,1000,为发烧而生,1)); %!DOCTYPE html html langen headmeta charsetUTF-8titleTitle/title /head body input typebutton value新增br hr table border1 cellspacing0 width800trth序号/thth品牌名称/thth企业名称/thth排序/thth品牌介绍/thth状态/thth操作/th/tr%for (int i 0; i brands.size(); i) {Brand brand brands.get(i);%tr aligncentertd%brand.getId()%/tdtd%brand.getBrandName()%/tdtd%brand.getCompanyName()%/tdtd%brand.getOrdered()%/tdtd%brand.getDescription()%/td%if(brand.getStatus()1){//显示启用%td%启用%/td%}else {//显示禁用%td%禁用%/td%}%tda href#修改/a a href#删除/a/td/tr%}%/table/body /html1.3.1 JSP缺点 由于JSP页面内既可以定义HTML标签又可以定义Java代码造成了以下问题: 书写麻烦:特别是复杂的页面阅读麻烦复杂度高:运行需要依赖于各种环境JREJSP容器JavaEE…占内存和磁盘:JSP会自动生成.java和.class文件占磁盘运行的是.class文件占内存调试困难:出错后需要找到自动生成的.java文件进行调试不利于团队协作:前端人员不会Java后端人员不精HTML … 演变过程 1.4 EL 表达式 Expression Language表达式语言用于简化JSP页面内的Java代码 主要功能获取数据 语法${expression} ${brands}获取域中存储的key为brands的数据 JavaWeb中的四大域对象: page:当前页面有效request:当前请求有效session:当前会话有效application:当前应用有效 例子 ServletDemo1 WebServlet(/demo1) public class ServletDemo1 extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.准备数据ListBrand brands new ArrayListBrand();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.jsprequest.getRequestDispatcher(/el-demo.jsp).forward(request,response);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } el-demo.jsp % page contentTypetext/html;charsetUTF-8 languagejava isELIgnoredfalse % html headtitleTitle/title /head body${brands}/body /html 如果只是显示 ${brands}的话在头部加上isELIgnoredfalse即可 el表达式获取数据会依次从这4个域中寻找直到找到为止 1.5 JSTL 标签 JSP标准标签库(Jsp Standarded Tag Library)使用标签取代JSP页面上的Java代码 例如 c:if test${flag 1} 男 /c:if c:if test${flag 2} 女 /c:if1.5.1 JSTL 快速入门 导入坐标 dependencygroupIdjstl/groupIdartifactIdjstllartifactIdversion1.2/version /dependency dependencygroupIdtaglibs/groupIdartifactIdstandard/artifactIdversion1.1.2/version /dependency在JSP页面上引入JSTL标签库 % taglib prefix c uri http://java.sun.com/jsp/jstl/core %使用 C:if 1.5.1 - I JSTL标签if 例子 ServletDemo1类修改部分 jstl-if.jsp % page contentTypetext/html;charsetUTF-8 languagejava isELIgnoredfalse % html %taglib prefixc urihttp://java.sun.com/jsp/jstl/core%headtitleTitle/title /head body %--c:if 来完成逻辑判断替换java if else --%%-- c:if testtrue--% %-- h1true/h1--% %-- /c:if--% %-- c:if testfalse--% %-- h1false/h1--% %-- /c:if--%c:if test${status 1}启用/c:ifc:if test${status 0}禁用/c:if /body /html 显示如果空白的话添加isELIgnored“false” 1.5.1 - II JSTL标签forEach c:forEach相当于for循环 items被遍历的容器var遍历产生的临时变量varStatus遍历状态对象count从1开始遍历的数字status从0开始遍历的数字 例子 % page contentTypetext/html;charsetUTF-8 languagejava isELIgnoredfalse % %taglib prefixc urihttp://java.sun.com/jsp/jstl/core %!DOCTYPE html html langen headmeta charsetUTF-8titleTitle/title /head body input typebutton value新增br hr table border1 cellspacing0 width800trth序号/thth品牌名称/thth企业名称/thth排序/thth品牌介绍/thth状态/thth操作/th/trc:forEach items${brands} varbrand varStatusstatustr aligncenter %-- td${brand.id}/td--%td${status.count}/tdtd${brand.brandName}/tdtd${brand.companyName}/tdtd${brand.ordered}/tdtd${brand.description}/tdc:if test${brand.status1}td启用/td/c:ifc:if test${brand.status ! 1}td禁用/td/c:iftda href#修改/a a href#删除/a/td/tr/c:forEach/table/body /htmlbegin开始数end结束数step步长 例子 c:forEach begin1 end10 step1 vari %-- ${i}br--%a href#${i}/a /c:forEach1.6 MVC模式 MVC是一种分层开发的模式其中: M: Model业务模型处理业务V: View视图界面展示C: Controller控制器处理请求调用模型和视图 MVC好处 职责单一互不影响有利于分工协作有利于组件重用 1.7 三层架构 数据访问层对数据库的CRUD基本操作业务逻辑层对业务逻辑进行封装组合数据访问层层中基本功能形成复杂的业务逻辑功能表现层接收请求封装数据调用业务逻辑层响应数据 MVC和三层架构的区别 1.8 实现案例 1.8.1 环境准备 核心配置文件pom.xml ?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdorg.example/groupIdartifactIdbrand-demo/artifactIdversion1.0-SNAPSHOT/versionpackagingwar/packagingpropertiesmaven.compiler.source17/maven.compiler.sourcemaven.compiler.target17/maven.compiler.target/propertiesdependencies !-- mybatis--dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.5/version/dependency!-- mysql--dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.30/version/dependency!-- servlet--dependencygroupIdjavax.servlet/groupIdartifactIdjavax.servlet-api/artifactIdversion3.1.0/versionscopeprovided/scope/dependency!-- jsp--dependencygroupIdjavax.servlet.jsp/groupIdartifactIdjsp-api/artifactIdversion2.2/versionscopeprovided/scope/dependency!-- jstl--dependencygroupIdjstl/groupIdartifactIdjstl/artifactIdversion1.2/version/dependency!-- standard标准标签库--dependencygroupIdtaglibs/groupIdartifactIdstandard/artifactIdversion1.1.2/version/dependency/dependenciesbuildpluginsplugingroupIdorg.apache.tomcat.maven/groupIdartifactIdtomcat7-maven-plugin/artifactIdversion2.2/version/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;pojo下的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;}Overridepublic String toString() {return Brand{ id id , brandName brandName \ , companyName companyName \ , ordered ordered , description description \ , status status };} }mybatis-config.xml ?xml version1.0 encodingUTF-8 ? !DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd configuration!--起别名--typeAliasespackage namecom.itheima.pojo//typeAliasesenvironments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLEDproperty namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql:///db1?useSSLfalseamp;useServerPrepStmtstrue/property nameusername valueroot/property namepassword valueroot//dataSource/environment/environmentsmappers!--扫描mapper--package namecom.itheima.mapper//mappers /configurationBrandMapper.xml ?xml version1.0 encodingUTF-8 ? !DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecom.itheima.mapper.BrandMapper/mapperBrandMapper.java package com.itheima.mapper;public interface BrandMapper { }目录展示 1.8.2 查询所有 brand.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/2Time: 9:59To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava isELIgnoredfalse % %taglib prefixc urihttp://java.sun.com/jsp/jstl/core %!DOCTYPE html html langen headmeta charsetUTF-8titleTitle/title /head body input typebutton value新增br hr table border1 cellspacing0 width80%trth序号/thth品牌名称/thth企业名称/thth排序/thth品牌介绍/thth状态/thth操作/th/trc:forEach items${brands} varbrand varStatusstatustr aligncenter %-- td${brand.id}/td--%td${status.count}/tdtd${brand.brandName}/tdtd${brand.companyName}/tdtd${brand.ordered}/tdtd${brand.description}/tdc:if test${brand.status1}td启用/td/c:ifc:if test${brand.status ! 1}td禁用/td/c:iftda href#修改/a a href#删除/a/td/tr/c:forEach/table/body /htmlBrandMapper.xml ?xml version1.0 encodingUTF-8 ? !DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecom.itheima.mapper.BrandMapperresultMap idbrandResultMap typebrandresult columnbrand_name propertybrandName/resultresult columncompany_name propertycompanyName/result/resultMap /mapperBrandMapper.java 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)ListBrand selectAll(); } BrandService.java public class BrandService {SqlSessionFactory factory SqlSessionFactoryUtils.getSqlSessionFactory();//查询所有功能public ListBrand selectAll(){//调用BrandMapper.selectAll()//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法ListBrand brands mapper.selectAll();sqlSession.close();return brands;} } index.html !DOCTYPE html html langen headmeta charsetUTF-8titleTitle/title /head bodya href/brand-demo/selectAllServlet查询所有/a /body /htmlSqlSessionFactoryUtils 类 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;} } selectAllServlet WebServlet(/selectAllServlet) public class selectAllServlet extends HttpServlet {private BrandService service new BrandService();Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.调用BrandService完成查询ListBrand brands service.selectAll();//2.存入request域中request.setAttribute(brands,brands);//3.转发到brand.jsprequest.getRequestDispatcher(/brand.jsp).forward(request,response);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 1.8.3 添加数据 brand.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/2Time: 9:59To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava isELIgnoredfalse % %taglib prefixc urihttp://java.sun.com/jsp/jstl/core %!DOCTYPE html html langen headmeta charsetUTF-8titleTitle/title /head body input typebutton value新增 idaddbr hr table border1 cellspacing0 width80%trth序号/thth品牌名称/thth企业名称/thth排序/thth品牌介绍/thth状态/thth操作/th/trc:forEach items${brands} varbrand varStatusstatustr aligncenter %-- td${brand.id}/td--%td${status.count}/tdtd${brand.brandName}/tdtd${brand.companyName}/tdtd${brand.ordered}/tdtd${brand.description}/tdc:if test${brand.status1}td启用/td/c:ifc:if test${brand.status ! 1}td禁用/td/c:iftda href#修改/a a href#删除/a/td/tr/c:forEach/tablescriptdocument.getElementById(add).onclick function (){location.href/brand-demo/addBrand.jsp ;} /script/body /htmlBrandMapper.java public interface BrandMapper {//查询所有Select(select * from tb_brand)ResultMap(brandResultMap)ListBrand selectAll();Insert(insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status}))void add(Brand brand); } BrandService.java public class BrandService {SqlSessionFactory factory SqlSessionFactoryUtils.getSqlSessionFactory();//查询所有功能public ListBrand selectAll(){//调用BrandMapper.selectAll()//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法ListBrand brands mapper.selectAll();sqlSession.close();return brands;}public void add(Brand brand){//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法mapper.add(brand);//提交事务sqlSession.commit();sqlSession.close();}} addBrand.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/2Time: 21:22To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %!DOCTYPE html html langenheadmeta charsetUTF-8title添加品牌/title /head body h3添加品牌/h3 form action/brand-demo/AddServlet methodpost品牌名称input namebrandNamebr企业名称input namecompanyNamebr排序input nameorderedbr描述信息textarea rows5 cols20 namedescription/textareabr状态input typeradio namestatus value0禁用input typeradio namestatus value1启用brinput typesubmit value提交 /form /body /htmlAddServlet.java WebServlet(/AddServlet) public class AddServlet extends HttpServlet {private BrandService service new BrandService();Overrideprotected 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.转发到查询所有Servletrequest.getRequestDispatcher(/selectAllServlet).forward(request,response);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 1.8.4 修改 1.8.4 - I 修改回显数据 BrandMapper.java public interface BrandMapper {//查询所有Select(select * from tb_brand)ResultMap(brandResultMap)ListBrand 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.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/2Time: 21:22To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava isELIgnoredfalse% %taglib prefixc urihttp://java.sun.com/jsp/jstl/core%!DOCTYPE html html langenheadmeta charsetUTF-8title修改品牌/title /head body h3修改品牌/h3 form action/brand-demo/AddServlet methodpost品牌名称input namebrandName value${brand.brandName}br企业名称input namecompanyName value${brand.companyName}br排序input nameordered value${brand.ordered}br描述信息textarea rows5 cols20 namedescription value${brand.description}/textareabr状态c:if test${brand.status 0}input typeradio namestatus value0 checked禁用input typeradio namestatus value1启用br/c:ifc:if test${brand.status 1}input typeradio namestatus value0禁用input typeradio namestatus value1 checked启用br/c:ifinput typesubmit value提交 /form /body /htmlselectByIdServlet WebServlet(/selectByIdServlet) public class selectByIdServlet extends HttpServlet {private BrandService service new BrandService();Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.接收idString id request.getParameter(id);//2.调用serivce查询Brand brand service.selectById(Integer.parseInt(id));//3.存储到request中request.setAttribute(brand,brand);//4.转发到update.jsprequest.getRequestDispatcher(/update.jsp).forward(request,response);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } BrandService public class BrandService {SqlSessionFactory factory SqlSessionFactoryUtils.getSqlSessionFactory();//查询所有功能public ListBrand selectAll(){//调用BrandMapper.selectAll()//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法ListBrand brands mapper.selectAll();sqlSession.close();return brands;}public void add(Brand brand){//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法mapper.add(brand);//提交事务sqlSession.commit();sqlSession.close();}//根据id查询public Brand selectById(int id){//调用BrandMapper.selectAll()//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法Brand brand mapper.selectById(id);sqlSession.close();return brand;} } 1.8.4 - II 修改数据 BrandMapper.java public interface BrandMapper {//查询所有Select(select * from tb_brand)ResultMap(brandResultMap)ListBrand 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); } updateService.java WebServlet(/updateServlet) public class updateServlet extends HttpServlet {private BrandService service new BrandService();Overrideprotected 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.转发到查询所有Servletrequest.getRequestDispatcher(/selectAllServlet).forward(request,response);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } BrandService.java public class BrandService {SqlSessionFactory factory SqlSessionFactoryUtils.getSqlSessionFactory();//查询所有功能public ListBrand selectAll(){//调用BrandMapper.selectAll()//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法ListBrand brands mapper.selectAll();sqlSession.close();return brands;}//添加public void add(Brand brand){//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法mapper.add(brand);//提交事务sqlSession.commit();sqlSession.close();}//根据id查询public Brand selectById(int id){//调用BrandMapper.selectAll()//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法Brand brand mapper.selectById(id);sqlSession.close();return brand;}//添加public void update(Brand brand){//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取BrandMapperBrandMapper mapper sqlSession.getMapper(BrandMapper.class);//4.调用方法mapper.update(brand);//提交事务sqlSession.commit();sqlSession.close();}} 2. 会话跟踪技术 会话用户打开浏览器访问web服务器的资源会话建立直到有一方断开连接会话结束。在一次会话中可以包含多次请求和响应会话跟踪一种维护浏览器状态的方法服务器需要识别多次请求是否来自于同一浏览器以便于在同一次会话的多次请求间共享数据HTTP协议是无状态的每次浏览器向服务器请求时服务器都会将该请求视为新的请求因此我们需要会话跟踪技术来实现会话数据共享 实现方式 客户端会话跟踪技术Cookie服务端会话跟踪技术Session 2.1 Cookie 2.1.1 Cookie基本使用 Cookie客户端会话技术将数据保存到客户端以后每次请求都携带Cookie数据进行访问 基本使用 发送Cookie 创建Cookie对象设置数据 Cookie cookie new Cookie(key,value);发送Cookie到客户端使用response对象 response.addCookie(cookie);例如 WebServlet(/aServlet) public class aServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//发送cookie//1.创建cookie对象Cookie cookie new Cookie(username, zs);//2.发送Cookie.responseresponse.addCookie(cookie);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 获取Cookie 获取客户端携带的所有Cookie使用request对象 Cookie[] cookies request.getCookies();遍历数组获取每一个Cookie对象for cookie.getName();使用Cookie对象方法获取数据 cookie.getName();cookie.getValue();例子 WebServlet(/bServlet) public class bServlet extends HttpServlet {Overrideprotected 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;}}}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 接收aServlet的cookie 2.1.2 Cookie原理 cookie的实现是基于HTTP协议的 响应头set-cookie请求头cookie 2.1.3 Cookie使用细节 Cookie存活时间 默认情况下Cookie存储在浏览器内存中当浏览器关闭内存释放则Cookie被销毁setMaxAge(int seconds):设置Cookie存活时间 1、正数将Cookie写入浏览器所在电脑的硬盘持久化存储。到时间自动删除2、负数默认值Cookie在当前浏览器内存中当浏览器关闭则Cookie被销毁3、零删除对应Cookie 例子 WebServlet(/aServlet) public class aServlet extends HttpServlet {Overrideprotected 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.responseresponse.addCookie(cookie);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } Cookie存储中文 Cookie不能直接存储中文如果需要存储则需要进行转码URL编码 //编码value URLDecoder.encode(value,UTF-8); //解码value URLDecoder.decode(value,UTF-8);例子 aServelt WebServlet(/aServlet) public class aServlet extends HttpServlet {Overrideprotected 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.responseresponse.addCookie(cookie);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } bServlet WebServlet(/bServlet) public class bServlet extends HttpServlet {Overrideprotected 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;}}}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 2.2 Session 2.2.1 Session基本使用 服务端会话跟踪技术将数据保存到服务端 JavaEE提供HttpSession接口来实现一次会话的多次请求间数据共享功能 使用: 获取Session对象 HttpSession session request.getSession();Session对象功能: void setAttribute(String name, Object o)存储数据到session域中Object getAttribute(String name)根据key获取值void removeAttribute(String name)根据key删除该键值对 例子 SessionDemo1 WebServlet(/demo1) public class SessionDemo1 extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//存储到Session中//1.获取Session对象HttpSession session request.getSession();//2.存储数据session.setAttribute(username,vanwot);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } SessionDemo2 WebServlet(/demo2) public class SessionDemo2 extends HttpServlet {Overrideprotected 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);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 2.2.2 Session原理 Session是基于Cookie实现的 2.2.3 Session使用细节 Session钝化、活化: 服务器重启后Session中的数据是否还在?钝化在服务器正常关闭后Tomcat会自动将Session数据写入硬盘的文件中活化再次启动服务器后从文件中加载数据到Session中 Seesion销毁: 默认情况下无操作30分钟自动销毁 配置在web-xml文件中 session-configsession-timeout30/session-timeout /session-config调用Session对象的invalidate()方法 2.3 小结 Cookie和Session都是完成一次会话内多次请求间数据共享的 其区别 存储位置Cookie是将数据存储在客户端Session将数据存储在服务端安全性Cookie不安全Session安全数据大小Cookie最大3KBSession无大小限制存储时间Cookie可以长期存储Session默认30分钟服务器性能Cookie不占服务器资源Session占用服务器资源 2.4 案例 2.4.1 用户登录 在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;}Overridepublic String toString() {return User{ id id , username username \ , password password \ };} } UserMapper.xml ?xml version1.0 encodingUTF-8 ? !DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd mapper namespacecom.itheima.mapper.UserMapper/mapperUserService: public class UserService {SqlSessionFactory factory SqlSessionFactoryUtils.getSqlSessionFactory();//登录方法public User login(String username,String password){//2.获取SqlSessionSqlSession sqlSession factory.openSession();//3.获取UserMapperUserMapper 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();Overrideprotected 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 {//登录失败//存储错误信息到requestrequest.setAttribute(login_msg,用户名或密码错误);//跳转到login.jsprequest.getRequestDispatcher(/login.jsp).forward(request,response);}}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 用户名和密码错误时 正确时 2.4.2 记住用户 2.4.2 - I 写cookie login.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/4Time: 23:39To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %!DOCTYPE html html langenheadmeta charsetUTF-8titlelogin/titlelink hrefcss/login.css relstylesheet /headbody div idloginDiv styleheight: 350pxform action/brand-demo/loginServlet idformh1 idloginMsgLOGIN IN/h1div iderrorMsg${login_msg}/divpUsername:input idusername nameusername typetext/ppPassword:input idpassword namepassword typepassword/ppRemember:input idremember nameremember value1 typecheckbox/pdiv idsubDivinput typesubmit classbutton valuelogin upinput typereset classbutton valueresetnbsp;nbsp;nbsp;a hrefregister.html没有账号/a/div/form /div/body /htmlloginService WebServlet(/loginServlet) public class loginServlet extends HttpServlet {private UserService service new UserService();Overrideprotected 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 {//登录失败//存储错误信息到requestrequest.setAttribute(login_msg,用户名或密码错误);//跳转到login.jsprequest.getRequestDispatcher(/login.jsp).forward(request,response);}}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 勾选登录成功后 2.4.2 - II 获取cookie 刷新后 login.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/4Time: 23:39To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %!DOCTYPE html html langenheadmeta charsetUTF-8titlelogin/titlelink hrefcss/login.css relstylesheet /headbody div idloginDiv styleheight: 350pxform action/brand-demo/loginServlet idformh1 idloginMsgLOGIN IN/h1div iderrorMsg${login_msg}/divpUsername:input idusername nameusername value${cookie.username.value} typetext/ppPassword:input idpassword namepassword value${cookie.password.value} typepassword/ppRemember:input idremember nameremember value1 typecheckbox/pdiv idsubDivinput typesubmit classbutton valuelogin upinput typereset classbutton valueresetnbsp;nbsp;nbsp;a hrefregister.html没有账号/a/div/form /div/body /html2.4.3 用户注册 register.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/5Time: 10:47To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %!DOCTYPE html html langen headmeta charsetUTF-8title欢迎注册/titlelink hrefcss/register.css relstylesheet /head bodydiv classform-divdiv classreg-contenth1欢迎注册/h1span已有帐号/span a hreflogin.html登录/a/divform idreg-form action/brand-demo/registerServlet methodposttabletrtd用户名/tdtd classinputsinput nameusername typetext idusernamebrspan idusername_err classerr_msg${register_msg}/span/td/trtrtd密码/tdtd classinputsinput namepassword typepassword idpasswordbrspan idpassword_err classerr_msg styledisplay: none密码格式有误/span/td/trtrtd验证码/tdtd classinputsinput namecheckCode typetext idcheckCodeimg srcimgs/a.jpga href# idchangeImg看不清/a/td/tr/tablediv classbuttonsinput value注 册 typesubmit idreg_btn/divbr classclear/form/div /body /htmlregisterService 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();Overrideprotected 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);}}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } login.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/4Time: 23:39To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %!DOCTYPE html html langenheadmeta charsetUTF-8titlelogin/titlelink hrefcss/login.css relstylesheet /headbody div idloginDiv styleheight: 350pxform action/brand-demo/loginServlet idformh1 idloginMsgLOGIN IN/h1div iderrorMsg${login_msg}${register_msg}/divpUsername:input idusername nameusername value${cookie.username.value} typetext/ppPassword:input idpassword namepassword value${cookie.password.value} typepassword/ppRemember:input idremember nameremember value1 typecheckbox/pdiv idsubDivinput typesubmit classbutton valuelogin upinput typereset classbutton valueresetnbsp;nbsp;nbsp;a hrefregister.jsp没有账号/a/div/form /div/body /html成功 失败 2.4.4 验证码 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);}}} } 验证码图片会跟随变化 register.jsp %--Created by IntelliJ IDEA.User: 19148Date: 2023/8/5Time: 10:47To change this template use File | Settings | File Templates. --% % page contentTypetext/html;charsetUTF-8 languagejava %!DOCTYPE html html langen headmeta charsetUTF-8title欢迎注册/titlelink hrefcss/register.css relstylesheet /head bodydiv classform-divdiv classreg-contenth1欢迎注册/h1span已有帐号/span a hreflogin.html登录/a/divform idreg-form action/brand-demo/registerServlet methodposttabletrtd用户名/tdtd classinputsinput nameusername typetext idusernamebrspan idusername_err classerr_msg${register_msg}/span/td/trtrtd密码/tdtd classinputsinput namepassword typepassword idpasswordbrspan idpassword_err classerr_msg styledisplay: none密码格式有误/span/td/trtrtd验证码/tdtd classinputsinput namecheckCode typetext idcheckCodeimg idcheckCodeImg src/brand-demo/checkCodeServleta href# idchangeImg看不清/a/td/tr/tablediv classbuttonsinput value注 册 typesubmit idreg_btn/divbr classclear/form/divscriptdocument.getElementById(changeImg).onclick function (){document.getElementById(checkCodeImg).src /brand-demo/checkCodeServlet?new Date().getMilliseconds();//加个参数避免同上面的路径缓存但是这个参数在多次点击下必须要永远不一样} /script /body /htmlcheckCodeServlet WebServlet(/checkCodeServlet) public class checkCodeServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ServletOutputStream os response.getOutputStream();String checkCode CheckCodeUtil.outputVerifyImage(100, 50, os, 4);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} } 2.4.4 - I 校验验证码 registerServlet WebServlet(/registerServlet) public class registerServlet extends HttpServlet {private UserService service new UserService();Overrideprotected 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);}}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);} }
http://www.yayakq.cn/news/4767/

相关文章:

  • 洛阳有做网站开发的吗曼奇立德原画培训多少钱
  • 网页 网站免费域名注册永久
  • 网站建设与维护 前台温州网站升级
  • 做网站用什么配置的vps南昌微信网站建设
  • 网站建设怎么谈长春建筑学院
  • 租房网站开发文献综述模板二次网站开发
  • 紫网站建设合肥做网站推荐 晨飞网络
  • 阿里云建站售前咨询门户资源分享网站模板
  • 查派网站建设wordpress分表分库插件
  • 网站打不开是怎么回事深圳做自适应网站
  • 想学习网站建设微信软文范例100字
  • 公司网站的栏目设置国内做的好的帽子网站
  • html中文美食网站模板公司主页格式
  • 厦门市城市建设档案馆的网站宾馆酒店网站建设方案
  • 外贸自助建站微商城运营的主要工作
  • 开网站做淘宝客烟台网站制作山海云
  • 天津网站排名方案wordpress做导航网站
  • 专业建站公司的业务内容江苏省质量建设厅网站
  • 聊城手机网站建设服务tcga做多因素分析的网站
  • centos 网站搭建为什么不建议做运维
  • 深圳专业营销网站济宁建设局官方网站
  • 一般的网站建设网站首页分辨率
  • com域名的网站vs2017做的网站如何发布
  • 大连网站建设详细流程刚刚发生在昆明的大事
  • 网站怎么做前台跟后台的接口上海ktv最新通知
  • 什么网站需要icp备案dedecms可以做什么网站
  • 网站框架搭建德阳小程序开发
  • 承德网站建设规划注销网站 取消接入
  • 个人 可以备案做分类信息网站吗连山网站建设
  • 一个网站可以绑定几个域名姬月直播