首页 技术 正文
技术 2022年11月21日
0 收藏 469 点赞 3,442 浏览 18924 个字

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方法异步上传

        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 });

 

 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="/taglibs.jsp" %>
<html>
<head>
<script type="text/javascript">
jQuery(function($){
$('#itemsTable').datagrid({
title:'用户列表', //标题
method:'post',
iconCls:'icon-edit', //图标
singleSelect:false, //多选
//height:560, //高度
fitColumns: true, //自动调整各列,用了这个属性,下面各列的宽度值就只是一个比例。
striped: true, //奇偶行颜色不同
collapsible:true,//可折叠
url:"queryItemsMap", //数据来源
sortName: 'name', //排序的列
sortOrder: 'desc', //倒序
remoteSort: true, //服务器端排序
idField:'id', //主键字段
queryParams:{}, //查询条件
pagination:true, //显示分页
rownumbers:true, //显示行号
columns:[[
{field:'ck',checkbox:true,width:2}, //显示复选框
{field:'name',title:'名称',width:20,sortable:true,
formatter:function(value,row,index){return row.name;} //需要formatter一下才能显示正确的数据
},
{field:'price',title:'价格',width:20,sortable:true,
formatter:function(value,row,index){return row.price;}
},
{field:'createtime',title:'生产日期',width:30,sortable:true,
formatter:function(value,row,index)
{
var createtime = new Date(value);
return createtime.toLocaleString();
//return row.createtime;
}
},
{field:'detail',title:'说明',width:30,sortable:true,
formatter:function(value,row,index){
return row.detail; //该列的值是deptId,显示的是deptName
}
}
]],
toolbar:[{
text:'新增',
iconCls:'icon-add',
handler:function(){
jQuery("#itemsDiv").window('open');
}
},'-',{
text:'更新',
iconCls:'icon-edit',
handler:function(){
updaterow();
}
},'-',{
text:'删除',
iconCls:'icon-remove',
handler:function(){
deleterow();
}
},'-'],
onLoadSuccess:function(){
$('#itemsTable').datagrid('clearSelections'); //一定要加上这一句,要不然datagrid会记住之前的选择状态,删除时会出问题
}
});
}); //新增商品
function addItems(){
var r = $('#itemsForm').form('validate'); if(!r) {
return false;
}
var formData = new FormData($( "#itemsForm" )[0]);
$.ajax({
url: 'addOrUpdate' ,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$('#itemsDiv').window('close');
$('#itemsTable').datagrid('reload');
$.messager.alert('提示',returndata.mes,'info');
}
});
} //弹出窗口
function showWindow(options){
jQuery("#itemsDiv").window(options);
}
//关闭弹出窗口
function closeWindow(){
$("#itemsDiv").window('close');
}
//预览本地照片
function change_photo(){
PreviewImage($("input[name='items_pic']")[0], 'Img', 'Imgdiv');
}
//预览本机照片 来自网上
function PreviewImage(fileObj,imgPreviewId,divPreviewId){
var allowExtention=".jpg,.bmp,.gif,.png";//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value;
var extention=fileObj.value.substring(fileObj.value.lastIndexOf(".")+1).toLowerCase();
var browserVersion= window.navigator.userAgent.toUpperCase();
if(allowExtention.indexOf(extention)>-1){
if(fileObj.files){//HTML5实现预览,兼容chrome、火狐7+等
if(window.FileReader){
var reader = new FileReader();
reader.onload = function(e){
document.getElementById(imgPreviewId).setAttribute("src",e.target.result);
}
reader.readAsDataURL(fileObj.files[0]);
}else if(browserVersion.indexOf("SAFARI")>-1){
alert("不支持Safari6.0以下浏览器的图片预览!");
}
}else if (browserVersion.indexOf("MSIE")>-1){
if(browserVersion.indexOf("MSIE 6")>-1){//ie6
document.getElementById(imgPreviewId).setAttribute("src",fileObj.value);
}else{//ie[7-9]
fileObj.select();
if(browserVersion.indexOf("MSIE 9")>-1)
fileObj.blur();//不加上document.selection.createRange().text在ie9会拒绝访问
var newPreview =document.getElementById(divPreviewId+"New");
if(newPreview==null){
newPreview =document.createElement("div");
newPreview.setAttribute("id",divPreviewId+"New");
newPreview.style.width = document.getElementById(imgPreviewId).width+"px";
newPreview.style.height = document.getElementById(imgPreviewId).height+"px";
newPreview.style.border="solid 1px #d2e2e2";
}
newPreview.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')";
var tempDivPreview=document.getElementById(divPreviewId);
tempDivPreview.parentNode.insertBefore(newPreview,tempDivPreview);
tempDivPreview.style.display="none";
}
}else if(browserVersion.indexOf("FIREFOX")>-1){//firefox
var firefoxVersion= parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
if(firefoxVersion<7){//firefox7以下版本
document.getElementById(imgPreviewId).setAttribute("src",fileObj.files[0].getAsDataURL());
}else{//firefox7.0+
document.getElementById(imgPreviewId).setAttribute("src",window.URL.createObjectURL(fileObj.files[0]));
}
}else{
document.getElementById(imgPreviewId).setAttribute("src",fileObj.value);
}
}else{
alert("仅支持"+allowExtention+"为后缀名的文件!");
fileObj.value="";//清空选中文件
if(browserVersion.indexOf("MSIE")>-1){
fileObj.select();
document.selection.clear();
}
fileObj.outerHTML=fileObj.outerHTML;
}
} </script>
</head> <body>
<div style="padding:10" id="tabdiv">
<table id="itemsTable"></table>
</div>
<!-- model 模态弹出窗口 --> <div id="itemsDiv" class="easyui-window" data-options="modal:true,closed:true,iconCls:'icon-save'" title="商品管理" style="width:350px;height:300px;">
<form id="itemsForm" enctype="multipart/form-data" style="padding:10px 20px 10px 40px;">
<p>名称: <input name="name" type="text" class="easyui-validatebox" required="true"></p>
<p>规格: <input name="detail" type="text" type="text" class="easyui-validatebox" required="true" ></p>
<p>价格: <input name="price" type="text" type="text" class="easyui-validatebox" required="true"></p>
<p>日期: <input name="createtime" type="text" class="Wdate" onClick="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss' })"></p>
<p>照片:<input class="easyui-filebox" data-options='onChange:change_photo' id="file_upload" name="items_pic"/><br/>
<div id="Imgdiv">
<img id="Img" width="200px" height="200px"/>
</div>
<div style="padding:5px;text-align:center;">
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" icon="icon-ok" onclick="addItems()">确认</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" icon="icon-cancel">返回</a>
</div>
</form>
</div>
<!-- model 模态弹出窗口 结束--> </body>
</html>

 

 

