用户模块
要登陆后才能购买,因此我们先写购买模块.
设计实体
privateStringid;
privateStringusername;
privateStringpassword;
privateStringemail;
privateStringcellphone;
privateStringaddress;
//各种setter、getter
设计数据库表
CREATETABLEuser(
id VARCHAR(40)PRIMARYKEY,
username VARCHAR(20)NOTNULL,
cellphoneVARCHAR(20)NOTNULL,
address VARCHAR(40)NOTNULL,
email VARCHAR(30),
password VARCHAR(30)NOTNULL
);
编写DAO
/**
* 用户的登录注册模块
* 1:登陆
* 2:注册
* 3:根据id查找具体的用户
*/
publicclassUserDaoImpl{
publicvoidregister(Useruser){
QueryRunnerqueryRunner=newQueryRunner(Utils2DB.getDataSource());
Stringsql="INSERT INTO user (id,username,cellphone,address,email,password) VALUES(?,?,?,?,?,?)";
try{
queryRunner.update(sql,newObject[]{user.getId(),user.getUsername(),user.getCellphone(),user.getAddress(),user.getEmail(),user.getPassword()});
}catch(SQLExceptione){
thrownewRuntimeException(e);
}
}
publicUserlogin(Stringusername,Stringpassword){
QueryRunnerqueryRunner=newQueryRunner(Utils2DB.getDataSource());
Stringsql="SELECT * FROM user WHERE username = ? AND password=?";
try{
return(User)queryRunner.query(sql,newObject[]{username,password},newBeanHandler(User.class));
}catch(SQLExceptione){
thrownewRuntimeException(e);
}
}
publicUserfind(Stringid){
QueryRunnerqueryRunner=newQueryRunner(Utils2DB.getDataSource());
Stringsql="SELECT * FROM user WHERE id=?";
try{
return(User)queryRunner.query(sql,id,newBeanHandler(User.class));
}catch(SQLExceptione){
thrownewRuntimeException(e);
}
}
}
测试DAO
publicclassUserDemo{
UserDaoImpluserDao=newUserDaoImpl();
@Test
publicvoidadd(){
Useruser=newUser();
user.setId("1");
user.setUsername("zhong");
user.setPassword("123");
user.setCellphone("10085");
user.setAddress("广州萝岗");
user.setEmail("40368324234234@QQ.com");
userDao.register(user);
}
@Test
publicvoidfind(){
Stringid="1";
Useruser=userDao.find(id);
System.out.println(user.getEmail());
}
@Test
publicvoidlogin(){
Stringusername="zhong";
Stringpassword="123";
Useruser=userDao.login(username,password);
System.out.println(user.getAddress());
}
}
抽取DAO
publicinterfaceUserDao{
voidregister(Useruser);
Userlogin(Stringusername,Stringpassword);
Userfind(Stringid);
}
编写Service
privateUserDaouserDao=DaoFactory.getInstance().createDao("zhongfucheng.dao.impl.UserDaoImpl",UserDao.class);
publicvoidregisterUser(Useruser){
userDao.register(user);
}
publicUserloginUser(Stringusername,Stringpassword){
returnuserDao.login(username,password);
}
publicUserfindUser(Stringid){
returnuserDao.find(id);
}
前台样式
- head.jsp
<divid="User">
用户名:<inputtype="text"name="username">
密码:<inputtype="password"name="password">
<buttonname="login">登陆</button>
<buttonname="register">注册</button>
</div>
- head.css
#body{
position:relative;
}
#user{
position:absolute;
margin-top:130px;
margin-left:1364px;
}
- 效果:
实现登陆注册功能
当点击登陆按钮的时候,把数据带过去给Servlet,让Servlet调用BusinessService方法,实现登陆。注册同理.....因此,我们需要用到JavaScript代码
- head.jsp
<c:iftest="${user==null}">
<divid="User">
用户名:<inputtype="text"id="username">
密码:<inputtype="password"id="password">
<buttonname="login"onclick="login()">登陆</button>
<buttonname="register"onclick="register()">注册</button>
</div>
</c:if>
<c:iftest="${user!=null}">
<divid="User">
欢迎您:${user.username} <ahref="${pageContext.request.contextPath}/UserServlet?method=Logout">注销</a>
</div>
</c:if>
- javaScript代码
<scripttype="text/javascript">
functionlogin(){
//得到输入框的数据
varusername=document.getElementById("username").value;
varpassword=document.getElementById("password").value;
//跳转到相对应的Servlet上
window.location.href="${pageContext.request.contextPath}/UserServlet?method=login&username="+username+"&password="+password;
}
functionregister(){
//跳转到注册页面
window.location.href="${pageContext.request.contextPath}/client/register.jsp";
}
</script>
- UserServlet
Stringmethod=request.getParameter("method");
BussinessServiceImplservice=newBussinessServiceImpl();
if(method.equals("login")){
try{
//得到页面传递过来的数据
Stringusername=request.getParameter("username");
Stringpassword=request.getParameter("password");
Useruser=service.loginUser(username,password);
request.getSession().setAttribute("user",user);
request.getRequestDispatcher("/client/head.jsp").forward(request,response);
}catch(Exceptione){
request.setAttribute("message","登陆失败了!");
request.getRequestDispatcher("/message.jsp").forward(request,response);
}
}elseif(method.equals("register")){
try{
//得到JSP传递过来的数据,封装成Bean对象
Useruser=WebUtils.request2Bean(request,User.class);
user.setId(WebUtils.makeId());
service.registerUser(user);
request.setAttribute("message","注册成功了!");
}catch(Exceptione){
e.printStackTrace();
request.setAttribute("message","注册失败了!");
}
request.getRequestDispatcher("/message.jsp").forward(request,response);
}elseif(method.equals("Logout")){
//销毁session
request.getSession().invalidate();
//回到首页
request.getRequestDispatcher("/client/head.jsp").forward(request,response);
}
购买模块
在显示图书的时候,顺便添加购买的超链接
<li><ahref="#">购买</a></li>
设计购物车实体
如果不清楚为什么这样设计,可参考我之前的博文:http://blog.csdn.net/hon_3y/article/details/56481439#t5
- Cart实体
publicclassCart{
privateMap<String,CartItem>map=newHashMap<>();
privatedoubleprice;
//提供把商品添加到购物的功能
publicvoidaddBook2Cart(Bookbook){
//得到对应的购物项
CartItemcartItem=map.get(book.getId());
//如果是null,说明购物车还没有该购物项
if(cartItem==null){
cartItem=newCartItem();
cartItem.setQuantity(1);
cartItem.setBook(book);
cartItem.setPrice(book.getPrice());
//把购物项加到购物车中
map.put(book.getId(),cartItem);
}else{
//如果购物车有该购物项了,那么将购物项的数量+1
cartItem.setQuantity(cartItem.getQuantity()+1);
}
}
//购物车的价钱是购物项价钱的总和
publicdoublegetPrice(){
doubletotalPrice=0;
for(Map.Entry<String,CartItem>me:map.entrySet()){
CartItemcartItem=me.getValue();
totalPrice+=cartItem.getPrice();
}
returntotalPrice;
}
publicMap<String,CartItem>getMap(){
returnmap;
}
publicvoidsetMap(Map<String,CartItem>map){
this.map=map;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
}
设计购物项实体
publicclassCartItem{
privateBookbook;
privatedoubleprice;
privateintquantity;
publicdoublegetPrice(){
returnthis.book.getPrice()*this.quantity;
}
publicvoidsetPrice(doubleprice){
this.price=price;
}
publicBookgetBook(){
returnbook;
}
publicvoidsetBook(Bookbook){
this.book=book;
}
publicintgetQuantity(){
returnquantity;
}
publicvoidsetQuantity(intquantity){
this.quantity=quantity;
}
}
处理用户想要买的书籍Servlet
<li><ahref="${pageContext.request
.contextPath}/BuyServlet?book_id=${book.id}">购买</a></li>
- BuyServlet
BussinessServiceImplservice=newBussinessServiceImpl();
//先检查该用户是否登陆了。
Useruser=(User)request.getSession().getAttribute("user");
if(user==null){
request.setAttribute("message","您还没登陆,请登陆了再来购买");
request.getRequestDispatcher("/message.jsp").forward(request,response);
return;
}
//如果登陆了...
//得到该用户的购物车
Cartcart=(Cart)request.getSession().getAttribute("cart");
if(cart==null){
cart=newCart();
request.getSession().setAttribute("cart",cart);
}
//得到用户想买的书籍
Stringbook_id=request.getParameter("book_id");
Bookbook=service.findBook(book_id);
//把书籍添加到购物车中
service.buyBook(cart,book);
request.setAttribute("message","该商品已添加到购物车中");
request.getRequestDispatcher("/message.jsp").forward(request,response);