提供小企业网站建设,哪家公司做网站便宜,忘记wordpress的账号和密码忘记,黄冈论坛交友目录 一.JSP
二.EL表达式与JSTL标签
三.Cookie
四.Session
五.Filter
六. 登录CRUD:品牌增删改查案例
Demo一览
1.导包
2.构建包结构
3.创建数据库表tb_brand与user
4.创建实体类
5.mybatis的配置文件和logback配置文件
6.写接口
7.工具类#xff1a;生成图片与…目录 一.JSP
二.EL表达式与JSTL标签
三.Cookie
四.Session
五.Filter
六. 登录CRUD:品牌增删改查案例
Demo一览
1.导包
2.构建包结构
3.创建数据库表tb_brand与user
4.创建实体类
5.mybatis的配置文件和logback配置文件
6.写接口
7.工具类生成图片与SqlSession创建
8.写service方法 9.css
10. Filter过滤器限制必须登录 11.index.jsplogin.jsp与register.jsp 12.登录注册的Servlet 13.增删改查有关的jsp与Servlet 如今JSP已不再是热门的前端工具不建议深入学习而Cookie与Filter可以了解了解
通过maven建立web工程工程目录如下学习的内容为java代码以及两个jsp文件 pom需要导入的依赖 dependencygroupIdjavax.servlet/groupIdartifactIdjavax.servlet-api/artifactIdversion3.1.0/version/dependency!--使用jsp需要导入的包--dependencygroupIdjavax.servlet.jsp/groupIdartifactIdjsp-api/artifactIdversion2.2/version/dependency!--使用jstl标签需要导入的两个包--dependencygroupIdjstl/groupIdartifactIdjstl/artifactIdversion1.2/version/dependencydependencygroupIdtaglibs/groupIdartifactIdstandard/artifactIdversion1.1.2/version/dependency 一.JSP 1.JSPJavaServerPages既可以写html又能写java代码会把jsp文件转换为java文件并编译执行本质为Servlet服务资源
2.使用在jsp中引用别的类需要导包
3.在jsp文件中写java代码%xxx%
4.插入数据到前端代码上%xxx%index.jsp:
% page importorg.example.pojo.Brand %
% page importjava.util.List %
% page importjava.util.ArrayList %
% page contentTypetext/html;charsetUTF-8 languagejava %
html
body
%ListBrand brands new ArrayList();System.out.println(HelloJSP!);String strJSP!;
%
%你好str%br
/body
/html
IDE控制台与浏览器都会有输出 二.EL表达式与JSTL标签
案例获取servlet传过来的集合对象中的数据 EL表达式主要功能为获取在请求转发/cookie/session中存储的键为XXX的数据
JSTL用标签替换JSP上面的java代码如判断与循环
1.使用EL表达式开启需要声明%page isELIgnoredfalse %jsp文件中使用el表达式获取数据${xxx}
2.使用jstl标签需要1.pom文件导包2.引入taglib标签%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %3.常见的jstl标签c:if与c:forEach
3.cif标签指定判断条件test属性
4.cforeach标签指定1.遍历的数据items属性2.遍历数据中单个元素的名字var属性var.xxx会调用该对象的类中对应的getXxx方法3.遍历过程中的序号名varStatus属性varStatus的属性index从0开始计数|count从1开始计数4.指定遍历时设置var的开始结束步长beginendstep jstl.jsp
%page isELIgnoredfalse %
%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
% page contentTypetext/html;charsetUTF-8 languagejava %
html
headtitleTitle/title/head
body
c:if testtrueh3true/h3/c:if
c:if test${status1}h3${status}/h3/c:if
table border1 cellspacing0 width800c:forEach items${brands} varbrand varStatusstatustr aligncentertd${status.count}/tdtd${brand.brandName}/tdtd${brand.companyName}/tdtd${brand.ordered}/tdtd${brand.description}/tdtdc:if test${brand.status1}%启用%/c:ifc:if test${brand.status0}%禁用%/c:if/tdtda href修改 /aa href删除/a/td/tr/c:forEach
/table
hr
c:forEach begin1 end10 step1 varia href${i}/a
/c:forEach
/body
/htmlpublic class Brand {private Integer id;private String brandName;private String companyName;private Integer ordered;private String description;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 };}
}Servlet 把数据存储到request域中再转发到jsp资源中。 WebServlet(/jsp)
public class JSPDemo extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {ListBrand brands new ArrayList();brands.add(new Brand(1,三只松鼠,三只松鼠,100,三只松鼠好吃不上火,1));brands.add(new Brand(2,优衣库,优衣库,200,优衣库服适人生,0));brands.add(new Brand(3,小米,小米科技有限公司,1000,为发烧而生,1));request.setAttribute(status,1);request.setAttribute(brands,brands);request.getRequestDispatcher(/jstl.jsp).forward(request,response);}
} 三.Cookie 会话跟踪HTTP协议每次向浏览器请求数据时会将该请求视为新请求
服务器需要识别多次请求是否来自同一浏览器以便在多次请求间共享数据
1.查看cookies谷歌控制台application
2.Cookies的实现基于HTTP协议响应头请求头Session基于cookie实现发送sessionId
3.发送cookie以键值对的形式创建cookie使用响应对象添加cookie
4.设置cookie对象的在浏览器中的存活时间单位为秒cookie默认为浏览器关闭cookie消失
5.接收cookie通过请求对象接收所有cookie数组并遍历 WebServlet(/cookie)
public class CookieDemo extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie cookie new Cookie(username, zhangsan);cookie.setMaxAge(60);response.addCookie(cookie);Cookie[] cookies request.getCookies();for (Cookie c : cookies) {System.out.println(c.getName() : c.getValue());}}
}访问目标路径两次得到如下结果 四.Session 1.存Session通过请求对象存储数据到Session中
2.获取session对象中对应键的值,后移除键值对
3.在web.xml中设置session存活时间 WebServlet(/session)
public class SessionDemo extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response){HttpSession sessionrequest.getSession();session.setAttribute(username,zhangsan);System.out.println(session.getAttribute(username));session.removeAttribute(username);}
}
web.xml:
!DOCTYPE web-app PUBLIC-//Sun Microsystems, Inc.//DTD Web Application 2.3//ENhttp://java.sun.com/dtd/web-app_2_3.dtd web-appdisplay-nameArchetype Created Web Application/display-namesession-config!--单位分钟--session-timeout1/session-timeout/session-config
/web-app 五.Filter
用于拦截访问的资源
//拦截资源目录和WebServlet一样的写法
WebFilter(/session)
public class FilterDemo implements Filter {public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println(拦截资源后放行......);filterChain.doFilter(servletRequest,servletResponse);System.out.println(放行后输出......);}public void init(FilterConfig filterConfig) {}public void destroy() {}
} 六. 登录CRUD:品牌增删改查案例
Demo一览 1.导包 dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion5.1.32/version/dependencydependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.5/version/dependencydependencygroupIdjavax.servlet/groupIdartifactIdjavax.servlet-api/artifactIdversion3.1.0/versionscopeprovided/scope/dependencydependencygroupIdjavax.servlet.jsp/groupIdartifactIdjsp-api/artifactIdversion2.2/versionscopeprovided/scope/dependencydependencygroupIdjstl/groupIdartifactIdjstl/artifactIdversion1.2/version/dependencydependencygroupIdtaglibs/groupIdartifactIdstandard/artifactIdversion1.1.2/version/dependency 2.构建包结构 3.创建数据库表tb_brand与user
4.创建实体类
public class Brand {private Integer id;private String brandName;private String companyName;private Integer ordered;private String description;private Integer status;public Brand() {}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 };}
}public class User {private Integer id;private String username;private String password;public User() {}public User(String username, String password) {this.username username;this.password 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 \ };}
} 5.mybatis的配置文件和logback配置文件 mybatis.config ?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttps://mybatis.org/dtd/mybatis-3-config.dtd
configurationtypeAliasespackage nameorg.example.pojo//typeAliasesenvironments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLEDproperty namedriver valuecom.mysql.jdbc.Driver/property nameurl valuejdbc:mysql:///db1?useSSLfalse/property nameusername valueroot/property namepassword value123456//dataSource/environment/environmentsmapperspackage nameorg.example.mapper//mappers
/configuration logback.xml ?xml version1.0 encodingUTF-8?
configurationappender nameConsole classch.qos.logback.core.ConsoleAppenderencoderpattern[%level] %boldGreen(%logger{15}) - %msg %n/pattern/encoder/appenderroot levelDEBUGappender-ref refConsole//root
/configuration BrandMapper.xml ?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespaceorg.example.mapper.BrandMapperresultMap idbrandResultMap typeBrandid columnid propertyid/result columnbrand_name propertybrandName/result columncompany_name propertycompanyName//resultMap
/mapper UserMapper.xml ?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespaceorg.example.mapper.UserMapper
/mapper6.写接口
public interface BrandMapper {ResultMap(brandResultMap)Select(select * from tb_brand)ListBrand selectAll();Insert(insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status}))void add(Brand brand);ResultMap(brandResultMap)Select(select * from tb_brand where id#{id})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);Delete(delete from tb_brand where id#{id})void deleteById(int id);
}public interface UserMapper {Select(select * from user where username #{username} and password #{password})User select(Param(username) String username, Param(password) String password);Select(select * from user where username #{username})User selectByUsername(String username);Insert(insert into user values(null,#{username},#{password}))void add(User user);
}7.工具类生成图片与SqlSession创建
public class CheckCodeUtil {//生成验证码工具类public static final String VERIFY_CODES 123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ;private static Random random new Random();public static void main(String[] args) throws Exception{OutputStream fosnew FileOutputStream(D:\\IDEACode\\demo2\\Web\\web-demo4-brandDemo\\src\\main\\webapp\\imgs\\a.jpg);String checkCodeCheckCodeUtil.outputVerifyImage(100,50,fos,4);System.out.println(checkCode);}//输出随机验证码图片流,并返回验证码值一般传入输出流响应response页面端Web项目用的较多//图片宽高输出流与数据长度//返回验证码数据public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {String verifyCode generateVerifyCode(verifySize);outputImage(w, h, os, verifyCode);return verifyCode;}//使用系统默认字符源生成验证码public static String generateVerifyCode(int verifySize) {return generateVerifyCode(verifySize, VERIFY_CODES);}//使用指定源生成验证码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();}//生成随机验证码文件,并返回验证码值 (生成图片形式用的较少)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;}//生成指定验证码图像文件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;}}//输出指定验证码图片流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);}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);}}}
}
public class SqlSessionFactoryUtil {static SqlSessionFactory sqlSessionFactory;static { try {sqlSessionFactory new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream(mybatis-config.xml));}catch (Exception e){e.printStackTrace();}}public static SqlSessionFactory getssf(){return sqlSessionFactory;}
}8.写service方法
public class BrandService {SqlSessionFactory sqlSessionFactory SqlSessionFactoryUtil.getssf();public ListBrand selectAll(){SqlSession sqlSessionsqlSessionFactory.openSession(true);BrandMapper mapper sqlSession.getMapper(BrandMapper.class);ListBrand brandsmapper.selectAll();sqlSession.close();return brands;}public void add(Brand brand){SqlSession sqlSessionsqlSessionFactory.openSession(true);BrandMapper mapper sqlSession.getMapper(BrandMapper.class);mapper.add(brand);sqlSession.close();}public Brand selectById(int id){//更新数据时回显数据SqlSession sqlSessionsqlSessionFactory.openSession(true);BrandMapper mapper sqlSession.getMapper(BrandMapper.class);Brand brandmapper.selectById(id);sqlSession.close();return brand;}public void update(Brand brand){SqlSession sqlSessionsqlSessionFactory.openSession(true);BrandMapper mapper sqlSession.getMapper(BrandMapper.class);mapper.update(brand);sqlSession.close();}public void deleteById(int id){SqlSession sqlSessionsqlSessionFactory.openSession(true);BrandMapper mapper sqlSession.getMapper(BrandMapper.class);mapper.deleteById(id);sqlSession.close();}
}
public class UserService {SqlSessionFactory sqlSessionFactory SqlSessionFactoryUtil.getssf();public User login(String username, String password){//登录需要设置cookie给浏览器需要返回用户对象SqlSession sqlSessionsqlSessionFactory.openSession(true);UserMapper mappersqlSession.getMapper(UserMapper.class);User usermapper.select(username,password);sqlSession.close();return user;}public boolean register(User user){SqlSession sqlSessionsqlSessionFactory.openSession(true);UserMapper mappersqlSession.getMapper(UserMapper.class);User umapper.selectByUsername(user.getUsername());if(unull){mapper.add(user);}sqlSession.close();return unull;}
}9.css
login.css
* {margin: 0;padding: 0;
}html {height: 100%;width: 100%;overflow: hidden;margin: 0;padding: 0;background: url(../imgs/Desert1.jpg) no-repeat 0px 0px;background-repeat: no-repeat;background-size: 100% 100%;-moz-background-size: 100% 100%;
}body {display: flex;align-items: center;justify-content: center;height: 100%;
}#loginDiv {width: 37%;display: flex;justify-content: center;align-items: center;height: 380px;background-color: rgba(75, 81, 95, 0.3);box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);border-radius: 5px;
}#name_trip {margin-left: 50px;color: red;
}p {margin-top: 30px;margin-left: 20px;color: azure;
}#remember{margin-left: 15px;border-radius: 5px;border-style: hidden;background-color: rgba(216, 191, 216, 0.5);outline: none;padding-left: 10px;height: 20px;width: 20px;
}
#username{width: 200px;margin-left: 15px;border-radius: 5px;border-style: hidden;height: 30px;background-color: rgba(216, 191, 216, 0.5);outline: none;color: #f0edf3;padding-left: 10px;
}
#password{width: 202px;margin-left: 15px;border-radius: 5px;border-style: hidden;height: 30px;background-color: rgba(216, 191, 216, 0.5);outline: none;color: #f0edf3;padding-left: 10px;
}
.button {border-color: cornsilk;background-color: rgba(100, 149, 237, .7);color: aliceblue;border-style: hidden;border-radius: 5px;width: 100px;height: 31px;font-size: 16px;
}#subDiv {text-align: center;margin-top: 30px;
}
#loginMsg{text-align: center;color: aliceblue;
}
#errorMsg{text-align: center;color:red;
}
register.css
* {margin: 0;padding: 0;list-style-type: none;
}
.reg-content{padding: 30px;margin: 3px;
}
a, img {border: 0;
}body {background-image: url(../imgs/reg_bg_min.jpg) ;text-align: center;
}table {border-collapse: collapse;border-spacing: 0;
}td, th {padding: 0;height: 90px;}
.inputs{vertical-align: top;
}.clear {clear: both;
}.clear:before, .clear:after {content: ;display: table;
}.clear:after {clear: both;
}.form-div {background-color: rgba(255, 255, 255, 0.27);border-radius: 10px;border: 1px solid #aaa;width: 424px;margin-top: 150px;margin-left:1050px;padding: 30px 0 20px 0px;font-size: 16px;box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);text-align: left;
}.form-div input[typetext], .form-div input[typepassword], .form-div input[typeemail] {width: 268px;margin: 10px;line-height: 20px;font-size: 16px;
}.form-div input[typecheckbox] {margin: 20px 0 20px 10px;
}.form-div input[typebutton], .form-div input[typesubmit] {margin: 10px 20px 0 0;
}.form-div table {margin: 0 auto;text-align: right;color: rgba(64, 64, 64, 1.00);
}.form-div table img {vertical-align: middle;margin: 0 0 5px 0;
}.footer {color: rgba(64, 64, 64, 1.00);font-size: 12px;margin-top: 30px;
}.form-div .buttons {float: right;
}input[typetext], input[typepassword], input[typeemail] {border-radius: 8px;box-shadow: inset 0 2px 5px #eee;padding: 10px;border: 1px solid #D4D4D4;color: #333333;margin-top: 5px;
}input[typetext]:focus, input[typepassword]:focus, input[typeemail]:focus {border: 1px solid #50afeb;outline: none;
}input[typebutton], input[typesubmit] {padding: 7px 15px;background-color: #3c6db0;text-align: center;border-radius: 5px;overflow: hidden;min-width: 80px;border: none;color: #FFF;box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
}input[typebutton]:hover, input[typesubmit]:hover {background-color: #5a88c8;
}input[typebutton]:active, input[typesubmit]:active {background-color: #5a88c8;
}
.err_msg{color: red;padding-right: 170px;
}
#password_err,#tel_err{padding-right: 195px;
}#reg_btn{margin-right:50px; width: 285px; height: 45px; margin-top:20px;
}#checkCode{width: 100px;
}#changeImg{color: aqua;
} 10. Filter过滤器限制必须登录 设置放行资源:通过获取的路径来判断是否包含目标字符串
检测用户是否登录:判断session里面是否有user WebFilter(/*)
public class LoginFilter implements Filter {Overridepublic void init(FilterConfig filterConfig) throws ServletException {}Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {HttpServletRequest req (HttpServletRequest) request;String[] urls {/css/, /img/, /login.jsp, /register.jsp, /loginServlet, registerServlet, /checkCodeServlet};String urireq.getRequestURI();for (String u : urls) {if (uri.contains(u)||/web_demo4_brandDemo_war/.equals(uri)) {System.out.println([DEBUG]请求服务器资源...uri);chain.doFilter(request, response);return;}}if (req.getSession().getAttribute(user) null) {System.out.println([DEBUG]用户未登录访问数据资源,携带提示信息返回登录界面...);req.setAttribute(login_msg, 您尚未登陆);req.getRequestDispatcher(/login.jsp).forward(request, response);return;}System.out.println([DEBUG]用户合法访问服务器资源...uri);chain.doFilter(request, response);}Overridepublic void destroy() {}
}11.index.jsplogin.jsp与register.jsp
% page contentTypetext/html;charsetUTF-8 languagejava %
html
body
/body
scriptlocation.href/web_demo4_brandDemo_war/login.jsp
/script
/html
% page contentTypetext/html;charsetUTF-8 languagejava %
%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
%page isELIgnoredfalse %
!DOCTYPE html
html langenheadmeta charsetUTF-8titlelogin/titlelink hrefcss/login.css relstylesheet
/headbodydiv idloginDiv styleheight: 350pxform action/web_demo4_brandDemo_war/loginServlet idform methodposth1 idloginMsgLOGIN IN/h1%--el表达式获取请求转发中的提示信息--%div iderrorMsg${login_msg}${register_msg}/div%--el表达式也可以获取cookie--%pUsername:input idusername nameusername typetext value${cookie.username.value}/ppPassword:input idpassword namepassword typepassword value${cookie.password.value}/ppRemember:input idremember nameremember valueon typecheckbox/pdiv idsubDivinput typesubmit classbutton valuelogin upinput typereset classbutton valuereseta hrefregister.jsp没有账号/a/div/form/div
/body/html
% page contentTypetext/html;charsetUTF-8 languagejava %
%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
%page isELIgnoredfalse %
!DOCTYPE html
html langenheadmeta charsetUTF-8title欢迎注册/titlelink hrefcss/register.css relstylesheet
/headbodydiv classform-divdiv classreg-contenth1欢迎注册/h1span已有帐号/span a hreflogin.jsp登录/a/divform idreg-form action/web_demo4_brandDemo_war/registerServlet methodposttabletrtd用户名/tdtd classinputsinput nameusername typetext idusernamebrspan idusername_exi classerr_msg styledisplay: none用户已存在/spanbrspan 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 idcheckCode%--访问图片生成服务请求图片资源--%img idcheckImg src/web_demo4_brandDemo_war/checkCodeServleta href idchangeImg看不清/a/td/tr/tablediv classbuttonsinput value注 册 typesubmit idreg_btn/divbr classclear/form/div
/body
script//在这里如果不加后面的问号与数据,点击图片不会改变changeImg function () {document.getElementById(checkImg).src /web_demo4_brandDemo_war/checkCodeServlet? new Date().getMilliseconds();}document.getElementById(changeImg).onclick changeImgdocument.getElementById(checkImg).onclick changeImg
/script/html 12.登录注册的Servlet 生成图片通过响应数据的输出流生成图片,并且把验证码设置为Session的键值对 WebServlet(/checkCodeServlet)
public class CheckCodeServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {String checkCode CheckCodeUtil.outputVerifyImage(100,50,response.getOutputStream(),4);System.out.println([DEBUG]验证码为:checkCode);System.out.println([DEBUG]返回生成的图片...);request.getSession().setAttribute(checkCodeGen,checkCode);}Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doGet(request, response);}
}
WebServlet(/loginServlet)
public class LoginServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding(UTF-8);String usernamerequest.getParameter(username);String passwordrequest.getParameter(password);User usernew UserService().login(username,password);if (usernull){System.out.println([DEBUG]登录失败,携带提示消息登陆界面...);request.setAttribute(login_msg,用户名密码错误);request.getRequestDispatcher(/login.jsp).forward(request,response);return;}System.out.println([DEBUG]登录成功,添加session,跳转到查询界面...);if(on.equals(request.getParameter(remember))) {System.out.println([DEBUG]用户点击了记住我,添加cookie...);Cookie[] cookies {new Cookie(username,username),new Cookie(password,username)};for (Cookie cookie : cookies) {cookie.setMaxAge(60);response.addCookie(cookie);}}request.getSession().setAttribute(user,user);response.sendRedirect(request.getContextPath()/selectAllServlet);}Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}
}
WebServlet(/registerServlet)
public class RegisterServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding(utf-8);if(!((String)request.getSession().getAttribute(checkCodeGen)).equalsIgnoreCase(request.getParameter(checkCode))){System.out.println([DEBUG]验证码错误,携带提示信息返回注册界面...);request.setAttribute(register_msg,验证码错误);request.getRequestDispatcher(/register.jsp).forward(request,response);return;}boolean flagnew UserService().register(new User(request.getParameter(username),request.getParameter(password)));if(flag){System.out.println([DEBUG]用户注册成功,携带提示消息返回登录界面...);request.setAttribute(register_msg,注册成功请登录);request.getRequestDispatcher(/login.jsp).forward(request,response);}else {System.out.println([DEBUG]用户登录失败,携带提示消息返回注册界面...);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);}
}13.增删改查有关的jsp与Servlet
brand.jsp
% page contentTypetext/html;charsetUTF-8 languagejava %
%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
%page isELIgnoredfalse %
!DOCTYPE html
html langenheadmeta charsetUTF-8titleTitle/title
/headbodyh2${user.username},欢迎您/h2brinput typebutton value新增 idaddbrhrtable border1 cellspacing0 width800trth序号/thth品牌名称/thth企业名称/thth排序/thth品牌介绍/thth状态/thth操作/th/trc:forEach items${brands} varbrand varStatusstatustr aligncentertd${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.status0}td%禁用%/td/c:iftda href/web_demo4_brandDemo_war/selectByIdServlet?id${brand.id}修改/aa href/web_demo4_brandDemo_war/deleteServlet?id${brand.id}删除/a/td/tr/c:forEach/table
/body
scriptdocument.getElementById(add).onclick function () {location.href /web_demo4_brandDemo_war/addBrand.jsp;}
/script
/html
WebServlet(/selectAllServlet)
public class SelectAllServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println([DEBUG]查询并显示所有数据...);request.setAttribute(brands,new BrandService().selectAll());request.getRequestDispatcher(/brand.jsp).forward(request,response);}//这里的doPost在jsp中不访问但最好写,如果别的资源使用post方式请求转发Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}
}
WebServlet(/deleteServlet)
public class DeleteServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println([DEBUG]用户选择删除数据...);req.setCharacterEncoding(UTF-8);new BrandService().deleteById(Integer.parseInt(req.getParameter(id)));;resp.sendRedirect(/web_demo4_brandDemo_war/selectAllServlet);}Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}
} addBrand.jsp
% page contentTypetext/html;charsetUTF-8 languagejava%
!DOCTYPE html
html langenheadmeta charsetUTF-8title添加品牌/title
/headbodyh3添加品牌/h3form action/web_demo4_brandDemo_war/addServlet methodpost品牌名称input namebrandName value淘宝br企业名称input namecompanyName value阿里巴巴br排序状况input nameordered value10br描述信息textarea rows5 cols20 namedescription阿里巴巴/textareabr状态信息input typeradio namestatus value0 checked禁用input typeradio namestatus value1启用brinput typesubmit value提交/form
/body/html
WebServlet(/addServlet)
public class AddServlet extends HttpServlet {Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println([DEBUG]用户添加数据...);req.setCharacterEncoding(UTF-8);new BrandService().add(new Brand(null,req.getParameter(brandName),req.getParameter(brandName),Integer.parseInt(req.getParameter(ordered)),req.getParameter(description),Integer.parseInt(req.getParameter(status))));resp.sendRedirect(/web_demo4_brandDemo_war/selectAllServlet);}Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}
} update.jsp
%page contentTypetext/html;charsetUTF-8 languagejava %
%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
%page isELIgnoredfalse %
!DOCTYPEhtml
html langenheadmeta charsetUTF-8title修改品牌/title
/headbody
h3修改品牌/h3
form action/web_demo4_brandDemo_war/addServlet methodpost%--隐藏id--%input nameid value${brand.id} typehidden品牌名称input namebrandName value${brand.brandName}br企业名称input namecompanyName value${brand.companyName}br排序状况input nameordered value${brand.ordered}br描述信息textarea rows5 cols20 namedescription${brand.description}/textareabr状态信息input typeradio namestatus value0 c:if test${brand.status0}checked/c:if禁用input typeradio namestatus value1 c:if test${brand.status1}checked/c:if启用brinput typesubmit value提交
/form
/body/html
%page contentTypetext/html;charsetUTF-8 languagejava %
%taglib prefixc urihttp://java.sun.com/jsp/jstl/core %
%page isELIgnoredfalse %
!DOCTYPEhtml
html langenheadmeta charsetUTF-8title修改品牌/title
/headbody
h3修改品牌/h3
form action/web_demo4_brandDemo_war/updateServlet methodpost%--隐藏id--%input nameid value${brand.id} typehidden品牌名称input namebrandName value${brand.brandName}br企业名称input namecompanyName value${brand.companyName}br排序状况input nameordered value${brand.ordered}br描述信息textarea rows5 cols20 namedescription${brand.description}/textareabr状态信息input typeradio namestatus value0 c:if test${brand.status0}checked/c:if禁用input typeradio namestatus value1 c:if test${brand.status1}checked/c:if启用brinput typesubmit value提交
/form
/body/html