2、itemsController.java

 package com.lr.controller; import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; import com.lr.controller.validation.ValidGroup1;
import com.lr.po.ItemsCustom;
import com.lr.po.ItemsQueryVo;
import com.lr.service.ItemsService; /**
*
* <p>
* Title: ItemsController </p>
* <p> Description:商品的controller </p>
* @date 2015-4-13下午4:03:35
* @version 1.0
*/
@Controller
//为了对url进行分类管理 ,可以在这里定义根路径,最终访问url是根路径+子路径
//比如:商品列表:/items/queryItems.action
@RequestMapping("/items")
public class ItemsController { @Autowired
private ItemsService itemsService; //商品分类
//itemtypes 表示最终将方法返回值放在request中的key ;
@ModelAttribute("itemtypes")
public Map<String,String> getItemTypes(){
Map<String,String> itemTypes= new HashMap<String,String>();
itemTypes.put("101","数码");
itemTypes.put("102","食品");
return itemTypes;
}
// 商品查询
@RequestMapping("/queryItems")
public ModelAndView queryItems(HttpServletRequest request,Integer id ,ItemsQueryVo itemsQueryVo) throws Exception {
//测试forward后request是否可以共享 // 调用service查找 数据库,查询商品列表
List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); // 返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
// 相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList); // 指定视图
// 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
// modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
modelAndView.setViewName("items/itemsList"); return modelAndView; } //添加商品,ID用当前时间的
@RequestMapping(value="/addItems")
public String addItems( ) throws Exception {
return "items/addItems";
}
//添加商品 通过 EASYUI框架
@RequestMapping(value="/addOrUpdate",method=RequestMethod.POST)
@ResponseBody
public Map<String, String> addOrUpdate(ItemsCustom itemsCustom,MultipartFile items_pic ) throws Exception{
//spring会利用jackson自动将返回值封装成JSON对象,比struts2方便了很多
Map<String, String> map = new HashMap<String, String>();
int randNumber = (int)(1+Math.random()*(10000000-56785+1));
itemsCustom.setId(randNumber);
//itemsCustom.setPic("abc.jpg");
String orgPicName = items_pic.getOriginalFilename();
//存在图片路径
String picPath= "h:\\web_upload\\";
if (orgPicName!=null && picPath!=null && orgPicName.length()>0) {
//新文件名
String newFileName = UUID.randomUUID() + orgPicName.substring(orgPicName.lastIndexOf("."));
File newFile = new File(picPath+newFileName);
//将内存中的数据写入磁盘
items_pic.transferTo(newFile);
itemsCustom.setPic(newFileName);
} try {
itemsService.addItems(itemsCustom);
map.put("mes", "操作成功");
} catch (Exception e) {
e.printStackTrace();
map.put("mes", "操作失败");
throw e;
}
return map;
} @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
//@RequestParam里边指定request传入参数名称和形参进行绑定。
//通过required属性指定参数是否必须要传入
//通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
public String editItems(Model model,@RequestParam(value="id",required=true) Integer items_id)throws Exception { //调用service根据商品id查询商品信息
ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
/* if (itemsCustom==null) {
throw new CustomException("修改的商品信息不存在!");
}*/ //通过形参中的model将model数据传到页面
//相当于modelAndView.addObject方法
model.addAttribute("items", itemsCustom); return "items/editItems";
} //商品信息修改提交,及校验
//在需要校验的POJO前面加@Validated,后面添加BindingResult接收校验输出的错误信息
//注意:@Validated和BindingResult bindingResult 是配对出现,并且形参顺序是固定的(一前一后)
//value= {ValidGroup1.class})指定使用分组1的校验
//
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(Model model,
HttpServletRequest request,
String pic,
Integer id,
@Validated(value= {ValidGroup1.class}) ItemsCustom itemsCustom,
BindingResult bindingResult,
MultipartFile items_pic //接收商品图片
)throws Exception { //获取校验错误信息
if (bindingResult.hasErrors()) {
// 输出错误信息
List<ObjectError> allErrors = bindingResult.getAllErrors(); for (ObjectError objectError : allErrors) {
// 输出错误信息
System.out.println(objectError.getDefaultMessage()); }
// 将错误信息传到页面
model.addAttribute("allErrors", allErrors); //可以直接使用model将提交pojo回显到页面
model.addAttribute("items", itemsCustom); // 出错重新到商品修改页面
return "items/editItems";
}else {
//上传图片
String originalFilename = items_pic.getOriginalFilename();
//存储图片的物理路径
String pic_path = "h:\\web_upload\\";
//原文件名称 System.out.println("==================================================");
System.out.println(pic);
String oldFileName = pic;
if (items_pic!=null && originalFilename!=null && originalFilename.length()>0 ) { //新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//新图片
File newFile = new File(pic_path+newFileName); //将内存中的数据写入磁盘
items_pic.transferTo(newFile);
oldFileName = newFileName; }
//将新图片名称写到itemsCustom中
itemsCustom.setPic(oldFileName);
//如果正确,执行更新操作。
itemsService.updateItems(id, itemsCustom); return "forward:queryItems.action"; }
}
//商品批量删除
@RequestMapping("deleteItems")
public String deleteItems(Integer[] items_id) throws Exception{ for (int i:items_id) {
itemsService.deleteItems(i); }
return "success"; } //商品批量修改
@RequestMapping("editItemsQuery")
public ModelAndView editItemsQuery(HttpServletRequest request,ItemsQueryVo itemsQueryVo) throws Exception{ // 调用service查找 数据库,查询商品列表
List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); // 返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
// 相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList); // 指定视图
// 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
// modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
modelAndView.setViewName("items/editItemsQuery"); return modelAndView;
} //批量商品修改提交
//通过ItemsQueryVo接收批量提交的信息,将商品信息存储到itemsQueryVo中itemsList属性中
@RequestMapping("/editItemsAllSubmit")
public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo) throws Exception{ return "success";
} //查询商品信息,输出json
///itemsView/{id}中的 {id},表示将这个位置的参数传到@PathVariable指定的名称变量中;
@RequestMapping("/itemsView/{id}") public @ResponseBody ItemsCustom itemsView(@PathVariable("id") Integer id) throws Exception{
ItemsCustom itemsCustom = itemsService.findItemsById(id);
return itemsCustom;
} // 商品查询输入到easy ui
@RequestMapping("/queryItemsMap")
@ResponseBody
//@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口
//将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。
public Map<String, Object> queryItemsMap(HttpServletRequest request,ItemsQueryVo itemsQueryVo) throws Exception {
//测试forward后request是否可以共享
// 调用service查找 数据库,查询商品列表
List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo); Map<String,Object> itemsMap = new HashMap<String,Object>();
itemsMap.put("total",13);
itemsMap.put("rows",itemsList); return itemsMap; } @RequestMapping("list")
public String list() throws Exception { return "items/itemsEasyUi";
}
}

