这是我在蓝桥班初学java做的第二个项目所遇到和解决的问题,写下来纪念,顺便供有缘人参考。
用户名/手机号/邮箱+密码登陆是当今最常用的登陆,对初学者而言这是必须掌握和精通的,这也是在我基础薄弱的我坚持解决的动力,其中感谢队友李青的大力协助。
model中写好teacher实体类,并提供getter和setter方法、toString重写转字符串。
SqlMapConfig.xml中configuration的typeAliases标签设置别名:
service层applicationContext-service.xml中使用 dubbo协议设置要暴露的接口
web层spring-servlet.xml中配置zookeeper
注:运行时别忘启动zookeeper
teacherLogin.jsp
共有2种方法
(1)正则表达式写于controller层。
判断2次输入的值是否匹配手机号或邮箱,默认用户名登陆。如果输入的值为手机号/邮箱,则将model实体类的用户名的setter方法置空,并将前端传过来的值赋给手机号的setter方法。
注:js和java实现同效,用的正则表达式不一样
(2)jsp前端中用js进行正则表达式判断。
TeacherController.java
@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Autowired
private ITeacherService teacherService;
@RequestMapping(value="/teacherLogin",method=RequestMethod.POST)
public String teaLogin(Teacher teacher,Model model,HttpServletRequest request) {
HttpSession session = request.getSession();
String teaName=teacher.getTeaName();
String teaPassword=teacher.getTeaPassword();
//判断是邮箱还是手机号的正则表达式
String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";/*注:js和java用正则表达式不一样*/
/*String em ="/^\\w+@\\w+\\.[A-Za-z]{2,3}(\\.[A-Za-z]{2,3})?$/";*/ /*js用正则表达式*/
String ph = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$"; /*java用验证手机号*/
/*测试用代码,前台输入手机号时测试,matches返回true/false*/
/*System.out.println(teaName);
System.out.println(teaName.matches(ph));*/
if(teaName.matches(ph)) {
/*如果匹配上则将教师名置空,并将teaName中的值写到setTeaPhone()方法中*/
teacher.setTeaName(null);
teacher.setTeaPhone(teaName);
/*代码测试用*/
System.out.println(teacher.getTeaPhone());
}else if(teaName.matches(em)) {
teacher.setTeaName(null);
teacher.setTeaEmail(teaName);
}
Teacher teaTem=teacherService.teaLogin(teacher);
if(teaTem==null) {
return "fail";
}
request.getSession().setAttribute("sessionTeacher", teaTem);
return "/manager/manager";
}
}
接口ITeacherService
public interface ITeacherService {
//验证老师登录
public Teacher teaLogin(Teacher teacher);
}
实现接口类TeacherService
@Service("teacherService")
public class TeacherService implements ITeacherService {
@Autowired
private TeacherMapper teacherMapper;
@Override
public Teacher teaLogin(Teacher teacher) {
/*测试用代码*/
/*System.out.println(teacher.getTeaPhone());
System.out.println(teacher.getTeaPassword());
System.out.println(teacher.getTeaName());
System.out.println(teacher.getTeaEmail());*/
return teacherMapper.teaLogin(teacher);
}
}
注:此项目采用面向接口编程,故Dao层也是接口TeacherMapper.java
(面向接口编程,必须xml配置文件的id必须与Dao层java文件中的方法名一致)
public interface TeacherMapper {
//验证老师登录
public Teacher teaLogin(Teacher teacher);
}
TeacherMapper.xml做if test动态sql
(2)jsp前端中用js进行正则表达式判断。
teacherLogin.jsp
```
……
/*js代码:*/