javaWeb 比较完整简单的mvc 注册登录Demo
程序员文章站
2024-02-26 09:35:46
...
这里选择在f盘建一个xml文件当作数据库.最后再把这个数据库换成真实的mysql
实体类
package cn.itcast.user.domain;
/**
* 实体类
* @author Administrator
*
*/
public class User {
private String username;
private String password;
private String verifyCode;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getVerifyCode() {
return verifyCode;
}
public void setVerifyCode(String verifyCode) {
this.verifyCode = verifyCode;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password
+ ", verifyCode=" + verifyCode + "]";
}
public User(String username, String password, String verifyCode) {
super();
this.username = username;
this.password = password;
this.verifyCode = verifyCode;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
}
Dao类
package cn.itcast.user.dao;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import cn.itcast.user.domain.User;
/**
* 数据类
*
* @author Administrator
*
*/
public class UserDao {
private String path = "F:/users.xml"; // 依赖数据文件
/**
* 按用户名查询
*
* @param username
* @return
*/
public User findByUsername(String username) {
/**
* 1.得到Document 2.xpath查询 3.校验查寻结果是否为null 如果为null 返回null
* 4.不为空就把Element封装到User对象中.
*/
// 得到Document
SAXReader reader = new SAXReader();
try {
Document document = reader.read(path);
// 通过xpath查询的到ELement
Element element = (Element) document
.selectSingleNode("//user[@username='" + username + "']");
// 校验
if (element == null)
return null;
// 把element的数据封装到User对象中
User user = new User();
String attrUsername = element.attributeValue("username"); // 获取该元素的名为username的值
String attrPassword = element.attributeValue("password"); // 获取该元素的名为password的值
user.setUsername(attrUsername);
user.setPassword(attrPassword);
return user;
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
/**
* 添加用户
*
* @param user
*/
public void add(User user) {
/*
* 1.得到Document 2.通过Document得到root元素即<users> 3.使用参数user 转换成Element对象
* 4.把Element添加到root元素中 5.保存Document
*/
SAXReader reader = new SAXReader();
try {
Document document = reader.read(path);
// 得到根元素
Element root = document.getRootElement();
// 通过跟元素创建新元素
Element userElement = root.addElement("user");
userElement.addAttribute("username", user.getUsername());
userElement.addAttribute("password", user.getPassword());
// 保存文档
// 创建输出格式化器
OutputFormat format = new OutputFormat("\t", true); // 缩进使用\t
// 是否换行ture
format.setTrimText(true); // 清空原有的换行和缩进
try {
// 创建XMLWriter
XMLWriter writer = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(path), "utf-8"), format);
writer.write(document); // 保存document对象
writer.close();
} catch (Exception e) {
throw new RuntimeException();
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Dao的测试类
package test.dao;
import org.junit.Test;
import cn.itcast.user.dao.UserDao;
import cn.itcast.user.domain.User;
/**
* UserDao的测试
*
* @author Administrator
*
*/
public class UserDaoTest {
@Test
public void testFindByUsername() {
UserDao userDao = new UserDao();
User user = userDao.findByUsername("赵四");
System.out.println(user);
}
@Test
public void testAdd() {
UserDao userDao = new UserDao();
User user = new User();
user.setUsername("王五");
user.setPassword("wangwu");
userDao.add(user);
}
}
Service类
1.自定义User的异常类
package cn.itcast.user.service;
/**
* 自定义一个异常类 只是给出父类的构造器即可 方便用来创建对象
* Alt+Shift+S 然后superClass 再把跟1.7相关的异常类删掉
* @author Administrator
*
*/
public class UserException extends Exception {
public UserException() {
super();
// TODO Auto-generated constructor stub
}
/*这个删掉
* public UserException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}*/
public UserException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public UserException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public UserException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
2.
package cn.itcast.user.service;
import static org.hamcrest.CoreMatchers.nullValue;
import javax.enterprise.inject.New;
import cn.itcast.user.dao.UserDao;
import cn.itcast.user.domain.User;
/**
* User的业务逻辑层
* @author Administrator
*
*/
public class UserService {
private UserDao userDao = new UserDao();
/**
* 注册功能
* @param user
* @throws UserException
*/
public void regist(User user) throws UserException {
/*
* 使用用户名去查询 如果返回null 完成添加
* 如果返回的不是null 抛出异常
*/
User _user = userDao.findByUsername(user.getUsername());
if(_user!=null) throw new UserException("用户名"+ user.getUsername() +",已被注册!");
userDao.add(user);
}
/**
* @param user
* @throws UserException
*
*/
public User login(User form) throws UserException{
/*
* 使用form中的username进行查询 得到User user
*/
User user = userDao.findByUsername(form.getUsername());
//如果返回null 说明用户名不存在 抛出异常 异常信息为"用户名不存在"
if(user == null)throw new UserException("用户名不存在!");
//比较user的password和form的password 如果不同 跑出异常 异常信息为"密码错误"
if(!form.getPassword().equals(user.getPassword())){
throw new UserException("密码错误!");
}
//返回数据库中查询出来的user 而不是form 因为form只有用户名密码 而user有全部信息
return user;
}
}
然后是Servlet类
1.VerifyCodeServlet
package cn.itcast.user.web.servlet;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.vcode.utils.VerifyCode;
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*
* 1.创建验证码类
*/
VerifyCode vc = new VerifyCode();
//得到验证码图片
BufferedImage image = vc.getImage();
//把图片上的文本保存到session中
request.getSession().setAttribute("session_vcode",vc.getText());
//把图片响应给客户端
VerifyCode.output(image, response.getOutputStream());
}
}
2.RegistServlet
package cn.itcast.user.web.servlet;
import static org.hamcrest.CoreMatchers.nullValue;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.commons.CommonUtils;
import cn.itcast.user.domain.User;
import cn.itcast.user.service.UserException;
import cn.itcast.user.service.UserService;
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 依赖USerService
UserService userService = new UserService();
/*
* 1封装表单数据(封装到User对象中)
*/
User form = CommonUtils.toBean(request.getParameterMap(), User.class);
// 用来装载所有错误信息
Map<String, String> errors = new HashMap<String, String>();
// 用户名校验
String username = form.getUsername(); // 获取表单的username
if (username == null || username.trim().isEmpty()) {
errors.put("username", "用户名不能为空");
} else if (username.length() < 3 || username.length() > 15) {
errors.put("username", "用户名长度必须在3-15之间!");
}
// 密码校验
String password = form.getUsername(); // 获取表单的username
if (password == null || password.trim().isEmpty()) {
errors.put("password", "密码不能为空");
} else if (password.length() < 3 || password.length() > 15) {
errors.put("password", "密码长度必须在3-15之间!");
}
//验证码校验
String sessionVerifyCode = (String) request.getSession()
.getAttribute("session_vcode");
String verifyCode = form.getVerifyCode();
if (verifyCode == null || verifyCode.trim().isEmpty()) {
errors.put("verifyCode", "验证码不能为空");
} else if (verifyCode.length()!=4) {
errors.put("verifyCode", "验证码长度必须为4位");
}else if (!verifyCode.equalsIgnoreCase(sessionVerifyCode)) {
errors.put("verifyCode", "验证码错误");
}
/*
* 判断map是否为空 不为空 则存在错误信息
*/
if(errors != null && errors.size()>0){
/*
* 保存errors到request域
* 保存form到request域 为了回显
* 转发到regist.jsp
*/
request.setAttribute("errors", errors);
request.setAttribute("user", form);
request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
return;
}
/*
* 新增功能:检验验证码 1.用户填写的验证码已经封装到user中 2.从session获取真正的验证码 3.对比 不同的话保存错误信息
* 保存表数据 转发到regist.jsp 4 相同就向下执行
*/
/*String sessionVerifyCode = (String) request.getSession()
.getAttribute("session_vcode");
if (!sessionVerifyCode.equalsIgnoreCase(form.getVerifyCode())) {
request.setAttribute("msg", "验证码错误");
request.setAttribute("user", form);
request.getRequestDispatcher("/user/regist.jsp").forward(request,
response);
return;
}*/
/*
* 2.调用userService的regist()方法 传递form过去 3.得到异常:获取异常信息.保存到request域
* 转发到regist.jsp显示 4.没有异常,输出注册成功
*/
try {
userService.regist(form);
response.getWriter()
.print("<h1>注册成功!</h1><a href='" + request.getContextPath()
+ "/user/login.jsp" + "'>点击这里到登录界面</a>");
} catch (UserException e) {
// 获取异常信息,保存到request域
request.setAttribute("msg", e.getMessage());
// 注册失败的时候保存表单数据到request域里
request.setAttribute("user", form);
// 转发到regist.jsp
request.getRequestDispatcher("/user/regist.jsp").forward(request,
response);
}
}
}
3.LoginServlet
package cn.itcast.user.web.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.commons.CommonUtils;
import cn.itcast.user.domain.User;
import cn.itcast.user.service.UserException;
import cn.itcast.user.service.UserService;
/**
* UserServlet层
*
* @author Administrator
*
*/
@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"); //响应编码
//依赖USerService
UserService userService = new UserService();
/*
* 邓庄表单数据到User form中
* 调用service的login()方法 得到返回的User user对象
* 如果跑出异常 获取异常信息 保存到request域中 再保存form 转发到login.jsp
* 如果没有异常 保存返回值到session中 重定向到welcome.jsp
*/
User form = CommonUtils.toBean(request.getParameterMap(), User.class);
try {
User user = userService.login(form);
request.getSession().setAttribute("sessionUser", user);
response.sendRedirect(request.getContextPath() + "/user/welcome.jsp");
} catch (UserException e) {
request.setAttribute("msg", e.getMessage());
request.setAttribute("user", form);
request.getRequestDispatcher("/user/login.jsp").forward(request, response);
}
}
}
最后是界面层
1.regist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'regist.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
function _change(){
//获取img元素
var ele = document.getElementById("vCode");
ele.src = "<c:url value='/VerifyCodeServlet'/>?xxx="+ new Date().getTime();
}
</script>
</head>
<body>
<h1>注册</h1>
<p style="color:red; font-weight: 900">${msg}</p>
<!-- ${pageContext.request.contextPath}/RegistServlet -->
<form action="<c:url value='/RegistServlet'/>" method="post">
用户名:<input type="text" name="username" value="${user.username }"/>${errors.username }<br/>
密 码:<input type="password" name="password" value="${user.password}"/>${errors.password }<br/>
验证码:<input type="text" name="verifyCode" value="${user.verifyCode }" size="3"/>
<img id="vCode" src="<c:url value='/VerifyCodeServlet' />" border="2px" />
<a href="javascript:_change()">换一张</a>${errors.verifyCode}<br/>
<input type="submit" value="注册" />
</form>
</body>
</html>
2.login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>登录</h1>
<p style="color:red; font-weight: 900">${msg}</p>
<!-- ${pageContext.request.contextPath}/RegistServlet -->
<form action="<c:url value='/LoginServlet'/>" method="post">
用户名:<input type="text" name="username" value="${user.username }"/><br/>
密 码:<input type="password" name="password" value="${user.password}"/><br/>
<input type="submit" value="登录" />
</form>
</body>
</html>
3.welcome.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'welcome.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1>欢迎登录本系统</h1>
<c:choose>
<c:when test="${empty sessionScope.sessionUser }">滚!</c:when>
<c:otherwise>
${sessionScope.sessionUser }
</c:otherwise>
</c:choose>
</body>
</html>
利用sql数据库
修改dao层,
1.把上一步写的UserDao改名成UserDaoImpl
2.建立UserDao接口
package cn.itcast.user.dao;
import cn.itcast.user.domain.User;
/**
* UserDao接口
* @author 10958
*
*/
public interface UserDao {
public void add(User user) ;
public User findByUsername(String username);
}
package cn.itcast.user.dao;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import cn.itcast.user.domain.User;
/**
* 数据类
* 持久层
* 用来访问xml文件
* @author Administrator
*
*/
public class UserDaoImpl implements UserDao{
private String path = "F:/users.xml"; // 依赖数据文件
/**
* 按用户名查询
*
* @param username
* @return
*/
public User findByUsername(String username) {
/**
* 1.得到Document 2.xpath查询 3.校验查寻结果是否为null 如果为null 返回null
* 4.不为空就把Element封装到User对象中.
*/
// 得到Document
SAXReader reader = new SAXReader();
try {
Document document = reader.read(path);
// 通过xpath查询的到ELement
Element element = (Element) document
.selectSingleNode("//user[@username='" + username + "']");
// 校验
if (element == null)
return null;
// 把element的数据封装到User对象中
User user = new User();
String attrUsername = element.attributeValue("username"); // 获取该元素的名为username的值
String attrPassword = element.attributeValue("password"); // 获取该元素的名为password的值
user.setUsername(attrUsername);
user.setPassword(attrPassword);
return user;
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
/**
* 添加用户
*
* @param user
*/
public void add(User user) {
/*
* 1.得到Document 2.通过Document得到root元素即<users> 3.使用参数user 转换成Element对象
* 4.把Element添加到root元素中 5.保存Document
*/
SAXReader reader = new SAXReader();
try {
Document document = reader.read(path);
// 得到根元素
Element root = document.getRootElement();
// 通过跟元素创建新元素
Element userElement = root.addElement("user");
userElement.addAttribute("username", user.getUsername());
userElement.addAttribute("password", user.getPassword());
// 保存文档
// 创建输出格式化器
OutputFormat format = new OutputFormat("\t", true); // 缩进使用\t
// 是否换行ture
format.setTrimText(true); // 清空原有的换行和缩进
try {
// 创建XMLWriter
XMLWriter writer = new XMLWriter(new OutputStreamWriter(
new FileOutputStream(path), "utf-8"), format);
writer.write(document); // 保存document对象
writer.close();
} catch (Exception e) {
throw new RuntimeException();
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
3.建立一个dao.properties 存变量
cn.itcast.user.dao.UserDao=cn.itcast.user.dao.JdbcUserDaoImpl
4.写一个DaoFactory 来实现UserDao对象的创建
package cn.itcast.user.dao;
import java.io.InputStream;
import java.util.Properties;
/**
* 返回一个具体UserDao的实现类对象
* 通过配置文件得到dao实现类的名称
* 通过类名称,完成创建类对象(反射完成的)
* @author 10958
*
*/
public class DaoFactory {
private static Properties props = null;
static {
try {
InputStream in = DaoFactory.class.getClassLoader().getResourceAsStream("dao.properties");
props = new Properties();
props.load(in);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static UserDao getUserDao() {
// 得到dao实现类的名称
String daoClassName = props.getProperty("cn.itcast.user.dao.UserDao");
// 通过反射去创建实现类的对象
try {
Class clazz = Class.forName(daoClassName);
return (UserDao) clazz.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
5.引入JdbcUtils工具类和dcconfig.properties变量文件
package cn.itcast.user.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcUtils {
private static Properties props = null;
// 只在JdbcUtils类被加载时执行一次
static {
// 给pros初始化 即加载dbconfig.properties文件到pros
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
props = new Properties();
props.load(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
// 加载驱动类
try {
Class.forName(props.getProperty("driverClassName"));
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
//获取连接
public static Connection getConnection() throws SQLException {
/*
* 1.加载配置文件 2.加载驱动类 3/调用DriverManager.getConnection()
*
*/
// InputStream in =
// JdbcUtils.class.getClassLoader().getResourceAsStream("dbconfig.properties");
// Properties props = new Properties();
// props.load(in);
return DriverManager.getConnection(props.getProperty("url"), props.getProperty("username"),
props.getProperty("password"));
}
}
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/mydb3
username=root
password=123
6.更改UserService里面UserDao的实现
package cn.itcast.user.service;
import static org.hamcrest.CoreMatchers.nullValue;
import javax.enterprise.inject.New;
import cn.itcast.user.dao.DaoFactory;
import cn.itcast.user.dao.UserDao;
import cn.itcast.user.domain.User;
/**
* User的业务逻辑层
*
* @author Administrator
*
*/
public class UserService {
// 把具体的实现类的创建 隐藏到工厂
private UserDao userDao = DaoFactory.getUserDao();
/**
* 注册功能
*
* @param user
* @throws UserException
*/
public void regist(User user) throws UserException {
/*
* 使用用户名去查询 如果返回null 完成添加 如果返回的不是null 抛出异常
*/
User _user = userDao.findByUsername(user.getUsername());
if (_user != null)
throw new UserException("用户名" + user.getUsername() + ",已被注册!");
userDao.add(user);
}
/**
* @param user
* @throws UserException
*
*/
public User login(User form) throws UserException {
/*
* 使用form中的username进行查询 得到User user
*/
User user = userDao.findByUsername(form.getUsername());
// 如果返回null 说明用户名不存在 抛出异常 异常信息为"用户名不存在"
if (user == null)
throw new UserException("用户名不存在!");
// 比较user的password和form的password 如果不同 跑出异常 异常信息为"密码错误"
if (!form.getPassword().equals(user.getPassword())) {
throw new UserException("密码错误!");
}
// 返回数据库中查询出来的user 而不是form 因为form只有用户名密码 而user有全部信息
return user;
}
}
7.最后写一个jdbcUserDaoImpl
package cn.itcast.user.dao;
import java.security.interfaces.RSAKey;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.Normalizer.Form;
import cn.itcast.user.domain.User;
/**针对数据库的实现
* @author 10958
*
*/
public class JdbcUserDaoImpl implements UserDao {
@Override
public void add(User form) {
/*
* 1.得到连接
*/
try {
Connection con = JdbcUtils.getConnection();
//准备sql模版得到pstmt
String sql = "INSERT INTO t_user Values(?,?)";
PreparedStatement pstmt = con.prepareStatement(sql);
//为sql的问号赋值
pstmt.setString(1, form.getUsername());
pstmt.setString(2, form.getPassword());
pstmt.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public User findByUsername(String username) {
try {
Connection con = JdbcUtils.getConnection();
//准备sql模版得到pstmt
String sql = "SELECT * FROM t_user WHERE username=?";
PreparedStatement pstmt = con.prepareStatement(sql);
//为sql的问号赋值
pstmt.setString(1, username);
//执行
ResultSet rs = pstmt.executeQuery();
//把rs转换成User类型返回
if(rs==null){
return null;
}
if(rs.next()){
//转换成User对象返回
//ORM 即对象关系映射
User user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
return user;
}else {
return null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
上一篇: Java的Struts框架中的主题模板和国际化设置
下一篇: java使用gzip实现文件解压缩示例