mybatis 和servlet使用MVC实现用户登录,注册,退出

普通实现:

 

USerMapper.java:

package com.bjsxt.mapper;

import org.apache.ibatis.annotations.Param;

import com.bjsxt.pojo.User;

public interface UserMapper {
	/**
	 * 查询用户的登录信息
	 * @param uname
	 * @param pwd
	 * @return
	 */
	User selUserByNP(@Param("uname") String uname,@Param("pwd") String pwd);
	
	/**
	 * 注册功能实现
	 * @param user
	 * @return
	 */
	int insertUser(User user);
}

 

USerMapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
	 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
	 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjsxt.mapper.UserMapper">
	<select id="selUserByNP" resultType="User" parameterType="string">
		select * from t_user where uname=#{uname} and pwd=#{pwd}
	</select>
	
	<insert id="insertUser" parameterType="User">
		insert into t_user values(default,#{uname},#{pwd},#{sex},#{age},#{birthday})
	</insert>
</mapper>

 

实体类:

package com.bjsxt.pojo;

public class User {
	private int uid;
	private String uname;
	private String pwd;
	private String sex;
	private int age;
	private String birthday;
	public int getUid() {
		return uid;
	}
	public void setUid(int uid) {
		this.uid = uid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String uname) {
		this.uname = uname;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getBirthday() {
		return birthday;
	}
	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result
				+ ((birthday == null) ? 0 : birthday.hashCode());
		result = prime * result + ((pwd == null) ? 0 : pwd.hashCode());
		result = prime * result + ((sex == null) ? 0 : sex.hashCode());
		result = prime * result + uid;
		result = prime * result + ((uname == null) ? 0 : uname.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (age != other.age)
			return false;
		if (birthday == null) {
			if (other.birthday != null)
				return false;
		} else if (!birthday.equals(other.birthday))
			return false;
		if (pwd == null) {
			if (other.pwd != null)
				return false;
		} else if (!pwd.equals(other.pwd))
			return false;
		if (sex == null) {
			if (other.sex != null)
				return false;
		} else if (!sex.equals(other.sex))
			return false;
		if (uid != other.uid)
			return false;
		if (uname == null) {
			if (other.uname != null)
				return false;
		} else if (!uname.equals(other.uname))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "User [uid=" + uid + ", uname=" + uname + ", pwd=" + pwd
				+ ", sex=" + sex + ", age=" + age + ", birthday=" + birthday
				+ "]";
	}
	public User() {
		super();
	}
	public User(int uid, String uname, String pwd, String sex, int age,
			String birthday) {
		super();
		this.uid = uid;
		this.uname = uname;
		this.pwd = pwd;
		this.sex = sex;
		this.age = age;
		this.birthday = birthday;
	}
	
}

 

UserService,java:

package com.bjsxt.service;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.bjsxt.pojo.User;

public interface UserService {
	/**
	 * 查询用户的登录信息
	 * @param uname
	 * @param pwd
	 * @return
	 */
	User selUserByNP(@Param("uname") String uname,@Param("pwd") String pwd);
	
	/**
	 * 注册功能实现
	 * @param user
	 * @return
	 */
	int insertUser(User user);
}

 

UserServiceImpl:

package com.bjsxt.service.impl;

import org.apache.ibatis.session.SqlSession;

import com.bjsxt.mapper.UserMapper;
import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import com.bjsxt.util.MyBatisUtil;

public class UserServiceImpl implements UserService{

	@Override
	public User selUserByNP(String uname, String pwd) {
		SqlSession session = MyBatisUtil.getSession();
		UserMapper mapper = session.getMapper(UserMapper.class);
		User selUserByNP = mapper.selUserByNP(uname, pwd);
		return selUserByNP;
	}

	@Override
	public int insertUser(User user) {
		SqlSession session = MyBatisUtil.getSession();
		UserMapper mapper = session.getMapper(UserMapper.class);
		int insertnum = mapper.insertUser(user);
		return insertnum;
	}

}

 

登录(UserServlet):

package com.bjsxt.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import com.bjsxt.service.impl.UserServiceImpl;

public class UserServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码
		req.setCharacterEncoding("utf-8");
		//设置响应编码:
		resp.setContentType("text/html;charset=utf-8");
		//获取请求数据
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		//处理请求数据
			UserService us=new UserServiceImpl();
			User user = us.selUserByNP(uname, pwd);
		//响应浏览器
			//创建session
			HttpSession session = req.getSession();
				if (user!=null) {
					session.setAttribute("User", user);
					//登录成功 重定向到main.jsp
					resp.sendRedirect("/15/main.jsp");
				} else {
					session.setAttribute("flag", "loginfalse");
					//登录失败 返回登录界面,并且给上失败标记
					resp.sendRedirect("/15/login.jsp");
					
				}
	}
}

 