3、main.jsp

 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="/taglibs.jsp" %>
<html>
<head> <title>lr信息综合管理平台 </title>
<style type="text/css">
#menu {
width:200px; /*border:1px solid red;*/
}
#menu ul {
list-style: none;
padding: 0px;
margin: 0px; }
#menu ul li {
border-bottom: 1px solid #fff;
text-align: center; }
#menu ul li a {
/*先将a标签转换为块级元素,才能设置宽和内间距*/
display: block;
background-color: #458fce;
color: #fff;
padding: 5px; text-decoration: none;
}
#menu ul li a:hover {
background-color: #008792;
} </style>
</head>
<script type="text/javascript">
//判断选中或增加tab组件
function addTab(title, url){
if ($('#tt').tabs('exists', title)){
$('#tt').tabs('select', title);
} else {
var content = '<iframe scrolling="auto" frameborder="0" src="'+url+'" style="width:100%;height:100%;"></iframe>';
$('#tt').tabs('add',{
title:title,
content:content,
closable:true
});
}
} //弹出窗口
function showWindow(options){
jQuery("#MyPopWindow").window(options);
}
//关闭弹出窗口
function closeWindow(){
$("#MyPopWindow").window('close');
}
</script>
<body class="easyui-layout">
<div region="north" style="height: 65px; background: #458fce; border="false">
<div style="float:left" ><img src="${basePath }/img/logo.png"/></div>
<div style="float:right;" ><h1 style="color:white;" >当前用户:${username} <a href="${basePath}/logout" rel="external nofollow" >退出</a></h1></div>
</div>
<div region="west" style="width: 200px" title="快速导航" split="true">
<div data-options="border:false" class="easyui-accordion" style="width:200px;">
<div id="menu" title="用户管理" data-options="iconCls:'icon-save',selected:true" >
<ul>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="addTab('用户管理','${basePath }/items/list')">用户添加</a>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="addTab('lingrui','http://www.lingrui.com')">lingrui</a>
</ul>
</div>
<div title="权限管理" data-options="iconCls:'icon-reload'" style="padding:10px;">
<ul>
<li><a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" onclick="addTab('系统调试','${basePath }/jsp/success.jsp')">lingrui</a>
</li>
</div>
<div title="客户管理" data-options="iconCls:'icon-reload'" style="padding:10px;">
content2
</div>
<div title="物料管理" data-options="iconCls:'icon-reload'" style="padding:10px;">
content2
</div> <div title="菜单管理">
<div style="margin-bottom:10px">
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" onclick="addTab('google','http://www.google.com')">google</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" onclick="addTab('jquery','http://jquery.com/')">jquery</a>
<a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="easyui-linkbutton" onclick="addTab('easyui','http://jeasyui.com/')">easyui</a>
</div>
</div>
</div>
</div>
<div data-options="region:'center'" style="background:#eee;"> <div id="tt" class="easyui-tabs" fit="true" ">
<div title="首页" data-options="iconCls:'icon-home'" >
<div align="center" style="padding-top: 100px"><font color="red" size="10">欢迎使用<br>lr综合管理平台</font></div>
</div>
</div> </div>
<div region="south" style="height: 25px;padding: 5px" align="center">
Copyright © 2018-2020 lr股份有限公司 版权所有
</div>
</body> </html>

