1. 程式人生 > >SpringMVC登入、註冊、驗證碼

SpringMVC登入、註冊、驗證碼

想要實現以下效果:

首先jsp前臺頁面

<body style="margin:150px 0 0 600px">
<!-- Panel面板
	data-options   英文為:屬性
	iconCls : string 設定一個16x16圖示的CSS類ID顯示在面板左上角。 
	
 -->
<div id="p" class="easyui-panel" title="登入"     
        style="width:350px;height:260px;padding:10px;background:#fafafa;"   
        data-options="iconCls:'icon-man'">  
<!-- 
		Form表單
		validatebox(驗證框)
		required boolean 定義為必填欄位。 
		
 -->
   <form id="loginform" method="post">   
	   	<table style="padding: 20px 0 10px 30px">
	   		<tr>
	   			<td>使用者名稱:</td>
	   			<td><input class="easyui-validatebox" type="text" name="user_name" data-options="required:true" /></td>
	   		</tr>
	   		<tr>
	   			<td>密碼:</td>
	   			<td><input class="easyui-validatebox" type="text" name="password" data-options="required:true" /></td>
	   		</tr>
	   		<tr>
	   			<td>驗證碼:</td>
	   			<td><input type="text" class="easyui-validatebox" id="code" name="code" placeholder="驗證碼" maxlength="4" value="" style="width: 60px" data-options="required:true" tipPosition="top"/>
	   				 <img src="${ctx}/user/getCode.action" title="看不清,點選重新整理" onclick="reloadValidCode()"
						style="vertical-align: middle;" id="imgcode"/></td>
	   		</tr>
	   		
	   		<tr>
	   			<td></td>
	   			<td>
	   			<a id="btn" href="#" onclick="login()" class="easyui-linkbutton c7" data-options="iconCls:'icon-ok'">登入</a> 
	   			<a id="btn" href="#" onclick="regisger()" class="easyui-linkbutton" data-options="iconCls:'icon-add'" style="margin-left: 55px">註冊</a> 
	   			</td>
	   		</tr>
	   		
	   	</table>
	</form>  

</div>  
<!-- easyui-dialog對話視窗
	modal boolean 定義是否將窗體顯示為模式化視窗。 
	resizable boolean 定義是否可以改變對話方塊視窗大小。 
	closed boolean 定義是否可以關閉視窗。 
	buttons array,selector 對話方塊視窗底部按鈕,可用值有
	easyui-combobox 下拉列表框
	editable boolean 定義使用者是否可以直接輸入文字到欄位中。 
	multiple boolean 定義是否支援多選。 
	required="true"   ValidateBox(驗證框)屬性
 -->
<div id="user_dialog" class="easyui-dialog" title="My Dialog" style="width:400px;height:auto;"   
        data-options="iconCls:'icon-save',resizable:true,modal:true,closed:true,buttons:'#user_dialog_bottons'">   
    <form id="user_form" method="post">  
    	<input type="hidden" name="id"> 
    	<table>
			   	<tr>
	    			<td>使用者名稱:</td>
	    			<td><input class="easyui-validatebox" type="text" name="user_name" data-options="required:true"/></td>
	    		</tr>
			   	<tr>
	    			<td>密碼:</td>
	    			<td><input class="easyui-validatebox" type="text" name="password" data-options="required:true"/></td>
	    		</tr>
			   	<tr>
	    			<td>真實姓名:</td>
	    			<td><input class="easyui-validatebox" type="text" name="name" data-options="required:true"/></td>
	    		</tr>
	    		<tr>
		   			<td>角色:</td>
		   			<td><input class="easyui-combobox" id="roles" name="roles" url='${ctx}/role/getAllList.action' 
				data-options="valueField:'id', textField:'role_name',editable:false,multiple:true,panelHeight:'auto'" required="true"></td>
		   		</tr>
			   	<tr>
	    			<td>手機號:</td>
	    			<td><input class="easyui-validatebox" type="text" name="phone" data-options="required:true"/></td>
	    		</tr>
    			<tr>
	    			<td>出生日期:</td>
	    			<td><input type="text" class="easyui-datebox" name="birthday" data-options="required:true"/></td>
	    		</tr>
    			<tr>
	    			<td>建立日期:</td>
	    			<td><input type="text" class="easyui-datebox" name="create_time" data-options="required:true"/></td>
	    		</tr>
			   	<tr>
	    			<td>建立人:</td>
	    			<td><input class="easyui-validatebox" type="text" name="create_user" data-options="required:true"/></td>
	    		</tr>
    			<tr>
	    			<td>最後修改時間:</td>
	    			<td><input type="text" class="easyui-datebox" name="update_time" data-options="required:true"/></td>
	    		</tr>
			   	<tr>
	    			<td>最後修改人:</td>
	    			<td><input class="easyui-validatebox" type="text" name="update_user" data-options="required:true"/></td>
	    		</tr>
			   	<tr>
	   			<td>性別:</td>
	   			<td  id="sextd">
		   				<input type="radio" name="sex" id="sex1" value="1" style="width:50px;" checked="checked">男</input>
						<input type="radio" name="sex" id="sex2" value="2" style="width:50px;">女</input>
		   			</td>
		   		</tr>
			   	<tr>
	    			<td>工資:</td>
	    			<td><input class="easyui-validatebox" type="text" name="salary" data-options="required:true"/></td>
	    		</tr>
			   	<tr>
	    			<td>履歷:</td>
	    			<td><input class="easyui-validatebox" type="text" name="content" data-options="required:true"/></td>
	    		</tr>
    	</table>
    	 