注册(RegServlet)

package com.bjsxt.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import com.bjsxt.service.impl.UserServiceImpl;

public class RegServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码
		req.setCharacterEncoding("utf-8");
		//设置响应编码:
		resp.setContentType("text/html;charset=utf-8");
		//获取请求数据
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String sex = req.getParameter("sex");
		int age = Integer.parseInt(req.getParameter("age"));
		String birthday = req.getParameter("birthday");
		
		//处理请求信息
		User user=new User();
		user.setUname(uname);
		user.setPwd(pwd);
		user.setSex(sex);
		user.setAge(age);
		user.setBirthday(birthday);
		UserService us=new UserServiceImpl();
		int num = us.insertUser(user);
		//响应处理结构
		if (num>0) {
			//注册成功,重定向到登录界面,添加一个注册成功的标签
			HttpSession session = req.getSession();
			session.setAttribute("flag", "regsuccess");
			resp.sendRedirect("/15/login.jsp");
		} else {
			//注册失败重定向到
			resp.sendRedirect("/15/reg.jsp");
		}
	}
}

 

退出(OutServlet

package com.bjsxt.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class OutServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式:
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式:
		resp.setContentType("text/html;charset=utf-8");
		//没有请求数据
		//设置响应数据
		HttpSession session = req.getSession();
		session.invalidate();
		//响应浏览器
		resp.sendRedirect("/15/login.jsp");
	}
}

 