4 index.jsp 登录页

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>系统登录</title> <script type="text/javascript">
function check_pwd(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username=="" ){
alert('请输入用户名!');
return false;
}else if (password=="" ){
alert('请输入密码!');
return false;
}
return true;
}
</script>
</head> <body style="text-align:center;background-color:#458fce;color:white;"> <form action="${pageContext.request.contextPath }/login.action" onsubmit="return check_pwd()" method="post">
<br><br><br><br><br><br><br><br>
<h3>系统登录</h3><br>
<%
HttpSession Session = request.getSession();
String flag = null;
flag = (String)Session.getAttribute("flag");
if (flag!=null && flag=="false"){
out.println(" 用户名或密码错误,请重新输入!<br>");
session.removeAttribute("flag");
} %>
<p id="pwderror" style="display:none;" >用户名或密码错误,请重新输入!</p>
用户账号:<input id="username" style="width:100px" name="username" placeholder="请输入用户名" value="admin"/> <br><br> 用户密码:<input id="password" style="width:100px" type="password" name="password" placeholder="请输入密码" value="admin" />
<br> <br>
<input type="submit" value="登 陆"/> <br><br><br><br><br><br><br><br>
<h3>版权所有:LR股份有限公司</h3>
</form> </body>
</html>

5 LoginController.java

 package com.lr.controller; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.lr.common.StringUtil;
