介绍
我在做管理系统时,想实现选择不同身份后,点击登录按钮便可以进入不同页面,以下是我查阅资料后实现的,如有不懂或遇到问题可以提问我
登录页面代码修改如下:
$(function(){
$("#submitBtn").click(function(){
var data = $("#form").serialize();
//$.ajax:用jquery的方式向后台发出ajax异步请求
var radioVal = $('input:radio:checked').val();
$.ajax({
type: "post",
url: "login",
data: data,
dataType: "json",
success: function(data){
if("success" == data.type){
if(radioVal == '2'){
window.parent.location.href ="stu";//跳转到相应页面
}else if(radioVal == '1'){
window.parent.location.href ="index";//跳转到相应页面
}
}else{
alert(data.msg);
}
}
});
});
});
<form id="form" method="post">
<!--
<input id="username" name="username" value="" type="text" required="required"/>
<input id="password" name="password" value="" type="password" required="required"/>
-->
<input type="radio" id="radio-2" name="type" value="2" title="学生" />
<input type="radio" id="radio-1" checked name="type" value="1" title="管理员" />
<button id="submitBtn" type="button" class="button"><span>Submit</span>
</form>
controller中代码如下
@RequestMapping(value="/login",method=RequestMethod.POST)
@ResponseBody
public Map<String,String> login(
@RequestParam(value="username",required=true) String username,
@RequestParam(value="password",required=true) String password,
@RequestParam(value="type",required=true) int type,
ModelAndView mv,HttpSession session
) {
Map<String,String> r=new HashMap<String,String>();
if(StringUtils.isEmpty(username)){
r.put("type", "error");
r.put("msg", "用户名不能为空!");
return r;
}
if(StringUtils.isEmpty(password)) {
r.put("type", "error");
r.put("msg", "密码不能为空");
return r;
}
if(type == 1){
User user=userService.login(username,password);
if(user==null) {
r.put("type", "error");
r.put("msg", "登录名或者密码错误,请重新输入");
return r;
}
else {
session.setAttribute("user", user);}
}
if(type == 2){
Student student=studentService.login(username, password);
if(student==null) {
r.put("type", "error");
r.put("msg", "登录名或者密码错误,请重新输入");
return r;
}
else {
session.setAttribute("user", student);}
}
session.setAttribute("userType", type);
r.put("type", "success");
r.put("msg", "登陆成功");
return r;
}