二、校验
①、用户名不能为空,②、密码不能为空,③、密码和确认密码要一致,④、真实姓名不能为空,⑤、邮箱要满足邮箱验证规则,⑥、电话号码必须是数字,⑦,角色不能为空
1.在获取表单参数之后在保存数据之前校验逻辑加到servlet中。
1.1如果是空要拼错误信息,然后这么多参数拼接到一起比较麻烦,所以要进行封装。由于逻辑判断条件有7条,逐条写比较繁琐,为了提高可读性需要抽取方法。
1.1.1在获取数据前创建getParameter();方法。
1.1.2将数据封装起来。
1.1.3传入参数。
1.1.4创建一个方法接错误信息的返回值。
1.1.5加入检验逻辑,检验通过提示,检验没通过提示。
1.1.6设定响应的内容类型response.setContentType("text/html");
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("进入Registerservlet doPost方法");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
Userinfo u = new Userinfo();
getParameter(request,u);
//校验
String errorMsg = validateUserInfo(u);
if("".equals(errorMsg)){
//调用service层方法进行业务处理
Userservice service = Userservice.getInstance();
service.register(u);
errorMsg = "注册成功";
}
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.write("");
writer.write("
writer.write("
");writer.write(errorMsg);
writer.write("");
writer.write("");
writer.close();
}
private String validateUserInfo(Userinfo u) {
StringBuffer errorMsg = new StringBuffer("");
if(u.getUsername() == null || "".equals(u.getUsername())){
errorMsg.append("用户名不能为空
");
}
if(u.getPassword() == null || "".equals(u.getPassword())){
errorMsg.append("密码不能为空
");
}else{
if(!u.getPassword().equals(u.getConpassword())){
errorMsg.append("密码和确认密码必须一致
");
}
}
if("-1".equals(u.getRole())){
errorMsg.append("角色不能为空
");
}
return errorMsg.toString();
}
private void getParameter(HttpServletRequest request, Userinfo u) {
String username=request.getParameter("username");
String password=request.getParameter("password");
String conPassword=request.getParameter("conPassword");
String realname=request.getParameter("realname");
String email=request.getParameter("email");
String phone=request.getParameter("phone");
String role=request.getParameter("role");
u.setUsername(username);
u.setPassword(conPassword);
u.setRealname(realname);
u.setEmail(email);
u.setPhone(phone);
u.setRole(role);
三、工具类
之前service层只写了注册,由于还有登录等,我们需要一个工具类,将注册等放进去。
1.创建util包,将之前用的DButil包,配置文件,复制过去更改配置文件等值。
2.更改service层,引用工具类。
2.1.1删除之前的驱动加载。
2.1.2c获取到连接,开启事务onn = DButil.getConn();
2.1.3在DButil中将提交,回滚,关闭封装到方法中,throw异常
2.1.4DaoImp中的ps关闭对象的方法也创建在DButil中.
servlet
package www.neuedu.com;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import www.model.bean.Userinfo;
import www.model.service.Userservice;
/**
* Servlet implementation class Registerservlet
*/
public class Registerservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Registerservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request,response);
/**
* HttpServletRequest request当前请求对象
* HttpServletResponse response当前响应对象
*/
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("进入Registerservlet doPost方法");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
/*String method=request.getMethod();
System.out.println("请求方法"+method);
String uri=request.getRequestURI();
System.out.println("请求uri"+uri);
StringBuffer url=request.getRequestURL();
System.out.println("请求url"+url);
Enumeration
while(enums.hasMoreElements()){
String name=enums.nextElement();
String value=request.getHeader(name);
System.out.println(name+"值为"+value);
}
System.out.println("=============");
String path=request.getContextPath();
System.out.println("path值"+path); */
Userinfo u = new Userinfo();
getParameter(request,u);
//校验
String errorMsg = validateUserInfo(u);
if("".equals(errorMsg)){
//调用service层方法进行业务处理
Userservice service = Userservice.getInstance();
service.register(u);
errorMsg = "注册成功";
}
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
writer.write("");
writer.write("
writer.write("
");writer.write(errorMsg);
writer.write("");
writer.write("");
writer.close();
}
private String validateUserInfo(Userinfo u) {
/* 在实现数据保存功能时,要考虑是否需要进行检验
* 用户名不能为空
* 密码不能成为空,密码和确认密码必须一致
* 真实姓名不能为空
* 邮箱必须满足邮箱的规则
* 电话号码必须是数字
* 角色不能为空
*/
StringBuffer errorMsg = new StringBuffer("");
if(u.getUsername() == null || "".equals(u.getUsername())){
errorMsg.append("用户名不能为空
");
}
if(u.getPassword() == null || "".equals(u.getPassword())){
errorMsg.append("密码不能为空
");
}else{
if(!u.getPassword().equals(u.getConpassword())){
errorMsg.append("密码和确认密码必须一致
");
}
}
if("-1".equals(u.getRole())){
errorMsg.append("角色不能为空
");
}
return errorMsg.toString();
}
private void getParameter(HttpServletRequest request, Userinfo u) {
String username=request.getParameter("username");
String password=request.getParameter("password");
String conPassword=request.getParameter("conPassword");
String realname=request.getParameter("realname");
String email=request.getParameter("email");
String phone=request.getParameter("phone");
String role=request.getParameter("role");
u.setUsername(username);
u.setPassword(conPassword);
u.setRealname(realname);
u.setEmail(email);
u.setPhone(phone);
u.setRole(role);
}
}
service
package www.model.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.eclipse.jdt.internal.compiler.batch.Main;
import www.model.bean.Userinfo;
import www.model.dao.UserDaoImp;
import www.model.util.DButil;
public class Userservice
private Userservice(){
} //私有构造器
private static Userservice instance= new Userservice();//私有静态实例变量
public static Userservice getInstance(){//公有静态方法
return instance;//返回对象
}
public void register(Userinfo u) {
Connection conn= null;
try{
//获取到连接,开启事务
conn = DButil.getConn();
UserDaoImp dao = new UserDaoImp();
dao.registerUser(u,conn);
//提交
DButil.commit(conn);
} catch (Exception e) {
//回滚
try {
DButil.rollback(conn);
} catch (SQLException e1) {
e1.printStackTrace();
}
} finally{
try {
DButil.closeConn(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
DButil
package www.model.util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
public class DButil {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static{
try {
Properties pop = new Properties();
InputStream is = null;
is = DButil.class.getClassLoader().getResourceAsStream("db.properties");
try {
pop.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver = pop.getProperty("driver");
url = pop.getProperty("url");
username = pop.getProperty("username");
password = pop.getProperty("password");
System.out.println(driver);
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("数据库崩了");
}
}
public static Connection getConn() throws ClassNotFoundException, SQLException{
//加载驱动
Connection conn = DriverManager.getConnection(url, username, password);
conn.setAutoCommit(false);
return conn;
}
public static void commit(Connection conn) throws SQLException {
conn.commit();
}
public static void rollback(Connection conn) throws SQLException {
conn.rollback();
}
public static void closeConn(Connection conn) throws SQLException {
conn.close();
}
public static void closePs(PreparedStatement ps) throws SQLException {
ps.close();
}
}
四、登录
准备html
准备js
function change2(){
location.href="register.html";
}
function doSubmit(){
//手动提交表单,先拿form再.submit
//document.forms返回页面所有form表单构成的数组
document.forms[0].submit();
}
1.创建loginServlet与创建registerServlet一样
1.1在doPost中写代码设定编码格式,
1.2获取表单参数。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//获取表单参数request.getParameter只能用字符串接返回值
String username =request.getParameter("username");
String password =request.getParameter("password");
2.调用service层代码进行业务处理。
Userinfo user = Userservice.getInstance().login(username, password);
2.1去service层写方法,写登录的方法。
2.1.1获取连接,try catch一下
2.1.2调用dao层,去dao写方法,daoImp重写。
public Userinfo login(String username,String password);
}
2.1.3 daoImp中都有一个参数Connection,将connection提出来,实例化service里拿到的对象,将conn传进创建对象的时候,关闭连接对象。
2.1.4将接口里的conn参数都去掉,将service的多余的conn参数也去掉。
2.1.5dao层加事务,增删改查。
public Userinfo login(String username, String password) {
Userinfo u=null;
PreparedStatement ps;
try {
ps = conn.prepareStatement(" select * from userinfo "
+" where username = ? and password = ? " );
ps.setString(1, password);
ps.setString(2, username);
ResultSet rs = ps.executeQuery();
if(rs.next()){
u = new Userinfo();
u.setUserid(rs.getInt("userid"));
u.setUsername(rs.getString("username"));
u.setPassword(rs.getString("password"));
u.setPhone(rs.getString("phone"));
u.setConpassword(rs.getString("conpassword"));
u.setEmail(rs.getString("email"));
u.setRealname(rs.getString("realname"));
u.setRole(rs.getString("role"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return u;
3.判断登录结果-->弹出的页面,(如果失败跳转到登录页面,如果成功跳入主界面)。