import com.lr.po.LrUser;
import com.lr.service.LoginService; /**
* Filename:LoginController.java
* Descript:登录退出
* Parm:
* Author:zhangsh
* CreateDate:2018年3月5日 下午4:40:39
*
*/
@Controller
public class LoginController { @Autowired
private LoginService loginService; //登录
@RequestMapping("/login")
public String login(HttpSession session,String username,String password) throws Exception{ //调用service 进行用户身份验证
//..... LrUser user = null;
user = loginService.findUserByName(username);
if (user==null ) {
//不存在的用户;用户名或密码错误,设置session标记flag为false
session.setAttribute("flag","false");
return "redirect:index.jsp";
}
String orgPassword ;
orgPassword = user.getPassword();
String userPwd = StringUtil.getSign(username) ;
System.out.println(userPwd);
if (orgPassword.equals(userPwd)) {
//验证通过,转主页面
session.setAttribute("username",username);
return "pub/main";
}else {
//登录失败,返回重新登录,在缓存中加入false为了在登录页提醒;
session.setAttribute("flag","false");
return "redirect:index.jsp";
}
} //退出
@RequestMapping("/logout")
public String logout(HttpSession session) throws Exception{
//清除session
session.invalidate();
return "redirect:index.jsp";
}
}

附:项目结构

spring mvc +easy ui +Mybatis 录入数据

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,401
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,896