复习:entity DAO/DBHelper service action jsp
总结:使用mybatis后的区别:DBHelper里书写的是SqlSession,而不是自己来拿数据库连接了,当然这得写配置文件SqlMapConfig;service包里是一个接口对一个实现类,如IUserService,UserService,在接口实现类里,通过SqlSession的getMapper方法自动实现DAO层的UserMapper接口;DAO包里全部是接口;sql语句及与实体类的映射全部由mybatis里的配置文件完成,如User类对应就写一个User.xml文件。
代码演示
- 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" type="text/css" href="css/login.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("input[type='submit']").mouseover(function(){
var nick = $("input:first").val();
var pwd = $("input:eq(1)").val();
if(nick == '' || pwd == ''){
$(this).attr("type","button");
}else{
$(this).attr("type","submit");
}
});
});
</script>
</head>
<body>
<div id="out">
<form action="login.do" method="post">
<ul>
<li class="move"><input type="text" name="nick" placeholder="昵称"/></li>
<li><input type="password" name="pwd" placeholder="密码"/></li>
<li><input type="submit" value="登录"/></li>
<li><a href="reg.jsp">我要注册?</a></li>
<span></span>
</ul>
</form>
</div>
</body>
</html>
- action/web.xml
package com.frame.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.frame.entity.User;
import com.frame.service.UserService;
public class LoginAction extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String nick = req.getParameter("nick");
String pwd = req.getParameter("pwd");
UserService uService = new UserService();
User loginer = uService.findByNickAndPwd(nick, pwd);
if(loginer != null){
req.getSession().setAttribute("loginer", loginer);
req.getRequestDispatcher("index.jsp").forward(req,resp);
}else{
resp.sendRedirect("login.jsp");
}
}
}
<!-- 登录处理页 -->
<servlet>
<servlet-name>loginAction</servlet-name>
<servlet-class>com.frame.action.LoginAction</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginAction</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
- service
package com.frame.service;
import org.apache.ibatis.session.SqlSession;
import com.frame.dao.UserMapper;
import com.frame.entity.User;
import com.frame.util.DBHelper;
public class UserService implements IUserService {
//dao层只提供了一个接口,并不需要我们自己实现,通过mybatis的session.getMapper()动态代理实例化对象
private UserMapper userMapper;
@Override
public User findByNickAndPwd(String nick, String pwd) {
SqlSession session = DBHelper.getSession();
userMapper = session.getMapper(UserMapper.class);
return userMapper.selectByNickAndPwd(nick, pwd);
}
@Override
public void addUser(User u) {
SqlSession session = DBHelper.getSession();
userMapper = session.getMapper(UserMapper.class);
userMapper.insert(u);
session.commit();//不提交,数据不会写入数据库
DBHelper.close(session);
}
@Override
public User findByNick(String nick) {
SqlSession session = DBHelper.getSession();
userMapper = session.getMapper(UserMapper.class);
User u = userMapper.selectByNick(nick);
DBHelper.close(session);
return u;
}
}
- DAO
package com.frame.dao;
import org.apache.ibatis.annotations.Param;
import com.frame.entity.User;
public interface UserMapper {
public User selectByNickAndPwd(@Param("nick") String nick,@Param("pwd") String pwd);
public void insert(User u);
public User selectByNick(String nick);
}
- entity/User.xml
package com.frame.entity;
public class User {
private int id;
private String nick;
private String pwd;
private String name;
private String sex;
private String phone;
private String addr;
private String photo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD SQL Map 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="com.frame.dao.UserMapper">
<select id="selectByNickAndPwd" resultType="User">
select * from user where nick=#{nick} and pwd=#{pwd}
</select>
<insert id="insert">
insert into user(nick,pwd,name,sex,phone,addr,photo)values(#{nick},#{pwd},#{name},#{sex},#{phone},#{addr},#{photo})
</insert>
<select id="selectByNick" resultType="User">
select * from user where nick=#{nick}
</select>
</mapper>
- DBHelper
package com.frame.util;
import java.io.IOException;
import java.io.Reader;
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 DBHelper {
private static SqlSessionFactory factory;
//之所以将factory作为成员变量,而不在静态代码块里,是因为工厂是复用的,不用每次都创建
//同理session不能作为成员变量,是因为session不能复用,如果共用一个会话,数据就相当于全部共享了
static{
SqlSessionFactoryBuilder factoryBuilder = new SqlSessionFactoryBuilder();
try {
Reader reader = Resources.getResourceAsReader("SqlMapConfig.xml");
factory = factoryBuilder.build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
//获取数据库会话对象
public static SqlSession getSession(){
return factory.openSession();
}
//关闭数据库会话
public static void close(SqlSession session){
if(session != null){
session.close();
}
}
}
- SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-config.dtd">
<configuration>
<!-- 可以给实体类取别名,这个放在前面,放在后面会出错 -->
<typeAliases>
<typeAlias type="com.frame.entity.User" alias="User"/>
<typeAlias type="com.frame.entity.Province" alias="Province"/>
<typeAlias type="com.frame.entity.City" alias="City"/>
<typeAlias type="com.frame.entity.Street" alias="Street"/>
</typeAliases>
<!-- step1:配环境 -->
<environments default="e1">
<environment id="e1">
<!-- 先配事务,事务是必须配的,简单的事务类型JDBC -->
<transactionManager type="JDBC"></transactionManager>
<!-- 再配数据源,POOLED 以连接池的方式 -->
<dataSource type="POOLED">
<!-- 在数据源中配置连接属性,注意这里是username不是user -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/studysys"/>
<property name="username" value="root"/>
<property name="password" value="root1205"/>
</dataSource>
</environment>
</environments>
<!-- step2:引入实体类的映射配置文件 -->
<mappers>
<mapper resource="com/frame/entity/User.xml"/>
<mapper resource="com/frame/entity/Province.xml"/>
<mapper resource="com/frame/entity/City.xml"/>
<mapper resource="com/frame/entity/Street.xml"/>
</mappers>
</configuration>