工具类(MyBatisUtil   默认自动提交数据

package com.bjsxt.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {
	private static SqlSessionFactory factory=null;
	static{
		try {
			InputStream	is = Resources.getResourceAsStream("mybatis-cfg.xml");
			 factory = new SqlSessionFactoryBuilder().build(is);

		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	public static SqlSession getSession() {
		SqlSession session =null;
		if (factory!=null) {
			 session = factory.openSession(true);
		}
		return session;
	}
}

 

mybaties-cfg.xml(配置文件)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
  <configuration>
  <!-- properties加载配置文件
   -->
  <properties resource="db.properties"></properties>
  <settings>
  	<setting name="logImpl" value="LOG4J"/>
  </settings>
  <typeAliases>
  	<package name="com.bjsxt.pojo"/>
  </typeAliases>
  	<environments default="dev">
 		<environment id="dev">
 			<transactionManager type="JDBC"/>
 			<dataSource type="POOLED">
 				<property name="driver" value="${jdbc.driver}"/>
 				<property name="url" value="${jdbc.url}"/>
 				<property name="username" value="${jdbc.username}"/>
 				<property name="password" value="${jdbc.password}"/>
 			</dataSource>
 		</environment>
  	</environments>
  	<mappers >
  		<package name="com.bjsxt.mapper"/>
  	</mappers>
  </configuration>

 

login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
	<base href="<%=basePath%>">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="renderer" content="webkit">
    <title>登录</title>  
    <link rel="stylesheet" href="css/pintuer.css">
    <link rel="stylesheet" href="css/admin.css">
    <script src="js/jquery.js"></script>
    <script src="js/pintuer.js"></script>  
</head>
<body>
<div class="bg"></div>
<div class="container">
    <div class="line bouncein">
        <div class="xs6 xm4 xs3-move xm4-move">
            <div style="height:150px;"></div>
            <div class="media media-y margin-big-bottom">           
            </div>         
            <form action="use" method="post">
            <div class="panel loginbox">
                <div class="text-center margin-big padding-big-top"><h1>后台管理中心</h1></div>
                <!-- 声明java代码块 -->
                <%
                	Object obj=session.getAttribute("flag");
                	if(obj!=null){
                		if("loginfalse".equals((String)obj)){	
			                	%>
			             
			                	<div style="color: red;text-align: center;">用户名或密码错误</div>
			                	
			                	<%
                		}else if("regsuccess".equals((String)obj)){
                				%>
			                	
			                	 <div style="color: red;text-align: center;">用户注册成功</div>
			                	
			                	<%
                		}
              	  	}
                	session.invalidate();
                 %>
               
                <div class="panel-body" style="padding:30px; padding-bottom:10px; padding-top:10px;">
                    <div class="form-group">
                        <div class="field field-icon-right">
                            <input type="text" class="input input-big" name="uname" placeholder="登录账号" data-validate="required:请填写账号" />
                            <span class="icon icon-user margin-small"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="field field-icon-right">
                            <input type="password" class="input input-big" name="pwd" placeholder="登录密码" data-validate="required:请填写密码" />
                            <span class="icon icon-key margin-small"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="field">
                            <input type="text" class="input input-big" name="code" placeholder="填写右侧的验证码" data-validate="required:请填写右侧的验证码" />
                           <img src="images/passcode.jpg" alt="" width="100" height="32" class="passcode" style="height:43px;cursor:pointer;" onclick="this.src=this.src+'?'">  
                                                   
                        </div>
                    </div>
                </div>
                <div style="padding:30px;">
	                <input type="submit" class="button button-block bg-main text-big input-big" value="登录">
	                <br>
	  				<div style="font-size: 20px;font-family:'楷体';font-weight: bold; text-align: center;"><a href="reg.jsp" >还有没账号?免费注册</a></div>
  				 </div>
            </div>
            </form>          
        </div>
    </div>
</div>

</body>
</html>

 

reg.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title></title>
<link rel="stylesheet" href="css/pintuer.css">
<link rel="stylesheet" href="css/admin.css">
<script src="js/jquery.js"></script>
<script src="js/pintuer.js"></script>
<!-- 声明js代码域,用于性别的选择-->
<script type="text/javascript">
	$(function(){
	
		$("#man").click(function(){
			//给男的加上选择状态加上
			$("#manSpan").addClass("icon-check");
			//将女的选择状态去掉
			$("#womanSpan").removeClass("icon-check");
		})
		
		$("#woman").click(function(){
			//将女的选择状态加上
			$("#womanSpan").addClass("icon-check");
			//将男的选择状态去掉
			$("#manSpan").removeClass("icon-check");
		})
	})
</script>
</head>
<body>
<div class="panel admin-panel">
  <div class="panel-head"><strong><span class="icon-key"></span>用户注册</strong></div>
  <div class="body-content">
    <form method="post" class="form-x" action="reg"> 
       <div class="form-group">
        <div class="label">
          <label for="sitename">账号:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50" id="uname" name="uname" size="50" placeholder="请输入账号" data-validate="required:请输入账号" />       
        </div>
      </div>  
         
      <div class="form-group">
        <div class="label">
          <label for="sitename">密码:</label>
        </div>
        <div class="field">
          <input type="password" class="input w50" name="pwd" size="50" placeholder="请输入密码" data-validate="required:请输入密码,length#>=5:密码不能小于5位" />         
        </div>
      </div>
      
      <div class="form-group">
        <div class="label">
          <label for="sitename">确认密码:</label>
        </div>
        <div class="field">
          <input type="password" class="input w50" size="50" placeholder="请再次输入密码" data-validate="required:请再次输入密码,repeat#pwd:两次输入的密码不一致" />          
        </div>
      </div>
      
      <div class="form-group">
        <div class="label">
          <label>性别:</label>
        </div>
        <div class="field">
          <div class="button-group radio">
          
	          <label class="button active">
	         	  <span class="icon-check" id="manSpan"></span>             
	              <input name="sex" id="man" value="男" type="radio" checked="checked">男             
	          </label>             
        
	          <label class="button active">
	          	  <span class=""  id="womanSpan"></span>          	
	              <input name="sex" id="woman" value="女"  type="radio">女
	          </label>         
           </div>       
        </div>
     </div>
     
        <div class="form-group">
        <div class="label">
          <label for="sitename">年龄:</label>
        </div>
        <div class="field">
          <input type="text" class="input w50" name="age" size="50" />         
        </div>
      </div>
      
      <div class="form-group">
        <div class="label">
          <label for="sitename">出生日期:</label>
        </div>
        <div class="field">
          <input type="date" class="input w50" name="birthday" size="50" />         
        </div>
      </div>
      <div class="form-group">
        <div class="label">
          <label></label>
        </div>
        <div class="field">
          <button class="button bg-main icon-check-square-o" type="submit"> 提交</button>   
        </div>
      </div>      
    </form>
  </div>
</div>
</body></html>

 

main.jsp(主页面)

<%@ page language="java" import="java.util.*,com.bjsxt.pojo.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="zh-cn">
<head>
 	<base href="<%=basePath%>">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="renderer" content="webkit">
    <title>后台管理中心</title>  
    <link rel="stylesheet" href="css/pintuer.css">
    <link rel="stylesheet" href="css/admin.css">
    <script src="js/jquery.js"></script>  
    <!-- 声明js代码域,处理退出登录 -->
    <script type="text/javascript">
    	$(function(){
    		$("#out").click(function(){
    			var flag= window.confirm("你确定要离开我们吗~~");
    			if(flag){
    				return window.confirm("嘤嘤嘤~~~~  真的确定要走了么???");
    			}
    		})
    	})
    </script> 
</head>
<body style="background-color:#f2f9fd;">
<div class="header bg-main">
  <div class="logo margin-big-left fadein-top">
    <h1><img src="images/y.jpg" class="radius-circle rotate-hover" height="50" alt="" />后台管理中心</h1>
  </div>
  <div class="head-l" style="position: relative;left: 1050px"><span style="font-size: 20px;color: white;">当前用户:<%=((User)session.getAttribute("User")).getUname()%></span>&nbsp&nbsp<a id="out" class="button button-little bg-red" href="out"><span class="icon-power-off"></span> 退出登录</a> </div>
</div>
<div class="leftnav">
  <div class="leftnav-title"><strong><span class="icon-list"></span>菜单列表</strong></div>
  <h2><span class="icon-user"></span>基本设置</h2>
  <ul style="display:block">
    <li><a href="info.jsp" target="right"><span class="icon-caret-right"></span>网站设置</a></li>
    <li><a href="pass.html" target="right"><span class="icon-caret-right"></span>修改密码</a></li>
    <li><a href="page.html" target="right"><span class="icon-caret-right"></span>单页管理</a></li>  
    <li><a href="adv.html" target="right"><span class="icon-caret-right"></span>首页轮播</a></li>   
    <li><a href="book.html" target="right"><span class="icon-caret-right"></span>留言管理</a></li>     
    <li><a href="column.html" target="right"><span class="icon-caret-right"></span>栏目管理</a></li>
  </ul>   
  <h2><span class="icon-pencil-square-o"></span>栏目管理</h2>
  <ul>
    <li><a href="list.html" target="right"><span class="icon-caret-right"></span>内容管理</a></li>
    <li><a href="add.html" target="right"><span class="icon-caret-right"></span>添加内容</a></li>
    <li><a href="cate.html" target="right"><span class="icon-caret-right"></span>分类管理</a></li>        
  </ul>  
</div>
<script type="text/javascript">
$(function(){
  $(".leftnav h2").click(function(){
	  $(this).next().slideToggle(200);	
	  $(this).toggleClass("on"); 
  })
  $(".leftnav ul li a").click(function(){
	    $("#a_leader_txt").text($(this).text());
  		$(".leftnav ul li a").removeClass("on");
		$(this).addClass("on");
  })
});
</script>
<ul class="bread">
  <li><a href="{:U('Index/info')}" target="right" class="icon-home"> 首页</a></li>
  <li><a href="##" id="a_leader_txt">网站信息</a></li>
  <li><b>当前语言:</b><span style="color:red;">中文</php></span>
  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;切换语言:<a href="##">中文</a> &nbsp;&nbsp;<a href="##">英文</a> </li>
</ul>
<div class="admin">
  <iframe scrolling="auto" rameborder="0" src="info.jsp" name="right" width="100%" height="100%"></iframe>
</div>
<div style="text-align:center;">
<p>来源:<a href="http://www.mycodes.net/" target="_blank">源码之家</a></p>
</div>
</body>
</html>

这就是我们简单的登录,注册,退出操作。看到servlet,就知道,这样会导致代码冗余。我们就将servlet方法提取到一起

合成一个DataServlet,

package com.bjsxt.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;
import com.bjsxt.service.impl.UserServiceImpl;

public class DateServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
		//获取请求信息
		String methodName=req.getParameter("method");
		//调用方法处理请求(动态根据方法名调用方法--->反射)
		try {
			Class cla = this.getClass();
			//反射获取要被调用的方法对象
			Method m = cla.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//调用反射的方法
			m.invoke(this, req,resp);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	//登录处理方法
	public void userLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		System.out.println("DataServlet.userLogin(开始处理用户登录请求)");
		//获取请求数据
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		//处理请求数据
		UserService us=new UserServiceImpl();
		User user = us.selUserByNP(uname, pwd);
		//响应浏览器
		//创建session
		HttpSession session = req.getSession();
		if (user!=null) {
			session.setAttribute("User", user);
			//登录成功 重定向到main.jsp
			resp.sendRedirect("/155/main.jsp");
		} else {
			session.setAttribute("flag", "loginfalse");
			//登录失败 返回登录界面,并且给上失败标记
			resp.sendRedirect("/155/login.jsp");

		}
	}
	//退出处理方法
	public void userOut(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		System.out.println("DataServlet.userOut(用户退出开始处理)");
		//设置响应数据
		HttpSession session = req.getSession();
		session.invalidate();
		//响应浏览器
		resp.sendRedirect("/155/login.jsp");


	}
	//注册处理方法
	public void userReg(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		System.out.println("DataServlet.userReg(用户注册开始处理)");
		//获取请求数据
		String uname = req.getParameter("uname");
		String pwd = req.getParameter("pwd");
		String sex = req.getParameter("sex");
		int age = Integer.parseInt(req.getParameter("age"));
		String birthday = req.getParameter("birthday");

		//处理请求信息
		User user=new User();
		user.setUname(uname);
		user.setPwd(pwd);
		user.setSex(sex);
		user.setAge(age);
		user.setBirthday(birthday);
		UserService us=new UserServiceImpl();
		int num = us.insertUser(user);
		//响应处理结构
		if (num>0) {
			//注册成功,重定向到登录界面,添加一个注册成功的标签
			HttpSession session = req.getSession();
			session.setAttribute("flag", "regsuccess");
			resp.sendRedirect("/155/login.jsp");
		} else {
			//注册失败重定向到
			resp.sendRedirect("/155/reg.jsp");
		}
	}
}

dateServlet中我们是用动态获取方法,因此我们在jsp上面懂了手脚:


 

我们给他设置一个隐藏标签,提交表单,隐藏标签也是会提交的,我们在dateservlet中,使用method去获取方法名称。

 

在这种方法,我们还是会瑕疵,于是,我们又新建应该servlet,用来装向上抽取servlet的方法:

package com.bjsxt.servlet;

import java.io.IOException;
import java.lang.reflect.Method;

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

public abstract class DataServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		//设置请求编码格式
		req.setCharacterEncoding("utf-8");
		//设置响应编码格式
		resp.setContentType("text/html;charset=utf-8");
		//获取请求信息
		String methodName=req.getParameter("method");
		//调用方法处理请求(动态根据方法名调用方法--->反射)
		try {
			Class cla = this.getClass();
			//反射获取要被调用的方法对象
			Method m = cla.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//调用反射的方法
			m.invoke(this, req,resp);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}

我们看运行的截图:

 

登录截图:

 

注册截图

 

主页面:

 

退出效果:

点击确定会继续挽留。

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值