主要是为了以后方便练习
第一天:
项目导入以及用户登录注册和退出
使用idea导入初始项目(maven项目)
项目启动方式一:
项目启动方式二:
注意:在写后面的方法时,出现
java.lang.IllegalArgumentException: Property 'dataSource' is required
需要将工具类JDBCUtils的路径写对了 项目提供的路径是错误的 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("/druid.properties");
// 加载配置文件中的数据
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
用户注册分析:(激活码)
前端部分代码:
<form id="registerForm" ></form>
<script>
//校验用户名:
function checkUserName(){
var username=$("#username").val();
var reg_username=/^\w{8,20}$/;
var flag=reg_username.test(username);
if(flag){
// 用户名合法
$("#username").css("border","");
}else{
// 用户名非法,加一个红色边框
$("#username").css("border","1px solid red");
}
return flag;
}
//校验密码:
function checkPassword(){
var password=$("#password").val();
var reg_password=/^\w{8,20}$/;
var flag=reg_password.test(password);
if(flag){
$("#password").css("border","");
}else{
$("#password").css("border","1px solid red");
}
return flag;
}
//校验邮箱
function checkEmail(){
var email=$("#email").val();
//gyb950209@163.com
var reg_email=/^\w+@\w+\.\w+$/;
var flag=reg_email.test(email);
if(flag){
$("#email").css("border","");
}else{
$("#email").css("border","1px solid red");
}
return flag;
}
//校验姓名
function checkName(){
var name=$("#name").val();
var reg_name=/^\d+$/;
var flag=reg_name.test(name);
if(flag){
$("#name").css("border","");
}else{
$("#name").css("border","1px solid red");
}
return flag;
}
$(function () {
//校验所有的信息
$("#registerForm").submit(function(){
return checkUserName() && checkPassword() &&checkEmail() &&checkName();
});
//校验某个部分
$("#username").blur(checkUserName);
$("#password").blur(checkPassword);
$("#email").blur(checkEmail);
$("#name").blur(checkName);
});
</script>
$("#registerForm").submit(function(){
if(checkUserName() && checkPassword() &&checkEmail() &&checkName()){
//校验通过,发送ajax请求,提交表单数据
$("#registerForm").serialize()
$.post("registerServlet",$(this).serialize(),function () {
});
}
return false;
});
后端部分代码
/**
* 用于封装后端返回前端数据对象
*/
public class ResultInfo implements Serializable {
private boolean flag;//后端返回结果正常为true,发生异常返回false
private Object data;//后端返回结果数据对象
private String errorMsg;//发生异常的错误消息
//无参构造方法
public ResultInfo() {
}
public ResultInfo(boolean flag) {
this.flag = flag;
}
/**
* 有参构造方法
* @param flag
* @param errorMsg
*/
public ResultInfo(boolean flag, String errorMsg) {
this.flag = flag;
this.errorMsg = errorMsg;
}
/**
* 有参构造方法
* @param flag
* @param data
* @param errorMsg
*/
public ResultInfo(boolean flag, Object data, String errorMsg) {
this.flag = flag;
this.data = data;
this.errorMsg = errorMsg;
}
Controller
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//验证校验
String check = request.getParameter("check");
//从sesion中获取验证码
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");//为了保证验证码只能使用一次
//比较
if(checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)){
//验证码错误
ResultInfo info = new ResultInfo();
//注册失败
info.setFlag(false);
info.setErrorMsg("验证码错误");
//将info对象序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
return;
}
//获取数据
Map<String, String[]> map= request.getParameterMap();
User user=new User();
try {
BeanUtils.populate(user,map);
} catch (Exception e) {
e.printStackTrace();
}
UserService service=new UserServiceImpl();
Boolean flag=service.regist(user);
ResultInfo info=new ResultInfo();
if(flag){
//注册成功
info.setFlag(true);
}else{
//注册失败
info.setFlag(false);
info.setErrorMsg("注册失败!");
}
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
service
public class UserServiceImpl implements UserService {
UserDao dao=new UserDaoImpl();
@Override
public Boolean regist(User user) {
//查询用户名是否存在
User u=dao.findUserByUserName(user.getUsername());
if(u !=null){
//存在
return false;
}else{
//保存用户信息
dao.regist(user);
return true;
}
}
}
dao
public class UserDaoImpl implements UserDao {
JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public void regist(User user) {
String sql="insert into tab_user(username,password,name,birthday,sex,telephone,email) value (?,?,?,?,?,?,?)";
template.update(sql,user.getUsername(),user.getPassword(),user.getName(),user.getBirthday(),user.getSex(),
user.getTelephone(),user.getEmail());
}
@Override
public User findUserByUserName(String username) {
User user =null;
try {
String sql="select * from tab_user where username=?";
user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
}catch (Exception e){
}
return user;
}
}
邮件激活
为什么要进行邮件激活?为了保证用户填写的邮箱是正确的.将来可以推广一些宣传信息到用户邮箱中
发送邮件
用户点击邮件激活
不要忘记dao层代码也要修改
Controller
@WebServlet("/activeUserServlet")
public class ActiveUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
UserService service=new UserServiceImpl();
String code = request.getParameter("code");
if(code !=null){
boolean flag=service.active(code);
//3.判断标记
String msg = null;
if(flag){
//激活成功
msg = "激活成功,请<a href='login.html'>登录</a>";
}else{
//激活失败
msg = "激活失败,请联系管理员!";
}
response.setContentType("text/html;charset=utf-8");
response.getWriter().write(msg);
}
}
public boolean active(String code) {
//1.根据激活码查询用户对象
User user = dao.findByCode(code);
if(user != null){
//2.调用dao的修改激活状态的方法
dao.updateStatus(user);
return true;
}else{
return false;
}
}
public User findByCode(String code) {
User user=null;
try{
String sql="select * from tab_user where code=?";
user=template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),code);
}catch (Exception e){
e.printStackTrace();
}
return user;
}
public void updateStatus(User user) {
String sql="update tab_user set status=? where code=?";
template.update(sql,"Y",user.getCode());
}
登录(这里没有写判断验证码了)
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ObjectMapper mapper=new ObjectMapper();
ResultInfo info=new ResultInfo();
UserService service=new UserServiceImpl();
Map<String, String[]> map = request.getParameterMap();
User user=new User();
try {
BeanUtils.populate(user,map);
User u1=service.login(user);
if(u1 ==null){
info.setFlag(false);
info.setErrorMsg("用户名或者密码错误");
}
if(u1 !=null && !"Y".equals(u1.getStatus())){
info.setFlag(false);
info.setErrorMsg("您尚未激活,请激活");
}
if(u1 !=null && "Y".equals(u1.getStatus())){
info.setFlag(true);
}
String json=mapper.writeValueAsString(info);
response.getWriter().write(json);
} catch (Exception e){
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
public User login(User user) {
User u=dao.login(user);
if(u !=null){
return u;
}
return null;
}
<script>
$(function () {
$("#btn").click(function(){
$.post("loginServlet",$("#loginForm").serialize(),function(data){
if(data.flag){
location.href="index.html";
}else {
$("#errorMsg").html(data.errorMsg) ;
}
},"json");
});
});
</script>
<div id="errorMsg" class="alert alert-danger" ></div>
<form id="loginForm" method="post" accept-charset="utf-8">
<button type="button" id="btn">登录</button>
登录成功后,显示欢迎某某
<script>
$(function () {
$.post("welcomeServlet",function(data){
alert(data.name)
var msg="欢迎回来,"+data.name;
$("#welcome").html(msg);
},"json");
});
</script>
<span id="welcome"></span>
@WebServlet("/welcomeServlet")
public class WelcomeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
HttpSession session = request.getSession();
User user=(User)session.getAttribute("user");
ObjectMapper mapper=new ObjectMapper();
String json= mapper.writeValueAsString(user);
System.out.println(json);
response.getWriter().write(json);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
退出
1.将session销毁
2.跳转到登录页面
@WebServlet("/exitServlet")
public class ExitServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getSession().invalidate();
response.sendRedirect(request.getContextPath()+"/login.html");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
<a href="javascript:location.href='exitServlet'" >退出</a>