JAVA web中的一些代码应用
分开jsp页面
- 在html中不能写jsp的代码
- ${pageContext.resquest.ContextPath}相当于/chatper06
- jsp的动作元素
- jsp:forward</jsp:forward>
写一个index.jsp,跳到首页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<jsp:forward page="client/index.jsp"></jsp:forward>
</body>
</html>
foot.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<div id="divfoot">
<table width="100%" border="0" cellspacing="0">
<tr>
<td rowspan="2" style="width: 10%"><img
src="${pageContext.request.contextPath}/client/images/logo.png"
width="195" height="50" style="margin-left: 175px" />
</td>
<td style="padding-top: 5px; padding-left: 50px"><a href="#">
<font color="#747556"><b>CONTACT US</b> </font> </a>
</td>
</tr>
<tr>
<td style="padding-left: 50px"><font color="#CCCCCC"> <b>COPYRIGHT
2015 © BookStore All Rights RESERVED.</b> </font>
</td>
</tr>
</table>
</div>
head.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<div id="divhead">
<table cellspacing="0" class="headtable">
<tr>
<td>
<a href="index.jsp">
<img src="${pageContext.request.contextPath}/client/images/logo.png" width="200" height="60" border="0" />
</a>
</td>
<td style="text-align:right">
<img src="${pageContext.request.contextPath}/client/images/cart.gif" width="26" height="23" style="margin-bottom:-4px" /> <a href="#">购物车</a>
| <a href="#">帮助中心</a>
| <a href="#">我的帐户</a>
| <a href="${pageContext.request.contextPath}/client/register.jsp">新用户注册</a>
</td>
</tr>
</table>
</div>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/client/css/main.css" type="text/css" />
<!-- 导入首页轮播图css和js脚本 -->
<link type="text/css" href="${pageContext.request.contextPath}/client/css/autoplay.css" rel="stylesheet" />
<script type="text/javascript" src="${pageContext.request.contextPath}/client/js/autoplay.js"></script>
</head>
<body class="main">
<!-- 1.网上书城顶部 start -->
<%@include file="head.jsp"%>
<!-- 网上书城顶部 end -->
<!-- 2.网上书城菜单列表 start -->
<%@include file="menu_search.jsp" %>
<!-- 网上书城菜单列表 end -->
<!-- 3.网上书城首页轮播图 start -->
<div id="box_autoplay">
<div class="list">
<ul>
<li><img src="${pageContext.request.contextPath}/client/ad/index_ad1.jpg" width="900" height="335" /></li>
<li><img src="${pageContext.request.contextPath}/client/ad/index_ad2.jpg" width="900" height="335" /></li>
<li><img src="${pageContext.request.contextPath}/client/ad/index_ad3.jpg" width="900" height="335" /></li>
<li><img src="${pageContext.request.contextPath}/client/ad/index_ad4.jpg" width="900" height="335" /></li>
<li><img src="${pageContext.request.contextPath}/client/ad/index_ad5.jpg" width="900" height="335" /></li>
</ul>
</div>
</div>
<!-- 网上书城首页轮播图 end -->
<!-- 4.公告板和本周热卖 start -->
<div id="divcontent">
<table width="900px" border="0" cellspacing="0">
<tr>
<td width="497">
<img src="${pageContext.request.contextPath}/client/images/billboard.gif" width="497" height="38" />
<table cellspacing="0" class="ctl">
<tr>
<td width="485" height="29">
尊敬的网上书城用户, <br>
为了让大家有更好的购物体验,3月25日起,当日达业务关小黑屋回炉升级!<br>具体开放时间请留意公告,感谢大家的支持与理解,祝大家购物愉快!<br>
3月23日<br>
传智播客 网上书城系统管理部<br>
</td>
</tr>
</table>
</td>
<td style="padding:5px 15px 10px 40px">
<table width="100%" border="0" cellspacing="0">
<tr>
<td>
<img src="${pageContext.request.contextPath}/client/images/hottitle.gif" width="126" height="29" />
</td>
</tr>
</table>
<table width="100%" border="0" cellspacing="0">
<tr>
<td style="width:80; text-align:center">
<a href="#">
<img src="${pageContext.request.contextPath}/client/bookcover/105.jpg" width="102" height="130" border="0" />
</a>
<br />
</td>
<td style="width:80; text-align:center">
<a href="#">
<img src="${pageContext.request.contextPath}/client/bookcover/106.jpg" width="102" height="130" border="0" />
</a>
<br />
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<!-- 公告板和本周热卖 end -->
<!--5. 网上书城底部 start -->
<%@ include file="foot.jsp" %>
<!-- 网上书城底部 end -->
</body>
</html>
menu_search.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<div id="divmenu">
<a href="#">文学</a>
<a href="#">生活</a>
<a href="#">计算机</a>
<a href="#">外语</a>
<a href="#">经管</a>
<a href="#">励志</a>
<a href="#">社科</a>
<a href="#">学术</a>
<a href="#">少儿</a>
<a href="#">艺术</a>
<a href="#">原版</a>
<a href="#">科技</a>
<a href="#">考试</a>
<a href="#">生活百科</a>
<a href="#" style="color:#FFFF00">全部商品目录</a>
</div>
<div id="divsearch">
<form action="#" id="searchform">
<table width="100%" border="0" cellspacing="0">
<tr>
<td style="text-align:right; padding-right:220px">
Search
<input type="text" name="textfield" class="inputtable" id="textfield" value="请输入书名"
onmouseover="this.focus();"
onclick="my_click(this, 'textfield');"
onBlur="my_blur(this, 'textfield');"/>
<a href="#">
<img src="${pageContext.request.contextPath}/client/images/serchbutton.gif" border="0" style="margin-bottom:-4px" onclick="search()"/>
</a>
</td>
</tr>
</table>
</form>
</div>
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户注册</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/client/css/main.css" type="text/css" />
<script type="text/javascript" src="${pageContext.request.contextPath}/client/js/form.js"></script>
</head>
<body class="main">
<!-- 1.网上书城顶部 start -->
<%@include file="head.jsp"%>
<!-- 网上书城顶部 end -->
<!--2. 网上书城菜单列表 start -->
<%@include file="menu_search.jsp" %>
<!-- 网上书城菜单列表 end -->
<!-- 3.网上书城用户注册 start -->
<div id="divcontent" align="center">
<form action="${pageContext.request.contextPath}/client/registersuccess.jsp" method="post" onsubmit="return checkForm();">
<table width="850px" border="0" cellspacing="0">
<tr>
<td style="padding: 30px"><h1>新会员注册</h1>
<table width="70%" border="0" cellspacing="2" class="upline">
<tr>
<td style="text-align: right; width: 20%">会员邮箱:</td>
<td style="width: 40%">
<input type="text" class="textinput" id="email" name="email" onkeyup="checkEmail();"/>
</td>
<td colspan="2"><span id="emailMsg"></span><font color="#999999">请输入有效的邮箱地址</font></td>
</tr>
<tr>
<td style="text-align: right">会员名:</td>
<td><input type="text" class="textinput" id="username" name="username" onkeyup="checkUsername();"/>
</td>
<td colspan="2"><span id="usernameMsg"></span><font color="#999999">字母数字下划线1到10位, 不能是数字开头</font></td>
</tr>
<tr>
<td style="text-align: right">密码:</td>
<td><input type="password" class="textinput" id="password" name="password" onkeyup="checkPassword();"/></td>
<td><span id="passwordMsg"></span><font color="#999999">密码请设置6-16位字符</font></td>
</tr>
<tr>
<td style="text-align: right">重复密码:</td>
<td>
<input type="password" class="textinput" id="repassword" name="repassword" onkeyup="checkConfirm();"/>
</td>
<td><span id="confirmMsg"></span> </td>
</tr>
<tr>
<td style="text-align: right">性别:</td>
<td colspan="2">
<input type="radio" name="gender" value="男" checked="checked" /> 男
<input type="radio" name="gender" value="女" /> 女
</td>
<td> </td>
</tr>
<tr>
<td style="text-align: right">联系电话:</td>
<td colspan="2">
<input type="text" class="textinput"
style="width: 350px" name="telephone" />
</td>
<td> </td>
</tr>
<tr>
<td style="text-align: right">个人介绍:</td>
<td colspan="2">
<textarea class="textarea" name="introduce"></textarea>
</td>
<td> </td>
</tr>
</table>
<table width="70%" border="0" cellspacing="0">
<tr>
<td style="padding-top: 20px; text-align: center">
<input type="image" src="images/signup.gif" name="submit" border="0"/>
</td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</div>
<!-- 网上书城用户注册 end -->
<!--4. 网上书城下方显示 start -->
<%@ include file="foot.jsp" %>
<!-- 网上书城下方显示 start -->
</body>
</html>
registersuccess.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>success page</title>
</head>
<body>
<center>
<font color="green" size="7">注册成功</font>
</center>
</body>
</html>
使用Filter的简单自动登录
因为Cookie可以实现用户的自动登录功能
使用到的文件:index.jsp;login.jsp;AutoLoginFilter: LoginServlet;LogoutServlet.配置文件web.xml
index.jsp;User
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>显示用户登录信息</title>
</head>
<body>
<br/>
<center>
<h3>欢迎光临</h3>
</center>
<br/>
<br/>
<c:choose>
<c:when test="${sessionScope.user.null}">
<a href="${pageContext.request.contextPath}/login.jsp">用户登录</a>
</c:when>
<c:otherwise>
欢迎您:${sessionScope.user.username}!
<a href="${pageContext.request.contextPath}/LogoutServlet">注销</a>
</c:otherwise>
</c:choose>
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>登录</title>
<center><h3>用户登录</h3></center>
</head>
<body>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
<table border="1" width="600px" cellpadding="0" cellspacing="0" align="center">
<tr>
<td height="30" align="center">用户名:</td>
<td> <input type="text" name="username">${errerMsg}</td>
</tr>
<tr>
<td height="30" align="center">密 码:</td>
<td>
<input type="password" name="password"></td>
</tr>
<tr>
<td height="35" align="center">自动登录时间</td>
<td>
<input type="radio" name="autologin" value="${60*60*24*31}">一个月
<input type="radio" name="autologin" value="${60*60*24*31*3}">三个月
<input type="radio" name="autologin" value="${60*60*24*31*6}">六个月
<input type="radio" name="autologin" value="${60*60*24*31*12}">一年
</td>
</tr>
<tr>
<td height="30" colspan="2" align="center">
<input type="submit" value="登录"/>
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
AutoLoginFilter
package com.yue.chapter08.Servlet;
import com.yue.chapter08.pojo.User;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class AutoLoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//获得一个名为autologin的cookie
HttpServletRequest req = (HttpServletRequest) servletRequest;
Cookie[] cookies = req.getCookies();
String autologin = null;
for(int i= 0 ;cookies != null && i < cookies.length; i++){
if("autologin".equals(cookies[i].getName())){
//找到指定的cookie
autologin = cookies[i].getValue();
break;
}
}
if(autologin != null){
//做自动登录
String[] split = autologin.split("-");
String username = split[0];
String password = split[1];
//检查用户名和密码
if("itcast".equals(username) && "123456".equals(password)){
//登录成功,将用户状态user对象装入seesion域中
User user = new User();
user.setPassword(password);
user.setUsername(username);
req.getSession().setAttribute("user",user);
}
}
filterChain.doFilter(req,servletResponse);
}
@Override
public void destroy() {
}
}
loginServlet
package com.yue.chapter08.Servlet;
import com.yue.chapter08.pojo.User;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获得用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//检查用户名和密码
if("itcast".equals(username)&&"123456".equals(password)){
//登录状态
//将用户状态user对象加入Session域中
User user = new User();
user.setUsername(username);
user.setPassword(password);
req.getSession().setAttribute("user",user);
//发送自动登录的cookie
String autologin = req.getParameter("autologin");
if(autologin != null){
//注意cookie中的密码要加密
Cookie autologin1 = new Cookie("autologin", username + "_" + password);
autologin1.setMaxAge(Integer.parseInt(autologin));
autologin1.setPath(req.getAuthType());
resp.addCookie(autologin1);
}
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}else {
req.setAttribute("errerMsg","用户名或密码错误");
RequestDispatcher requestDispatcher = req.getRequestDispatcher("login.jsp");
requestDispatcher.forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
LogoutServlet
package com.yue.chapter08.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//用户注销
req.getSession().removeAttribute("user");
//从客户端删除自动登录的cookie
//重新设置一个cookie去覆盖它
Cookie autologin = new Cookie("autologin", "");
autologin.setMaxAge(0);
autologin.setPath(req.getContextPath());
resp.addCookie(autologin);
resp.sendRedirect(req.getContextPath()+ "/index.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
User
package com.yue.chapter08.pojo;
public class User {
private String username;
private String password;
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;
}
}
web.xml
<filter>
<filter-name>AutoLoginFilter</filter-name>
<filter-class>com.yue.chapter08.Servlet.AutoLoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutoLoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.yue.chapter08.Servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.yue.chapter08.Servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
使用Filter实现统一全站编码
根据请求的方式不同, 对请求进行不同的中文乱码的方式不同,post的请求消息参数在消息体中,只需req.setCharacterEncoding("Utf-8);而对于get方法的请求:它的参数在url地址的后面,所以以采用不同的方式,
- String v = req.getParmater(“username”);
- 使用String的构造方式进行处理中文乱码 new String(v.getBytes(“iso-8859-1”),“utf-8”);
- 这样就可以解决中文乱码问题
- 但是参数过多的话,就会导致麻烦,所以使用装配这设计模式,进行增强getParameter()方法的方式
form.jsp
<%--
Created by IntelliJ IDEA.
User: 岳振彪
Date: 2020/6/15
Time: 21:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<center>
<h3>用户登录</h3>
</center>
</head>
<body style="text-align: center">
<a href="<%=request.getContextPath()%>/CharacterServlet?username=晨晨&password=123">超链接</a>
<form action="<%=request.getContextPath()%>/CharacterServelt" method="post">
<table border="1" width="600px" cellpadding="0" cellspacing="0" align="center">
<tr>
<td height="30" align="center">用户名:</td>
<td> <input type="text" name="username">${errerMsg}</td>
</tr>
<tr>
<td height="30" align="center">密 码:</td>
<td>
<input type="password" name="password"></td>
</tr>
<tr>
<td height="30" colspan="2" align="center">
<input type="submit" value="登录"/>
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
CharacterFilter
package com.yue.chapter08.character;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CharacterFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
resp.setContentType("text/html;utf-8");
//拦截所有的请求,解决全站的中文乱码问题
//指定request和response的编码
String method = req.getMethod();
if(method.equalsIgnoreCase("post")){
req.setCharacterEncoding("utf-8");
}
//对request进行包装
CharacterRequest characterRequest = new CharacterRequest(req);
filterChain.doFilter(characterRequest,resp);
}
@Override
public void destroy() {
}
}
CharacterRequest
package com.yue.chapter08.character;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;
/*
* 继承默认包装类HttpServletRequestWrapper
* */
public class CharacterRequest extends HttpServletRequestWrapper {
private HttpServletRequest req;
public CharacterRequest(HttpServletRequest request) {
super(request);
this.req = request;
}
//子类继承父类,复写一些方法
@Override
public String getParameter(String name) {
//调用被包装对象的getParameter(),获得请求参数
String parameter = req.getParameter(name);
if(parameter == null){
return null;
}
//判断请求方式
String method = req.getMethod();
if(method.equalsIgnoreCase("get")){
try {
parameter = new String(parameter.getBytes("iso-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//解决乱码后返回结果
return parameter;
}
}
CharacterServlet
package com.yue.chapter08.character;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CharacterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("username"));
System.out.println(req.getParameter("password"));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
web.xml
<servlet>
<servlet-name>CharacterServlet</servlet-name>
<servlet-class>com.yue.chapter08.character.CharacterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CharacterServlet</servlet-name>
<url-pattern>/CharacterServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterFilter</filter-name>
<filter-class>com.yue.chapter08.character.CharacterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
使用JDBC完成数据的增删改查
- 过程
- 写一个包装类Users
- 写一个工具类JdbcUtils,简约代码
- UserDao类,对数据进行增删改查
Users
package com.yue.chapter09;
import java.util.Date;
public class Users {
private int id;
private String name;
private String password;
private Date birthday;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
JdbcUtils
package com.yue.chapter09;
import java.sql.*;
public class JdbcUtils {
public static Connection getCon() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/yun6";
String user ="root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void release(ResultSet rs, Statement st,Connection conn) {
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
UserDao
package com.yue.chapter09;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class UsersDao {
public boolean inset(Users user){
Connection coon = null;
Statement st = null;
try{
//建立连接
coon = JdbcUtils.getCon();
//获得Statement对象
st = coon.createStatement();
//因为birthday在user中是urti,在数据库中是sql,进行转换
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String format = simpleDateFormat.format(user.getBirthday());
//另一种
// Date birthday = user.getBirthday();
// String format1 = String.format("%tF", birthday);
//因为使用的是statement对象,没有占位符,所以要使用拼接的方式,
String sql = "insert into users(id,name,password,birthday)" +
"values("+ user.getId()+ ",'"+ user.getName() +"','"+ user.getPassword() +"','"+ format +"')";
int i = st.executeUpdate(sql);
if(i > 0){
return true;
}
return false;
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.release(null,st,coon);
}
return false;
}
//查询所有的对象
public ArrayList<Users> findAll(){
Connection coon = null;
Statement st = null;
ResultSet rs = null;
ArrayList<Users> users = new ArrayList<>();
try {
//奖励连接
coon = JdbcUtils.getCon();
//获取Statement
st = coon.createStatement();
//sql语句
String sql = "select * from users";
//查询,获取到结果集
rs = st.executeQuery(sql);
//对结果集的处理
while (rs.next()){
Users users1 = new Users();
users1.setId(rs.getInt("id"));
users1.setName(rs.getString("name"));
users1.setPassword(rs.getString("password"));
users1.setBirthday(rs.getDate("birthday"));
users.add(users1);
}
return users;
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.release(rs,st,coon);
}
return null;
}
public Users findById(int id){
Connection coon = null;
PreparedStatement st = null;
ResultSet rs = null;
try {
//奖励连接
coon = JdbcUtils.getCon();
//sql语句
String sql = "select * from users where id=?";
//获取Statement
st = coon.prepareStatement(sql);
//执行sql,为id赋值
st.setInt(1,id);
//查询,获取到结果集
rs = st.executeQuery();
//对结果集的处理
if (rs.next()){
Users users1 = new Users();
users1.setId(rs.getInt("id"));
users1.setName(rs.getString("name"));
users1.setPassword(rs.getString("password"));
users1.setBirthday(rs.getDate("birthday"));
return users1;
}
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.release(rs,st,coon);
}
return null;
}
public boolean update(Users users){
Connection coon = null;
PreparedStatement st = null;
try{
//建立连接
coon = JdbcUtils.getCon();
//sql语句
String sql = "update users set name =?,password=? where id=?";
//获得Statement对象
st = coon.prepareStatement(sql);
//执行sql,为它赋值
st.setString(1,users.getName());
st.setString(2,users.getPassword());
st.setInt(3,users.getId());
int i = st.executeUpdate();
if(i > 0){
return true;
}
return false;
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.release(null,st,coon);
}
return false;
}
public boolean delete(int id){
Connection coon = null;
PreparedStatement st = null;
try{
//建立连接
coon = JdbcUtils.getCon();
//sql语句
String sql = "delete from users where id =?";
//获得Statement对象
st = coon.prepareStatement(sql);
//执行sql,为它赋值
st.setInt(1,id);
int i = st.executeUpdate();
if(i > 0){
return true;
}
return false;
}catch (Exception e){
e.printStackTrace();
}finally {
JdbcUtils.release(null,st,coon);
}
return false;
}
}
测试
public class delete {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
boolean delete = usersDao.delete(2);
System.out.println(delete);
}
}
public class findId {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
Users byId = usersDao.findById(2);
System.out.println(byId.getName());
}
}
public class Insert {
public static void main(String[] args) {
//向用户中插入数据
Users users = new Users();
UsersDao usersDao = new UsersDao();
users.setId(2);
users.setName("ab");
users.setPassword("456");
users.setBirthday(new Date());
boolean inset = usersDao.inset(users);
System.out.println(inset);
}
}
public class queryAll {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
ArrayList<Users> all = usersDao.findAll();
for(int i= 0;i<all.size();i++){
System.out.println(all.get(i).getName());
}
}
}
public class update {
public static void main(String[] args) {
UsersDao usersDao = new UsersDao();
Users users = new Users();
users.setId(1);
users.setName("ee");
users.setPassword("55");
usersDao.update(users);
}
}
使用DBUtils实现crud
- 步骤
- 在数据库中创建user表,用User类封装数据
- 创建一个工具类:C3p0Utils
- 创建一个dao类,DBUTilsDao
- 创建测试类:测试Dao的增删改查方法
- QuerryRunner 类的使用方法
- 第一种
- QueryRunner runner = new QueryRunner();
- runner.query(connection,sql,处理器对象,params)
- 第二种
- QueryRunner runner = new QueryRunner(dataSource对象);
- runner.query(sql,处理器对象,params)
- 总结:
- 执行insert into,update,delete ,都使用update方法,返回int
- 执行select查询,调用query方法,放回List,Object,Map等对象。
C3p0Utils
package com.yue.chapter10;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
public class C3p0Utils {
public static DataSource ds = null;
static {
ds = new ComboPooledDataSource("itcast");
}
public static DataSource getDataSource(){
return ds;
}
}
DBUTilsDao
package com.yue.chapter10;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class DBUTilsDao {
public boolean insert(User user) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "insert into user(name,password) values(?,?)";
int count = queryRunner.update(sql,user.getName(),user.getPassword());
if(count > 0 ){
return true;
}
return false;
}
public List<User> findAll() throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "select * from user";
List<User> query = queryRunner.query(sql, new BeanListHandler<User>(User.class));
return query;
}
public User findById(int id) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "select * from user where id=?";
User query = queryRunner.query(sql, new BeanHandler<User>(User.class), id);
return query;
}
public Boolean update(User user)throws SQLException{
QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "update user set name = ?,password = ? where id = ?";
int i = queryRunner.update(sql, user.getName(), user.getPassword(), user.getId());
if(i>0){
return true;
}
return false;
}
public boolean delete (int id) throws SQLException {
QueryRunner queryRunner = new QueryRunner(C3p0Utils.getDataSource());
String sql = "delete from user where id =?";
int i = queryRunner.update(sql, id);
if(i>0){
return true;
}
return false;
}
}
User
package com.yue.chapter10;
public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/yun6
</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="checkoutTimeout">30000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<named-config name="itcast">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">
jdbc:mysql://localhost:3306/yun6
</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">15</property>
</named-config>
</c3p0-config>
测试的代码
public class deleteTest {
private static DBUTilsDao dbuTilsDao = new DBUTilsDao();
private static void testInset() throws SQLException {
boolean delete = dbuTilsDao.delete(2);
System.out.println(delete);
}
public static void main(String[] args) throws SQLException {
testInset();
}
}
public class findAllTest {
private static DBUTilsDao dbuTilsDao = new DBUTilsDao();
private static void testInset() throws SQLException {
List<User> all = dbuTilsDao.findAll();
System.out.println(all.size());
}
public static void main(String[] args) throws SQLException {
testInset();
}
}
public class findByIdTest {
private static DBUTilsDao dbuTilsDao = new DBUTilsDao();
private static void testInset() throws SQLException {
User user = dbuTilsDao.findById(2);
System.out.println(user.getName()+user.getPassword());
}
public static void main(String[] args) throws SQLException {
testInset();
}
}
public class InsertTest {
private static DBUTilsDao dbuTilsDao = new DBUTilsDao();
private static void testInset() throws SQLException {
User user = new User();
user.setName("xi");
user.setPassword("156462");
boolean insert = dbuTilsDao.insert(user);
System.out.println(insert);
}
public static void main(String[] args) throws SQLException {
testInset();
}
}
public class updateTest {
private static DBUTilsDao dbuTilsDao = new DBUTilsDao();
private static void testInset() throws SQLException {
User user = new User();
user.setId(2);
user.setName("ooo");
user.setPassword("0000000");
dbuTilsDao.update(user);
}
public static void main(String[] args) throws SQLException {
testInset();
}
}
利用jsp model 完成注册
- 准备jsp页面:register.jsp注册页面;loginSuccess.jsp注册成功要跳转的页面
- 准别javabean:
- UserBean:封装注册的基本参数,包含用户名,密码,邮箱
- RegisterFormBean:封装注册参数,包含用户名密码确认密码邮箱;服务段校验:比如用户名是否为null,用户名是否是重复的,前端校验:校验数据是否完整,比如格式是否规范
- 数据库模拟文件:
- controllerServlet文件处理注册请求
loginSuccess.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login successfully</title>
<style type="text/css">
#main{
width: 500px;
height: auto;
}
#main div {
width: 200px;
height: auto;
}
ul{
padding-top: 1px;
padding-left: 1px;
list-style: none;
}
</style>
</head>
<body>
<%
if (session.getAttribute("userBean") == null) {
%>
<jsp:forward page="register.jsp"/>
<%
return;
}
%>
<div id="main">
<div id="welcome">
恭喜你登陆成功
</div>
<hr/>
<div>您的信息</div>
<div>
<ul>
<li>您的名字:${userBean.name}</li>
<li>您的邮箱:${userBean.email}</li>
</ul>
</div>
</div>
</body>
</html>
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户注册</title>
<style type="text/css">
h3{
margin-left: 100px;
}
#outer{
width: 750px;
}
span{
color: #ff0000;
}
div{
height: 20px;
margin-bottom: 10px;
}
.ch{
width: 80px;
text-align: right;
float: left;
}
.ip{
width: 500px;
float: left;
}
.ip>input{
margin-right: 20px;
}
#bt{
margin-left: 50px;
}
#bt>input{
margin-right: 30px;
}
</style>
</head>
<body>
<form action="ControllerServlet" method="post">
<h3>用户注册</h3>
<div id="outer">
<div>
<div class="ch">姓名:</div>
<div class="ip">
<input type="text" name="name" value="${formBean.name}">
<span>${formBean.errors.name}${DBMes}</span>
</div>
<div>
<div class="ch">密码:</div>
<div class="ip">
<input type="text" name="password">
<span>${formBean.errors.password}</span>
</div>
</div>
<div>
<div class="ch">确认密码:</div>
<div class="ip">
<input type="text" name="password2">
<span>${formBean.errors.password2}</span>
</div>
</div>
<div>
<div class="ch">邮箱:</div>
<div class="ip">
<input type="text" name="email" value="${formBean.email}">
<span>${formBean.errors.email}</span>
</div>
</div>
<div>
<div id="bt">
<input type="reset" value="重置">
<input type="submit" value="注册">
</div>
</div>
</div>
</div>
</form>
</body>
</html>
ControllerServlet
package com.yue.chapter11;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class ControllerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户信息注册时的参数0
resp.setContentType("text/html;charset=utf-8");
req.setCharacterEncoding("utf-8");
String name = req.getParameter("name");
String password = req.getParameter("password");
String password2 = req.getParameter("password2");
String email = req.getParameter("email");
//将获取的参数封装到RegisterFormBean
RegisterFormBean formBean = new RegisterFormBean();
formBean.setEmail(email);
formBean.setName(name);
formBean.setPassword(password);
formBean.setPassword2(password2);
if(!formBean.validate()){
req.setAttribute("formBean" ,formBean);
req.getRequestDispatcher("/register.jsp").forward(req,resp);
return;
}
//参数填写符合要求,将数据封装到UserBean中
UserBean userBean = new UserBean();
userBean.setName(name);
userBean.setEmail(email);
userBean.setPassword(password);
//调用DBUtil的insertUser()方法,并返回一个boolean的类型
boolean b = DBUtil.getInstance().insertUser(userBean);
if(!b){
req.setAttribute("DBMes","您注册的用户已存在");
req.setAttribute("formBean",formBean);
req.getRequestDispatcher("/register.jsp").forward(req,resp);
return;
}
resp.getWriter().println("恭喜您注册成功,三秒后自动跳转");
//将成功注册的用户添加到Session中
req.getSession().setAttribute("userBean",userBean);
resp.setHeader("refresh" ,"3;url=loginSuccess.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
DBUtil
package com.yue.chapter11;
import java.util.HashMap;
public class DBUtil {
private static DBUtil instance = new DBUtil();
public static DBUtil getInstance(){
return instance;
}
//定义user的集合
private HashMap<String,UserBean> users = new HashMap<String,UserBean>();
private DBUtil(){
//向数据库中添加数据
UserBean userBean = new UserBean();
userBean.setName("Jack");
userBean.setPassword("1123456");
userBean.setEmail("jack@456.afdkl");
users.put("Jack",userBean);
UserBean userBean1 = new UserBean();
userBean1.setName("Jack");
userBean1.setPassword("1123456");
userBean1.setEmail("jack@456.afdkl");
users.put("Jack",userBean1);
}
//获取数据库中的数据
public UserBean getUser(String userName){
UserBean userBean = users.get(userName);
return userBean;
}
//向数据库中添加数据
public boolean insertUser(UserBean userBean){
if(userBean ==null){
return false;
}
String name = userBean.getName();
if(users.get(name)!=null){
return false;
}
users.put(name,userBean);
return true;
}
}
RegisterFormBean
package com.yue.chapter11;
import java.util.HashMap;
import java.util.Map;
public class RegisterFormBean {
private Map<String ,String> errors = new HashMap<String,String>();
private String name;
private String password;
private String password2;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
String regx ="[a-zA-z0-9_-]+@[a-zA-z0-9_-]+(\\.[a-zA-z0-9_-]+)+";
public boolean validate(){
boolean flag = true;
if(name == null || name.trim().equals("")){
errors.put("name","请输入姓名");
flag = false;
}
if(password == null || password.trim().equals("")){
errors.put("password","请输入密码");
flag = false;
}else if(password.length()>12 || password.length()<6){
errors.put("password","请输入6-12位密码");
flag = false;
}
if(password != null && !password.equals(password2)){
errors.put("password2","两次密码不一致");
flag = false;
}
if(email == null || email.trim().equals("")){
errors.put("email","请输入邮箱");
flag = false;
}else if(!email.matches(regx)){
errors.put("email","邮箱格式不对");
flag = false;
}
return false;
}
public Map<String, String> getErrors() {
return errors;
}
public void setErrors(String err,String errMsg) {
if(err!=null&&errMsg!=null){
errors.put(err,errMsg);
}
}
}
UserBean
package com.yue.chapter11;
public class UserBean {
private String name;
private String password;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}