<!--	      單選  <input type="radio" name="sex" value="0" checked="checked"/>男 <input type="radio" name="sex" value="1"/>女   
	   下拉<input id="hobby_combobox" class="easyui-combobox" name="hobby" data-options="required:true,valueField:'code',textField:'name',url:'${ctx}/dict/geByPid.action?pid=1',multiple:true" />  
-->	
</form>  
</div>
<div id="user_dialog_bottons">
<a href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="save()">儲存</a> 
<a href="javascript:$('#user_dialog').dialog('close');" class="easyui-linkbutton" data-options="iconCls:'icon-cancel'">取消</a> 
</div>
<script type="text/javascript">
function keyEnter(){ 
	if (event.keyCode == 13) { 
		login();
	} 
} 
document.onkeydown =keyEnter;
function reloadValidCode() {
	$("#imgcode").prop('src',"${ctx}/user/getCode.action?timed="+ new Date().getMilliseconds());
}
function login(){
	$('#loginform').form('submit', {    
	    url:"${ctx}/user/login.action",   
	    onSubmit: function(){
	    	//gettips("code","驗證碼錯誤","top");
			var isValid = $(this).form('validate');
			return isValid;	// 返回false終止表單提交
		},
	    success:function(data){ 
	    	var data = eval('(' + data + ')');  
	        if(data.success){
	        	window.location.href="${ctx}/user/main.action";
	        }else{
	        	$.messager.alert('警告',data.msg,'error',function(){
	        		reloadValidCode();
	        	});
	        }
	    }    
	});  
}
function regisger(){

		$("#user_dialog").dialog("open").dialog("setTitle","註冊");
		$("#hobby_combobox").combobox("clear");
		$("#user_form").form("clear");
	
}
//註冊
 function save(){
	debugger;
	$('#user_form').form('submit', {    
		url:"${ctx}/user/save.action",   
	    onSubmit: function(){    
	    	return $(this).form('validate');
	    },    
	    success:function(data){  
	    	var data = eval("("+data+")");
	        if(data.success){
	        	$('#user_dialog').dialog('close');
	        	$("#user_datagrid").datagrid("reload");
	        } 
	    }    
	});  
}
</script>

</body>

在controller層編寫

        @RequestMapping("login")//登入
	@ResponseBody
	public ResJson login(HttpServletRequest request , String user_name , String password , String code , HttpSession session){
		ResJson resJson = new ResJson();
		String codeValue = (String) request.getSession().getAttribute(Const.SESSION_CODE);
		if (code.equalsIgnoreCase(codeValue)) {
			User user = userService.getUserName(user_name);
			System.out.println(user);
			if (user==null) {
				resJson.setSuccess(false);
				resJson.setMsg("使用者名稱密碼錯誤");
			}else {
				password=Encoding.md5Encoding(password);
				System.out.println("--------------"+password.toString());
				if (password.equals(user.getPassword())) {
					request.getSession().setAttribute(Const.SESSION_USER, user);
					request.getSession().setAttribute(Const.SESSION_USER_NAME, user.getUser_name());
					resJson.setSuccess(true);
					session.setAttribute("user", user);
				}else {
					resJson.setMsg("使用者名稱密碼錯誤");
				}
			}
		}else {
			resJson.setMsg("驗證碼錯誤");
		}
		System.out.println(resJson);
		return resJson;
	}
	@RequestMapping("logout")//退出登入,調回登入頁面
	public ModelAndView logout(HttpServletRequest request){
		HttpSession session = request.getSession();
		Object object = session.getAttribute(Const.SESSION_USER);
		if (object!=null) {
			session.invalidate();
		}
		return new ModelAndView("login/login");
	}
	/**
	 * 獲取驗證碼
	 */
	@RequestMapping("getCode")
	@ResponseBody
	public String getCode(HttpServletRequest request , HttpServletResponse response){
		try {
			ValidCodeUtils.getImage(request, response);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return null;
	}

在dao.xml檔案中編寫

<!--登入-->
  <select id="login" parameterType="com.model.user.User" resultType="com.model.user.User">
  	select
			   a.user_name,
			   a.password
		from 
				ztl_user a
		where a.user_name=#{user_name}
  </select>

在spring-mvc.xml配置檔案中加入攔截器地址

<!-- 攔截器  -->
        <mvc:interceptors>
               <bean class="//SystemInterceptor配置檔案的地址" />
        </mvc:interceptors>

配置SystemInterceptor攔截器

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class Systemlnterceptor implements HandlerInterceptor{

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		// TODO Auto-generated method stub
		//獲取請求地址
		String requestURI = request.getRequestURI();
		//不需要攔截的請求
		String No=".*/((tologin)|(loginOpt)).*";
		//判斷請求
		if (requestURI.matches(No)) {
			return true;
		}
		String id=(String)request.getSession().getAttribute("id");
		if (id!=null) {
			return true;
		}
		request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		return false;
	}

}