文章目录 1.Ajax验证用户名 1.程序框架图 2.修改MemberServlet 3.修改login.jsp 4.结果展示 2.Ajax判断验证码是否输入正确 1.修改MemberServlet 2.修改login.jsp 3.结果展示 3.Ajax添加购物车 1.程序框架图 2.修改CartServlet 2.修改index.jsp 3.解决问题—未登录直接添加购物车,ajax请求无法重定向到登录页面 1.解决方案 2.编写WebUtils判断是否是ajax请求 3.修改MemberAuthorization(过滤器) 4.修改index.jsp 4.结果展示 1.未登录添加购物车,跳转到登录页面 2.登录之后添加购物车,ajax局部刷新 4.上传更新家居图片 1.需求分析 2.程序框架图 3.修改FurnServlet 4.修改furn_update.jsp 1.样式 2.修改form的enctype 3.修改td 5.解决bug,写sql的时候注意映射,映射,映射!!!!!!!!(卡了2个小时才发现,醉了) 6.结果展示 1.点击上传图片 2.查看效果 3.点击修改家居,回到原页面 5.上传添加家居图片 1.修改FurnServlet 2.修改furn_add.jsp 1.前端样式与前面一样 2.修改form的enctype 3.修改td 3.结果展示
1.Ajax验证用户名
1.程序框架图
2.修改MemberServlet
public void isExistName ( HttpServletRequest req, HttpServletResponse resp) throws IOException { String username = req. getParameter ( "username" ) ; boolean res = memberService. isExistsUsername ( username) ; Map < String , Boolean > map = new HashMap < > ( ) ; map. put ( "isExist" , res) ; Gson gson = new Gson ( ) ; String json = gson. toJson ( map) ; resp. getWriter ( ) . write ( json) ; }
3.修改login.jsp
$ ( "#username" ) . blur ( function ( ) { var username = $ ( this ) . val ( ) ; $. getJSON ( "memberServlet" , { "action" : "isExistName" , "username" : username} , function ( data, status, xhr ) { if ( data. isExist) { $ ( "span.errorMsg" ) . text ( "用户名已存在!" ) ; } else { $ ( "span.errorMsg" ) . text ( "用户名可用!" ) ; } } ) } )
4.结果展示
2.Ajax判断验证码是否输入正确
1.修改MemberServlet
public void judgementCodeText ( HttpServletRequest req, HttpServletResponse resp) throws IOException { String codeText = req. getParameter ( "codeText" ) ; HttpSession session = req. getSession ( ) ; Object kaptchaSessionKey = session. getAttribute ( KAPTCHA_SESSION_KEY ) ; boolean res = false ; if ( kaptchaSessionKey != null && ( ( String ) kaptchaSessionKey) . equalsIgnoreCase ( codeText) ) { res = true ; } Map < String , Object > map = new HashMap < > ( ) ; map. put ( "judgementCodeText" , res) ; Gson gson = new Gson ( ) ; String json = gson. toJson ( map) ; resp. getWriter ( ) . write ( json) ; }
2.修改login.jsp
$( "#code" ) . blur ( function ( ) { var codeText = $( this ) . val ( ) ; $. getJSON ( "memberServlet" , { "action" : "judgementCodeText" , "codeText" : codeText} , function ( data, status, xhr) { if ( data. judgementCodeText) { $( "span.errorMsg" ) . text ( "验证码正确!" ) ; } else { $( "span.errorMsg" ) . text ( "验证码错误!" ) ; } } ) } )
3.结果展示
3.Ajax添加购物车
1.程序框架图
2.修改CartServlet
public void addItemByAjax ( HttpServletRequest req, HttpServletResponse resp) throws IOException { Integer cartItemId = DataUtils . parseInt ( req. getParameter ( "cartItemId" ) , - 1 ) ; String cartItemName = req. getParameter ( "cartItemName" ) ; BigDecimal cartItemPrice = new BigDecimal ( req. getParameter ( "cartItemPrice" ) ) ; Integer cartItemCount = 1 ; BigDecimal cartItemTotalPrice = null ; HttpSession session = req. getSession ( ) ; HashMap < Integer , CartItem > cart = ( HashMap < Integer , CartItem > ) session. getAttribute ( "Cart" ) ; if ( cart == null || cart. isEmpty ( ) ) { HashMap < Integer , CartItem > CartItemHashMap = new HashMap < > ( ) ; cartItemTotalPrice = cartItemPrice; CartItem cartItem = new CartItem ( cartItemId, cartItemName, cartItemPrice, cartItemCount, cartItemTotalPrice) ; CartItemHashMap . put ( cartItemId, cartItem) ; session. setAttribute ( "Cart" , CartItemHashMap ) ; session. setAttribute ( "totalNum" , cartItemCount) ; session. setAttribute ( "allPrice" , cartItemPrice) ; } else { if ( cart. containsKey ( cartItemId) ) { cartItemCount = cart. get ( cartItemId) . getCount ( ) + 1 ; } cartItemTotalPrice = cartItemPrice. multiply ( new BigDecimal ( cartItemCount) ) ; CartItem cartItem = new CartItem ( cartItemId, cartItemName, cartItemPrice, cartItemCount, cartItemTotalPrice) ; cart. put ( cartItemId, cartItem) ; CartItem . calTotalNumAndPrice ( cart, session) ; } Map < String , Object > map = new HashMap < > ( ) ; map. put ( "cartTotalCount" , ( Integer ) session. getAttribute ( "totalNum" ) ) ; Gson gson = new Gson ( ) ; String json = gson. toJson ( map) ; resp. getWriter ( ) . write ( json) ; }
2.修改index.jsp
3.解决问题—未登录直接添加购物车,ajax请求无法重定向到登录页面
1.解决方案
2.编写WebUtils判断是否是ajax请求
package com. sxs. furns. utils ; import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
public class WebUtils { public static boolean isAjaxRequest ( HttpServletRequest request, HttpServletResponse response) { return "XMLHttpRequest" . equals ( request. getHeader ( "X-Requested-With" ) ) ; }
}
3.修改MemberAuthorization(过滤器)
package com. sxs. furns. filter ; import com. google. gson. Gson ;
import com. sxs. furns. utils. WebUtils ; import javax. servlet. * ;
import javax. servlet. http. HttpServletRequest ;
import javax. servlet. http. HttpServletResponse ;
import javax. servlet. http. HttpSession ;
import java. io. IOException ;
import java. util. HashMap ;
import java. util. Map ;
public class MemberAuthorization implements Filter { @Override public void init ( FilterConfig filterConfig) throws ServletException { } @Override public void doFilter ( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException , ServletException { HttpSession session = ( ( HttpServletRequest ) servletRequest) . getSession ( ) ; Object username = session. getAttribute ( "username" ) ; Object admin = session. getAttribute ( "admin" ) ; if ( username != null || admin != null ) { filterChain. doFilter ( servletRequest, servletResponse) ; } else { if ( ! WebUtils . isAjaxRequest ( ( HttpServletRequest ) servletRequest, ( HttpServletResponse ) servletResponse) ) { ( ( HttpServletResponse ) servletResponse) . sendRedirect ( "/jiaju_mail/views/member/login.jsp" ) ; } Map < String , Object > map = new HashMap < > ( ) ; map. put ( "url" , "views/member/login.jsp" ) ; String json = new Gson ( ) . toJson ( map) ; servletResponse. getWriter ( ) . write ( json) ; } } @Override public void destroy ( ) { }
}
4.修改index.jsp
4.结果展示
1.未登录添加购物车,跳转到登录页面
2.登录之后添加购物车,ajax局部刷新
4.上传更新家居图片
1.需求分析
2.程序框架图
3.修改FurnServlet
public void updateFurn ( HttpServletRequest req, HttpServletResponse resp) throws IOException { if ( ServletFileUpload . isMultipartContent ( req) ) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory ( ) ; ServletFileUpload servletFileUpload = new ServletFileUpload ( diskFileItemFactory) ; servletFileUpload. setHeaderEncoding ( "utf-8" ) ; try { List < FileItem > list = servletFileUpload. parseRequest ( req) ; Furn furn = new Furn ( ) ; ArrayList < String > furnItems = new ArrayList < > ( ) ; for ( FileItem fileItem : list) { if ( fileItem. isFormField ( ) ) { String furnItem = fileItem. getString ( "utf-8" ) ; furnItems. add ( furnItem) ; } else { String name = UUID . randomUUID ( ) + "_" + System . currentTimeMillis ( ) + fileItem. getName ( ) ; String filePath = "/assets/images/product-image/" ; String realPath = super . getServletContext ( ) . getRealPath ( filePath) ; File file = new File ( realPath) ; if ( ! file. exists ( ) ) { file. mkdirs ( ) ; } String fileFullPath = realPath + name; fileItem. write ( new File ( fileFullPath) ) ; String imgPath = "assets/images/product-image/" + name; furn. setImgPath ( imgPath) ; if ( fileItem. getName ( ) == null || "" . equals ( fileItem. getName ( ) ) ) { Furn rawFurn = furnService. queryFurnById ( DataUtils . parseInt ( furnItems. get ( 0 ) , 0 ) ) ; imgPath = rawFurn. getImgPath ( ) ; } furn. setImgPath ( imgPath) ; } } furn. setId ( DataUtils . parseInt ( furnItems. get ( 0 ) , 0 ) ) ; furn. setName ( furnItems. get ( 1 ) ) ; furn. setMaker ( furnItems. get ( 2 ) ) ; furn. setPrice ( new BigDecimal ( furnItems. get ( 3 ) ) ) ; furn. setSales ( DataUtils . parseInt ( furnItems. get ( 4 ) , 0 ) ) ; furn. setStock ( DataUtils . parseInt ( furnItems. get ( 5 ) , 0 ) ) ; String pageNo = req. getParameter ( "pageNo" ) ; if ( furnService. updateFurn ( furn) ) { resp. sendRedirect ( super . getServletContext ( ) . getContextPath ( ) + "/manage/furnServlet?action=page&pageNo=" + pageNo) ; } else { System . out. println ( "更新失败" ) ; } } catch ( FileUploadException e) { throw new RuntimeException ( e) ; } catch ( Exception e) { throw new RuntimeException ( e) ; } } }
4.修改furn_update.jsp
1.样式
< style type= "text/css" > . table- content table { width: 100 % ; border- collapse: collapse; margin: 20 px 0 ; font- family: 'Segoe UI ', Tahoma , Geneva , Verdana , sans- serif; box- shadow: 0 4 px 8 px rgba ( 0 , 0 , 0 , 0.05 ) ; } . table- content th, . table- content td { text- align: left; padding: 12 px; border- bottom: 1 px solid #ddd; } . table- content th { background: linear- gradient ( 120d eg, #006 c70, #00 b2a9) ; color: #ffffff; text- shadow: 0 1 px 1 px rgba ( 0 , 0 , 0 , 0.2 ) ; } . table- content tr: hover { background- color: #f5f5f5; } . table- content . product- thumbnail { display: flex; flex- direction: column; align- items: center; position: relative; margin: 20 px auto; } . table- content input[ type= "file" ] { width: 200 px; height: 200 px; opacity: 0 ; position: absolute; cursor: pointer; z- index: 2 ; } . table- content img { border- radius: 50 % ; width: 150 px; height: 150 px; object- fit: cover; border: 2 px solid #009688 ; box- shadow: 0 2 px 4 px rgba ( 0 , 0 , 0 , 0.2 ) ; } . product- thumbnail:: before { content: '点击或拖拽上传图片'; position: absolute; width: 200 px; height: 200 px; background- color: rgba ( 0 , 150 , 136 , 0.9 ) ; color: white; display: flex; justify- content: center; align- items: center; text- align: center; border- radius: 50 % ; font- size: 16 px; transition: all 0.3 s ease; opacity: 0 ; z- index: 1 ; font- family: 'Segoe UI ', Tahoma , Geneva , Verdana , sans- serif; font- weight: 600 ; box- shadow: 0 2 px 4 px rgba ( 0 , 0 , 0 , 0.2 ) ; } . product- thumbnail: hover:: before { opacity: 1 ; } . table- content input[ type= "submit" ] { background: linear- gradient ( 120d eg, #31 B0D5 , #2196F 3 ) ; color: white; padding: 10 px 20 px; border: none; border- radius: 5 px; transition: background- color 0.3 s ease; cursor: pointer; font- size: 16 px; text- transform: uppercase; letter- spacing: 1 px; box- shadow: 0 2 px 4 px rgba ( 0 , 0 , 0 , 0.2 ) ; } . table- content input[ type= "submit" ] : hover { background- color: #2196F 3 ; } @media ( max- width: 768 px) { . product- thumbnail { width: 150 px; height: 150 px; } . product- thumbnail input[ type= "file" ] { width: 150 px; height: 150 px; } . product- thumbnail img { width: 150 px; height: 150 px; } . product- thumbnail:: before { width: 150 px; height: 150 px; font- size: 14 px; } . table- content input[ type= "submit" ] { padding: 8 px 16 px; } } < / style> < script type= "text/javascript" > function prev ( event) { var img = document. getElementById ( "prevView" ) ; var file = event. files[ 0 ] ; var reader = new FileReader ( ) ; reader. readAsDataURL ( file) ; reader. onload = function ( ) { img. setAttribute ( "src" , this . result) ; } } < / script>
2.修改form的enctype
3.修改td
5.解决bug,写sql的时候注意映射,映射,映射!!!(卡了2个小时才发现,醉了)
6.结果展示
1.点击上传图片
2.查看效果
3.点击修改家居,回到原页面
5.上传添加家居图片
1.修改FurnServlet
public void add ( HttpServletRequest req, HttpServletResponse resp) throws IOException , ServletException , InvocationTargetException , IllegalAccessException { if ( ServletFileUpload . isMultipartContent ( req) ) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory ( ) ; ServletFileUpload servletFileUpload = new ServletFileUpload ( diskFileItemFactory) ; servletFileUpload. setHeaderEncoding ( "utf-8" ) ; try { List < FileItem > list = servletFileUpload. parseRequest ( req) ; Furn furn = new Furn ( ) ; ArrayList < String > furnItems = new ArrayList < > ( ) ; for ( FileItem fileItem : list) { if ( fileItem. isFormField ( ) ) { String furnItem = fileItem. getString ( "utf-8" ) ; furnItems. add ( furnItem) ; } else { String name = UUID . randomUUID ( ) + "_" + System . currentTimeMillis ( ) + fileItem. getName ( ) ; String filePath = "/assets/images/product-image/" ; String realPath = super . getServletContext ( ) . getRealPath ( filePath) ; File file = new File ( realPath) ; if ( ! file. exists ( ) ) { file. mkdirs ( ) ; } String fileFullPath = realPath + name; fileItem. write ( new File ( fileFullPath) ) ; String imgPath = "assets/images/product-image/" + name; furn. setImgPath ( imgPath) ; if ( fileItem. getName ( ) == null || "" . equals ( fileItem. getName ( ) ) ) { imgPath = "assets/images/product-image/default.jpg" ; } furn. setImgPath ( imgPath) ; } } furn. setName ( furnItems. get ( 0 ) ) ; furn. setMaker ( furnItems. get ( 1 ) ) ; furn. setPrice ( new BigDecimal ( furnItems. get ( 2 ) ) ) ; furn. setSales ( DataUtils . parseInt ( furnItems. get ( 3 ) , 0 ) ) ; furn. setStock ( DataUtils . parseInt ( furnItems. get ( 4 ) , 0 ) ) ; String pageNo = req. getParameter ( "pageNo" ) ; if ( furnService. add ( furn) ) { resp. sendRedirect ( super . getServletContext ( ) . getContextPath ( ) + "/manage/furnServlet?action=page&pageNo=" + pageNo) ; } else { System . out. println ( "插入失败" ) ; } } catch ( FileUploadException e) { throw new RuntimeException ( e) ; } catch ( Exception e) { throw new RuntimeException ( e) ; } } }
2.修改furn_add.jsp
1.前端样式与前面一样
2.修改form的enctype
3.修改td
3.结果展示
1.准备添加家居
2.效果展示
3.添加之后