使用jdbc ssm servlet 实现简单的登录查看功能
学习笔记
Spring
Spring就像是整个项目中装配bean的大工厂,在配置文件中可以指定使用特定的参数去调用实体类的构造方法来实例化对象。
Spring的核心思想是IoC(控制反转),即不再需要程序员去显式地new一个对象,而是让Spring框架帮你来完成这一切。
SpringMVC
SpringMVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。SpringMVC相当于SSH框架中struts。
mybatis
mybatis是对jdbc的封装,它让数据库底层操作变的透明。mybatis的操作都是围绕一个sqlSessionFactory实例展开的。mybatis通过配置文件关联到各实体类的Mapper文件,Mapper文件中配置了每个类对数据库所需进行的sql语句映射。在每次与数据库交互时,通过sqlSessionFactory拿到一个sqlSession,再执行sql命令。
项目目录结构
src
-main
—java
----controller
----mapper
----entity
----service
–resources
----mapper
----applicationContext.xml
----db.properties
----spring-mvc.xml
–webapp
----WEB-INF
------web.xml
----index.jsp
pom.xml
UserController
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping("/login.do")
public ModelAndView login(User user){
boolean flag = userService.login(user.getUsername(), user.getPassword());
ModelAndView modelAndView=new ModelAndView();
if(flag){
modelAndView.setViewName("../ok");
}else {
modelAndView.setViewName("../failure");
}
return modelAndView;
}
@RequestMapping("/find.do")
public ModelAndView find() {
List<User> all = userService.find();
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("user", all);
modelAndView.setViewName("../find");
return modelAndView;
}
}
UserDao
public interface UserDao {
User findUserByUserName(String username);
List<User> find();
}
IUserService
public interface IUserService {
boolean login(String username,String password);
List<User> find();
}
UserService
@Service
public class UserService implements IUserService {
@Autowired
private UserDao userDao;
@Override
public boolean login(String username, String password) {
User user = userDao.findUserByUserName(username);
if (user!=null && user.getPassword().equals(password)){
return true;
}
return false;
}
@Override
public List<User> find() {
return userDao.find();
}
}
index
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="/user/login.do" method="post">
username:<input name="username" type="text">
password:<input name="password" type="password">
<input type="submit" value="login">
</form>
</body>
</html>
ok.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<table>
<thead>
<tr>
<th class="sorting_asc">ID</th>
<th class="sorting_desc">用户名</th>
<th class="sorting_asc sorting_asc_disabled">密码</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${user}">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>