spring mvc +easy ui +Mybatis 录入数据
1、itemsEasyui.jsp
应用到的插件及知识点:日期控件My97 ,图片本地预览函数PreviewImage()
(1)easy ui 的模态窗口使用时,要指定DIV的属性 data-options="modal:true,closed:true,iconCls:'icon-save'" 主要是modal:true,需要展示时使用 jQuery("#itemsDiv").window('open'); 打开指定的div
(2) 利用FormData对象
,我们可以通过JavaScript用一些键值对来模拟一系列表单控件,.比起普通的ajax,使用FormData
的最大优点就是我们可以异步上传一个二进制文件. <form id="itemsForm" enctype="multipart/form-data" style="padding:10px 20px 10px 40px;">本例中因为要上传一个图片,序列化语句不能传递。$("#itemsForm").serializeArray()在有上传文件的格式时不能用;采用了ajax方法异步上传
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var formData = new FormData($( "#itemsForm" )[0]); 79 $.ajax({ 80 url: 'addOrUpdate' , 81 type: 'POST' , 82 data: formData, 83 async: false , 84 cache: false , 85 contentType: false , 86 processData: false , 87 success: function (returndata) { 88 $( '#itemsDiv' ).window( 'close' ); 89 $( '#itemsTable' ).datagrid( 'reload' ); 90 $.messager.alert( '提示' ,returndata.mes, 'info' ); 91 } 92 }); |
1 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 <%@include file="/taglibs.jsp" %> 3 <html> 4 <head> 5 <script type="text/javascript"> 6 jQuery(function($){ 7 $('#itemsTable').datagrid({ 8 title:'用户列表', //标题 9 method:'post', 10 iconCls:'icon-edit', //图标 11 singleSelect:false, //多选 12 //height:560, //高度 13 fitColumns: true, //自动调整各列,用了这个属性,下面各列的宽度值就只是一个比例。 14 striped: true, //奇偶行颜色不同 15 collapsible:true,//可折叠 16 url:"queryItemsMap", //数据来源 17 sortName: 'name', //排序的列 18 sortOrder: 'desc', //倒序 19 remoteSort: true, //服务器端排序 20 idField:'id', //主键字段 21 queryParams:{}, //查询条件 22 pagination:true, //显示分页 23 rownumbers:true, //显示行号 24 columns:[[ 25 {field:'ck',checkbox:true,width:2}, //显示复选框 26 {field:'name',title:'名称',width:20,sortable:true, 27 formatter:function(value,row,index){return row.name;} //需要formatter一下才能显示正确的数据 28 }, 29 {field:'price',title:'价格',width:20,sortable:true, 30 formatter:function(value,row,index){return row.price;} 31 }, 32 {field:'createtime',title:'生产日期',width:30,sortable:true, 33 formatter:function(value,row,index) 34 { 35 var createtime = new Date(value); 36 return createtime.toLocaleString(); 37 //return row.createtime; 38 } 39 }, 40 {field:'detail',title:'说明',width:30,sortable:true, 41 formatter:function(value,row,index){ 42 return row.detail; //该列的值是deptId,显示的是deptName 43 } 44 } 45 ]], 46 toolbar:[{ 47 text:'新增', 48 iconCls:'icon-add', 49 handler:function(){ 50 jQuery("#itemsDiv").window('open'); 51 } 52 },'-',{ 53 text:'更新', 54 iconCls:'icon-edit', 55 handler:function(){ 56 updaterow(); 57 } 58 },'-',{ 59 text:'删除', 60 iconCls:'icon-remove', 61 handler:function(){ 62 deleterow(); 63 } 64 },'-'], 65 onLoadSuccess:function(){ 66 $('#itemsTable').datagrid('clearSelections'); //一定要加上这一句,要不然datagrid会记住之前的选择状态,删除时会出问题 67 } 68 }); 69 }); 70 71 //新增商品 72 function addItems(){ 73 var r = $('#itemsForm').form('validate'); 74 75 if(!r) { 76 return false; 77 } 78 var formData = new FormData($( "#itemsForm" )[0]); 79 $.ajax({ 80 url: 'addOrUpdate' , 81 type: 'POST', 82 data: formData, 83 async: false, 84 cache: false, 85 contentType: false, 86 processData: false, 87 success: function (returndata) { 88 $('#itemsDiv').window('close'); 89 $('#itemsTable').datagrid('reload'); 90 $.messager.alert('提示',returndata.mes,'info'); 91 } 92 }); 93 } 94 95 //弹出窗口 96 function showWindow(options){ 97 jQuery("#itemsDiv").window(options); 98 } 99 //关闭弹出窗口 100 function closeWindow(){ 101 $("#itemsDiv").window('close'); 102 } 103 //预览本地照片 104 function change_photo(){ 105 PreviewImage($("input[name='items_pic']")[0], 'Img', 'Imgdiv'); 106 } 107 //预览本机照片 来自网上 108 function PreviewImage(fileObj,imgPreviewId,divPreviewId){ 109 var allowExtention=".jpg,.bmp,.gif,.png";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value; 110 var extention=fileObj.value.substring(fileObj.value.lastIndexOf(".")+1).toLowerCase(); 111 var browserVersion= window.navigator.userAgent.toUpperCase(); 112 if(allowExtention.indexOf(extention)>-1){ 113 if(fileObj.files){//HTML5实现预览,兼容chrome、火狐7+等 114 if(window.FileReader){ 115 var reader = new FileReader(); 116 reader.onload = function(e){ 117 document.getElementById(imgPreviewId).setAttribute("src",e.target.result); 118 } 119 reader.readAsDataURL(fileObj.files[0]); 120 }else if(browserVersion.indexOf("SAFARI")>-1){ 121 alert("不支持Safari6.0以下浏览器的图片预览!"); 122 } 123 }else if (browserVersion.indexOf("MSIE")>-1){ 124 if(browserVersion.indexOf("MSIE 6")>-1){//ie6 125 document.getElementById(imgPreviewId).setAttribute("src",fileObj.value); 126 }else{//ie[7-9] 127 fileObj.select(); 128 if(browserVersion.indexOf("MSIE 9")>-1) 129 fileObj.blur();//不加上document.selection.createRange().text在ie9会拒绝访问 130 var newPreview =document.getElementById(divPreviewId+"New"); 131 if(newPreview==null){ 132 newPreview =document.createElement("div"); 133 newPreview.setAttribute("id",divPreviewId+"New"); 134 newPreview.style.width = document.getElementById(imgPreviewId).width+"px"; 135 newPreview.style.height = document.getElementById(imgPreviewId).height+"px"; 136 newPreview.style.border="solid 1px #d2e2e2"; 137 } 138 newPreview.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')"; 139 var tempDivPreview=document.getElementById(divPreviewId); 140 tempDivPreview.parentNode.insertBefore(newPreview,tempDivPreview); 141 tempDivPreview.style.display="none"; 142 } 143 }else if(browserVersion.indexOf("FIREFOX")>-1){//firefox 144 var firefoxVersion= parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]); 145 if(firefoxVersion<7){//firefox7以下版本 146 document.getElementById(imgPreviewId).setAttribute("src",fileObj.files[0].getAsDataURL()); 147 }else{//firefox7.0+ 148 document.getElementById(imgPreviewId).setAttribute("src",window.URL.createObjectURL(fileObj.files[0])); 149 } 150 }else{ 151 document.getElementById(imgPreviewId).setAttribute("src",fileObj.value); 152 } 153 }else{ 154 alert("仅支持"+allowExtention+"为后缀名的文件!"); 155 fileObj.value="";//清空选中文件 156 if(browserVersion.indexOf("MSIE")>-1){ 157 fileObj.select(); 158 document.selection.clear(); 159 } 160 fileObj.outerHTML=fileObj.outerHTML; 161 } 162 } 163 164 </script> 165 </head> 166 167 <body> 168 <div style="padding:10" id="tabdiv"> 169 <table id="itemsTable"></table> 170 </div> 171 <!-- model 模态弹出窗口 --> 172 173 <div id="itemsDiv" class="easyui-window" data-options="modal:true,closed:true,iconCls:'icon-save'" title="商品管理" style="width:350px;height:300px;"> 174 <form id="itemsForm" enctype="multipart/form-data" style="padding:10px 20px 10px 40px;"> 175 <p>名称: <input name="name" type="text" class="easyui-validatebox" required="true"></p> 176 <p>规格: <input name="detail" type="text" type="text" class="easyui-validatebox" required="true" ></p> 177 <p>价格: <input name="price" type="text" type="text" class="easyui-validatebox" required="true"></p> 178 <p>日期: <input name="createtime" type="text" class="Wdate" onClick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss' })"></p> 179 <p>照片:<input class="easyui-filebox" data-options='onChange:change_photo' id="file_upload" name="items_pic"/><br/> 180 <div id="Imgdiv"> 181 <img id="Img" width="200px" height="200px"/> 182 </div> 183 <div style="padding:5px;text-align:center;"> 184 <a href="#" class="easyui-linkbutton" icon="icon-ok" onclick="addItems()">确认</a> 185 <a href="#" class="easyui-linkbutton" icon="icon-cancel">返回</a> 186 </div> 187 </form> 188 </div> 189 <!-- model 模态弹出窗口 结束--> 190 191 </body> 192 </html>
2、itemsController.java
1 package com.lr.controller; 2 3 import java.io.File; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import java.util.UUID; 8 9 import javax.servlet.http.HttpServletRequest; 10 11 import org.springframework.beans.factory.annotation.Autowired; 12 import org.springframework.stereotype.Controller; 13 import org.springframework.ui.Model; 14 import org.springframework.validation.BindingResult; 15 import org.springframework.validation.ObjectError; 16 import org.springframework.validation.annotation.Validated; 17 import org.springframework.web.bind.annotation.ModelAttribute; 18 import org.springframework.web.bind.annotation.PathVariable; 19 import org.springframework.web.bind.annotation.RequestMapping; 20 import org.springframework.web.bind.annotation.RequestMethod; 21 import org.springframework.web.bind.annotation.RequestParam; 22 import org.springframework.web.bind.annotation.ResponseBody; 23 import org.springframework.web.multipart.MultipartFile; 24 import org.springframework.web.servlet.ModelAndView; 25 26 import com.lr.controller.validation.ValidGroup1; 27 import com.lr.po.ItemsCustom; 28 import com.lr.po.ItemsQueryVo; 29 import com.lr.service.ItemsService; 30 31 /** 32 * 33 * <p> 34 * Title: ItemsController </p> 35 * <p> Description:商品的controller </p> 36 * @date 2015-4-13下午4:03:35 37 * @version 1.0 38 */ 39 @Controller 40 //为了对url进行分类管理 ,可以在这里定义根路径,最终访问url是根路径+子路径 41 //比如:商品列表:/items/queryItems.action 42 @RequestMapping("/items") 43 public class ItemsController { 44 45 @Autowired 46 private ItemsService itemsService; 47 48 49 //商品分类 50 //itemtypes 表示最终将方法返回值放在request中的key ; 51 @ModelAttribute("itemtypes") 52 public Map<String,String> getItemTypes(){ 53 Map<String,String> itemTypes= new HashMap<String,String>(); 54 itemTypes.put("101","数码"); 55 itemTypes.put("102","食品"); 56 return itemTypes; 57 } 58 // 商品查询 59 @RequestMapping("/queryItems") 60 public ModelAndView queryItems(HttpServletRequest request,Integer id ,ItemsQueryVo itemsQueryVo) throws Exception { 61 //测试forward后request是否可以共享 62 63 // 调用service查找 数据库,查询商品列表 64 List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); 65 66 // 返回ModelAndView 67 ModelAndView modelAndView = new ModelAndView(); 68 // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据 69 modelAndView.addObject("itemsList", itemsList); 70 71 // 指定视图 72 // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为 73 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); 74 // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀 75 modelAndView.setViewName("items/itemsList"); 76 77 return modelAndView; 78 79 } 80 81 //添加商品,ID用当前时间的 82 @RequestMapping(value="/addItems") 83 public String addItems( ) throws Exception { 84 return "items/addItems"; 85 } 86 //添加商品 通过 EASYUI框架 87 @RequestMapping(value="/addOrUpdate",method=RequestMethod.POST) 88 @ResponseBody 89 public Map<String, String> addOrUpdate(ItemsCustom itemsCustom,MultipartFile items_pic ) throws Exception{ 90 //spring会利用jackson自动将返回值封装成JSON对象,比struts2方便了很多 91 Map<String, String> map = new HashMap<String, String>(); 92 int randNumber = (int)(1+Math.random()*(10000000-56785+1)); 93 itemsCustom.setId(randNumber); 94 //itemsCustom.setPic("abc.jpg"); 95 String orgPicName = items_pic.getOriginalFilename(); 96 //存在图片路径 97 String picPath= "h:\\web_upload\\"; 98 if (orgPicName!=null && picPath!=null && orgPicName.length()>0) { 99 //新文件名 100 String newFileName = UUID.randomUUID() + orgPicName.substring(orgPicName.lastIndexOf(".")); 101 File newFile = new File(picPath+newFileName); 102 //将内存中的数据写入磁盘 103 items_pic.transferTo(newFile); 104 itemsCustom.setPic(newFileName); 105 } 106 107 try { 108 itemsService.addItems(itemsCustom); 109 map.put("mes", "操作成功"); 110 } catch (Exception e) { 111 e.printStackTrace(); 112 map.put("mes", "操作失败"); 113 throw e; 114 } 115 return map; 116 } 117 118 119 @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET}) 120 //@RequestParam里边指定request传入参数名称和形参进行绑定。 121 //通过required属性指定参数是否必须要传入 122 //通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。 123 public String editItems(Model model,@RequestParam(value="id",required=true) Integer items_id)throws Exception { 124 125 //调用service根据商品id查询商品信息 126 ItemsCustom itemsCustom = itemsService.findItemsById(items_id); 127 /* if (itemsCustom==null) { 128 throw new CustomException("修改的商品信息不存在!"); 129 }*/ 130 131 //通过形参中的model将model数据传到页面 132 //相当于modelAndView.addObject方法 133 model.addAttribute("items", itemsCustom); 134 135 return "items/editItems"; 136 } 137 138 //商品信息修改提交,及校验 139 //在需要校验的POJO前面加@Validated,后面添加BindingResult接收校验输出的错误信息 140 //注意:@Validated和BindingResult bindingResult 是配对出现,并且形参顺序是固定的(一前一后) 141 //value= {ValidGroup1.class})指定使用分组1的校验 142 // 143 @RequestMapping("/editItemsSubmit") 144 public String editItemsSubmit(Model model, 145 HttpServletRequest request, 146 String pic, 147 Integer id, 148 @Validated(value= {ValidGroup1.class}) ItemsCustom itemsCustom, 149 BindingResult bindingResult, 150 MultipartFile items_pic //接收商品图片 151 )throws Exception { 152 153 //获取校验错误信息 154 if (bindingResult.hasErrors()) { 155 // 输出错误信息 156 List<ObjectError> allErrors = bindingResult.getAllErrors(); 157 158 for (ObjectError objectError : allErrors) { 159 // 输出错误信息 160 System.out.println(objectError.getDefaultMessage()); 161 162 } 163 // 将错误信息传到页面 164 model.addAttribute("allErrors", allErrors); 165 166 167 //可以直接使用model将提交pojo回显到页面 168 model.addAttribute("items", itemsCustom); 169 170 // 出错重新到商品修改页面 171 return "items/editItems"; 172 }else { 173 //上传图片 174 String originalFilename = items_pic.getOriginalFilename(); 175 //存储图片的物理路径 176 String pic_path = "h:\\web_upload\\"; 177 //原文件名称 178 179 System.out.println("=================================================="); 180 System.out.println(pic); 181 String oldFileName = pic; 182 if (items_pic!=null && originalFilename!=null && originalFilename.length()>0 ) { 183 184 185 //新的图片名称 186 String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf(".")); 187 //新图片 188 File newFile = new File(pic_path+newFileName); 189 190 //将内存中的数据写入磁盘 191 items_pic.transferTo(newFile); 192 oldFileName = newFileName; 193 194 } 195 //将新图片名称写到itemsCustom中 196 itemsCustom.setPic(oldFileName); 197 //如果正确,执行更新操作。 198 itemsService.updateItems(id, itemsCustom); 199 200 return "forward:queryItems.action"; 201 202 } 203 } 204 //商品批量删除 205 @RequestMapping("deleteItems") 206 public String deleteItems(Integer[] items_id) throws Exception{ 207 208 for (int i:items_id) { 209 itemsService.deleteItems(i); 210 211 } 212 return "success"; 213 214 } 215 216 //商品批量修改 217 @RequestMapping("editItemsQuery") 218 public ModelAndView editItemsQuery(HttpServletRequest request,ItemsQueryVo itemsQueryVo) throws Exception{ 219 220 221 // 调用service查找 数据库,查询商品列表 222 List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); 223 224 // 返回ModelAndView 225 ModelAndView modelAndView = new ModelAndView(); 226 // 相当 于request的setAttribut,在jsp页面中通过itemsList取数据 227 modelAndView.addObject("itemsList", itemsList); 228 229 // 指定视图 230 // 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为 231 // modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp"); 232 // 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀 233 modelAndView.setViewName("items/editItemsQuery"); 234 235 return modelAndView; 236 } 237 238 //批量商品修改提交 239 //通过ItemsQueryVo接收批量提交的信息,将商品信息存储到itemsQueryVo中itemsList属性中 240 @RequestMapping("/editItemsAllSubmit") 241 public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo) throws Exception{ 242 243 return "success"; 244 } 245 246 //查询商品信息,输出json 247 ///itemsView/{id}中的 {id},表示将这个位置的参数传到@PathVariable指定的名称变量中; 248 @RequestMapping("/itemsView/{id}") 249 250 public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception{ 251 ItemsCustom itemsCustom = itemsService.findItemsById(id); 252 return itemsCustom; 253 } 254 255 256 // 商品查询输入到easy ui 257 @RequestMapping("/queryItemsMap") 258 @ResponseBody 259 //@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口 260 //将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。 261 public Map<String, Object> queryItemsMap(HttpServletRequest request,ItemsQueryVo itemsQueryVo) throws Exception { 262 //测试forward后request是否可以共享 263 // 调用service查找 数据库,查询商品列表 264 List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); 265 266 Map<String,Object> itemsMap = new HashMap<String,Object>(); 267 itemsMap.put("total",13); 268 itemsMap.put("rows",itemsList); 269 270 return itemsMap; 271 272 } 273 274 275 @RequestMapping("list") 276 public String list() throws Exception { 277 278 return "items/itemsEasyUi"; 279 } 280 }
3、main.jsp
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %> 2 <%@include file="/taglibs.jsp" %> 3 <html> 4 <head> 5 6 <title>lr信息综合管理平台 </title> 7 <style type="text/css"> 8 #menu { 9 width:200px; 10 11 /*border:1px solid red;*/ 12 } 13 #menu ul { 14 list-style: none; 15 padding: 0px; 16 margin: 0px; 17 18 } 19 #menu ul li { 20 border-bottom: 1px solid #fff; 21 text-align: center; 22 23 } 24 #menu ul li a { 25 /*先将a标签转换为块级元素,才能设置宽和内间距*/ 26 display: block; 27 background-color: #458fce; 28 color: #fff; 29 padding: 5px; 30 31 text-decoration: none; 32 } 33 #menu ul li a:hover { 34 background-color: #008792; 35 } 36 37 </style> 38 </head> 39 <script type="text/javascript"> 40 //判断选中或增加tab组件 41 function addTab(title, url){ 42 if ($('#tt').tabs('exists', title)){ 43 $('#tt').tabs('select', title); 44 } else { 45 var content = '<iframe scrolling="auto" frameborder="0" src="'+url+'" style="width:100%;height:100%;"></iframe>'; 46 $('#tt').tabs('add',{ 47 title:title, 48 content:content, 49 closable:true 50 }); 51 } 52 } 53 54 //弹出窗口 55 function showWindow(options){ 56 jQuery("#MyPopWindow").window(options); 57 } 58 //关闭弹出窗口 59 function closeWindow(){ 60 $("#MyPopWindow").window('close'); 61 } 62 </script> 63 <body class="easyui-layout"> 64 <div region="north" style="height: 65px; background: #458fce; border="false"> 65 <div style="float:left" ><img src="${basePath }/img/logo.png"/></div> 66 <div style="float:right;" ><h1 style="color:white;" >当前用户:${username} <a href="${basePath}/logout">退出</a></h1></div> 67 </div> 68 <div region="west" style="width: 200px" title="快速导航" split="true"> 69 <div data-options="border:false" class="easyui-accordion" style="width:200px;"> 70 <div id="menu" title="用户管理" data-options="iconCls:'icon-save',selected:true" > 71 <ul> 72 <li><a href="#" onclick="addTab('用户管理','${basePath }/items/list')">用户添加</a> 73 <li><a href="#" onclick="addTab('lingrui','http://www.lingrui.com')">lingrui</a> 74 </ul> 75 </div> 76 <div title="权限管理" data-options="iconCls:'icon-reload'" style="padding:10px;"> 77 <ul> 78 <li><a href="#" onclick="addTab('系统调试','${basePath }/jsp/success.jsp')">lingrui</a> 79 </li> 80 </div> 81 <div title="客户管理" data-options="iconCls:'icon-reload'" style="padding:10px;"> 82 content2 83 </div> 84 <div title="物料管理" data-options="iconCls:'icon-reload'" style="padding:10px;"> 85 content2 86 </div> 87 88 <div title="菜单管理"> 89 <div style="margin-bottom:10px"> 90 <a href="#" class="easyui-linkbutton" onclick="addTab('google','http://www.google.com')">google</a> 91 <a href="#" class="easyui-linkbutton" onclick="addTab('jquery','http://jquery.com/')">jquery</a> 92 <a href="#" class="easyui-linkbutton" onclick="addTab('easyui','http://jeasyui.com/')">easyui</a> 93 </div> 94 </div> 95 </div> 96 </div> 97 <div data-options="region:'center'" style="background:#eee;"> 98 99 <div id="tt" class="easyui-tabs" fit="true" "> 100 <div title="首页" data-options="iconCls:'icon-home'" > 101 <div align="center" style="padding-top: 100px"><font color="red" size="10">欢迎使用<br>lr综合管理平台</font></div> 102 </div> 103 </div> 104 105 </div> 106 <div region="south" style="height: 25px;padding: 5px" align="center"> 107 Copyright © 2018-2020 lr股份有限公司 版权所有 108 </div> 109 </body> 110 111 112 </html>
4 index.jsp 登录页
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 4 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> 5 6 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 7 <html> 8 <head> 9 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 10 <title>系统登录</title> 11 12 13 <script type="text/javascript"> 14 function check_pwd(){ 15 var username = document.getElementById("username").value; 16 var password = document.getElementById("password").value; 17 if (username=="" ){ 18 alert('请输入用户名!'); 19 return false; 20 }else if (password=="" ){ 21 alert('请输入密码!'); 22 return false; 23 } 24 return true; 25 } 26 </script> 27 </head> 28 29 <body style="text-align:center;background-color:#458fce;color:white;"> 30 31 <form action="${pageContext.request.contextPath }/login.action" onsubmit="return check_pwd()" method="post"> 32 <br><br><br><br><br><br><br><br> 33 <h3>系统登录</h3><br> 34 <% 35 HttpSession Session = request.getSession(); 36 String flag = null; 37 flag = (String)Session.getAttribute("flag"); 38 if (flag!=null && flag=="false"){ 39 out.println(" 用户名或密码错误,请重新输入!<br>"); 40 session.removeAttribute("flag"); 41 } 42 43 %> 44 <p id="pwderror" style="display:none;" >用户名或密码错误,请重新输入!</p> 45 用户账号:<input id="username" style="width:100px" name="username" placeholder="请输入用户名" value="admin"/> <br><br> 46 47 用户密码:<input id="password" style="width:100px" type="password" name="password" placeholder="请输入密码" value="admin" /> 48 <br> <br> 49 <input type="submit" value="登 陆"/> 50 51 <br><br><br><br><br><br><br><br> 52 <h3>版权所有:LR股份有限公司</h3> 53 </form> 54 55 </body> 56 </html>
5 LoginController.java
1 package com.lr.controller; 2 3 import javax.servlet.http.HttpSession; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 9 import com.lr.common.StringUtil; 10 import com.lr.po.LrUser; 11 import com.lr.service.LoginService; 12 13 /** 14 * Filename:LoginController.java 15 * Descript:登录退出 16 * Parm: 17 * Author:zhangsh 18 * CreateDate:2018年3月5日 下午4:40:39 19 * 20 */ 21 @Controller 22 public class LoginController { 23 24 @Autowired 25 private LoginService loginService; 26 27 //登录 28 @RequestMapping("/login") 29 public String login(HttpSession session,String username,String password) throws Exception{ 30 31 //调用service 进行用户身份验证 32 //..... 33 34 LrUser user = null; 35 user = loginService.findUserByName(username); 36 if (user==null ) { 37 //不存在的用户;用户名或密码错误,设置session标记flag为false 38 session.setAttribute("flag","false"); 39 return "redirect:index.jsp"; 40 } 41 String orgPassword ; 42 orgPassword = user.getPassword(); 43 String userPwd = StringUtil.getSign(username) ; 44 System.out.println(userPwd); 45 if (orgPassword.equals(userPwd)) { 46 //验证通过,转主页面 47 session.setAttribute("username",username); 48 return "pub/main"; 49 }else { 50 //登录失败,返回重新登录,在缓存中加入false为了在登录页提醒; 51 session.setAttribute("flag","false"); 52 return "redirect:index.jsp"; 53 } 54 } 55 56 //退出 57 @RequestMapping("/logout") 58 public String logout(HttpSession session) throws Exception{ 59 //清除session 60 session.invalidate(); 61 return "redirect:index.jsp"; 62 } 63 }
附:项目结构
活到老,学到老。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!