一、项目结构及依赖包
二、建库
-- phpMyAdmin SQL Dump
-- version 4.6.4
-- https://www.phpmyadmin.net/
--
-- Host: localhost
-- Generation Time: 2017-12-27 13:44:25
-- 服务器版本: 5.7.14
-- PHP Version: 5.6.26
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `test`
--
-- --------------------------------------------------------
--
-- 表的结构 `t_user`
--
CREATE TABLE `t_user` (
`userId` int(11) NOT NULL,
`userName` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `t_user`
--
INSERT INTO `t_user` (`userId`, `userName`, `password`) VALUES
(1, 'wxw1', '123'),
(3, 'wxw3', '123'),
(4, 'wxw4', '4444'),
(8, 'wxw8', '1234'),
(2, '王弈伟', '123');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `t_user`
--
ALTER TABLE `t_user`
ADD PRIMARY KEY (`userId`),
ADD UNIQUE KEY `userName` (`userName`,`password`);
--
-- 在导出的表使用AUTO_INCREMENT
--
--
-- 使用表AUTO_INCREMENT `t_user`
--
ALTER TABLE `t_user`
MODIFY `userId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
三、DAO实现
只贴代码不做解释,不清楚的请移步Spring 的持久化实例和Spring Mybatis实例SqlSessionDaoSupport混用xml配置和注解。
实体pojo
package test.SpringMVC.model;
public class TUser {
private long userId;
private String userName;
private String password;
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
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;
}
@Override
public String toString() {
return "TUser [userId=" + userId + ", userName=" + userName + ", password=" + password + "]";
}
}
接口
package test.SpringMVC.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import test.SpringMVC.model.TUser;
public interface ITUserDao {
@Select("select * from t_user")
public List<TUser> listAll();
@Select("select * from t_user where userId=#{userId}")
public TUser getById(long userId);
@Insert("insert into t_user(userId,userName,password) values(#{userId}, #{userName}, #{password})")
public int insert(TUser u);
@Update("update t_user set userName=#{userName},password=#{password} where userId=#{userId}")
public int update(TUser u);
@Delete("delete from t_user where userId=#{userId}")
public int deleteById(long userId);
@Select("delete from t_user")
public void delAllUser();
@Select("select * from t_user where userName=#{userName} and password=#{password}")
public TUser CheckLoginAndPwd(@Param("userName") String userName,@Param("password") String password);
}
接口实现:
package test.SpringMVC.daoimpl;
import java.util.List;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import test.SpringMVC.dao.ITUserDao;
import test.SpringMVC.model.TUser;
public class TUserDaoImpl extends SqlSessionDaoSupport implements ITUserDao {
@Override
public List<TUser> listAll() {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(ITUserDao.class).listAll();
}
@Override
public TUser getById(long userId) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(ITUserDao.class).getById(userId);
}
@Override
public int insert(TUser u) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(ITUserDao.class).insert(u);
}
@Override
public int update(TUser u) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(ITUserDao.class).update(u);
}
@Override
public int deleteById(long userId) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(ITUserDao.class).deleteById(userId);
}
@Override
public TUser CheckLoginAndPwd(String userName, String password) {
// TODO 自动生成的方法存根
return this.getSqlSession().getMapper(ITUserDao.class).CheckLoginAndPwd(userName, password);
}
@Override
public void delAllUser() {
// TODO 自动生成的方法存根
this.getSqlSession().getMapper(ITUserDao.class).delAllUser();
}
}
四、配置文件
web.xml配置了首页index.jsp,其它的请求都被spring拦截
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>spring mvc</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!--configure the setting of springmvcDispatcherServlet and configure the
mapping -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springmvc-servlet.xml配置了数据源、mybatis配置文件路径、静态资源放行,需要说明的是拦截器Myinterceptor实现了HandlerInterceptor接口,其中postHandle对未处于登录状态的请求进行拦截,强制跳转到登录页面user/Login.jsp,后面给出代码。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- scan the package and the sub package -->
<context:component-scan base-package="test.SpringMVC"/>
<!-- 解除servlet对静态资源文件访问的限制,使得静态资源先经过 -->
<!-- <mvc:default-servlet-handler />
-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<!-- if you use annotation you must configure following setting -->
<mvc:annotation-driven />
<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/**/*.js"/>
<mvc:exclude-mapping path="/**/*.css"/>
<bean class="test.SpringMVC.controller.Myinterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- configure the InternalResourceViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource1" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false" />
<property name="username" value="your-user" />
<property name="password" value="your-passwd" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource1" />
<property name="configLocation"
value="classpath:test/SpringMVC/dao/mybatis-cfg.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg ref="sqlSessionFactory" />
</bean>
<bean id="TUserDao" class="test.SpringMVC.daoimpl.TUserDaoImpl">
<property name="sqlSessionTemplate" ref="sqlSession" />
</bean>
</beans>
mybatis配置mybatis-cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<typeAlias alias="TUser" type="test.SpringMVC.model.TUser" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test?useSSL=false" />
<property name="username" value="your-user" />
<property name="password" value="your-passwd" />
</dataSource>
</environment>
</environments>
<mappers>
<!--接口的方式 注册接口-->
<mapper class="test.SpringMVC.dao.ITUserDao"/>
</mappers>
</configuration>
五、控制器
package test.SpringMVC.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import test.SpringMVC.dao.ITUserDao;
import test.SpringMVC.model.TUser;
@RestController
@ComponentScan("test.SpringMVC.*")
@RequestMapping("/user")
public class UserController {
@Autowired
@Qualifier("TUserDao") ;
private ITUserDao iservice;
@RequestMapping(value="/checkLogin",produces = {"application/json;charset=UTF-8" })
public @ResponseBody TUser checkLogin(@RequestBody TUser user,Model model,HttpSession session){
TUser user1=iservice.CheckLoginAndPwd(user.getUserName(), user.getPassword());
session.setAttribute("user1", user1);
return user1;
}
@RequestMapping(value = "/ulist", method = RequestMethod.GET)
public ModelAndView getUsers() {
List<TUser> ulist = iservice.listAll();
ModelAndView modelAndView = new ModelAndView("user/userslist");// 转到/WEB-INF/jsp/user/userslist.jsp
modelAndView.addObject("userslist", ulist);
return modelAndView;
}
@RequestMapping(value="/register",method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView register(@ModelAttribute TUser user,Model model){
ModelAndView modelAndView = new ModelAndView("user/regsuccess");// 转到/WEB-INF/jsp/user/regsuccess.jsp
if(iservice.CheckLoginAndPwd(user.getUserName(), user.getPassword())!=null||iservice.getById(user.getUserId())!=null){
model.addAttribute("msg", "注册失败:id不能重复,用户名密码不能都一样!");// 失败也是转到user/regsuccess.jsp这个页面只是显示不一样信息
return modelAndView;
}
model.addAttribute("msg", "注册成功");
iservice.insert(user);
return modelAndView;
}
@RequestMapping("/LogOut")
public ModelAndView LogOut(HttpSession session){
session.invalidate();
ModelAndView modelAndView = new ModelAndView("user/Login");// 转到/WEB-INF/jsp/user/Login.jsp
return modelAndView;
}
@RequestMapping(value = "/saveUser",produces = "text/html;charset=UTF-8")
public void saveUser(TUser u){
iservice.insert(u);
}
@RequestMapping("/delUser")
public void delUser(int id){
iservice.deleteById(id);
}
@RequestMapping("/updateUser")
public void updateUser(TUser u){
iservice.update(u);
}
@RequestMapping("/userlist.json")
public @ResponseBody List<TUser> getUserList() {
return iservice.listAll();
}
@RequestMapping("/toaddform")
public ModelAndView toaddform() {
ModelAndView modelAndView = new ModelAndView("user/userform");// 转到/WEB-INF/jsp/user/userform.jsp
return modelAndView;
}
}
使用@RestController注解等于使用@Controller和@ResponseBody两个注解,标识该类是Spring MVC controller处理器,并且把返回结果直接写入HTTP response body中。所以返回String没有被解析为跳转路径,而是直接把字符串的内容显示到页面上。如返回String需要跳转则用@Controller注解。
六、拦截器Myinterceptor
package test.SpringMVC.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import test.SpringMVC.model.TUser;
public class Myinterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO 自动生成的方法存根
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO 自动生成的方法存根
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object hander) throws Exception {
// TODO 自动生成的方法存根
String url=request.getRequestURI();
if(url.indexOf("/checkLogin.action")>=0){
return true;
}
if(url.indexOf("/register.action")>=0)
{
return true;
}
HttpSession session=request.getSession();
TUser user=(TUser)session.getAttribute("user1");
if(user!=null){
return true;
}
request.getRequestDispatcher("/WEB-INF/jsp/user/Login.jsp").forward(request, response);
return false;
}
}
七、页面代码:
首页index.jsp:一个菜单列表,以及用bootstrap实现了右上角登录标志,登录状态就显示用户名,点击注销会通过/LogOut RequestMapping转到Login.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">
<link rel="stylesheet" href="css/bootstrap.min.css" />
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<!-- 标题 -->
<div class="row">
<div class="col-md-7">
<h1>菜单列表</h1>
</div>
<div class="col-md-offset-10">
<h4>欢迎您:<span class="glyphicon glyphicon-user"></span>
<strong>${user1.userName}</strong>
<small><a href="${pageContext.request.contextPath }/user/LogOut.action">注销</a></small></h4>
</div>
</div>
<ul>
<li><a href="user/ulist.do">t_user数据库页面</a></li>
<li><a href="user/toaddform.do">注册新t_user</a></li>
</ul>
</body>
</html>
user/Login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css" />
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-datetimepicker.min.js"></script>
<script type="text/javascript"
src="js/bootstrap-datetimepicker.zh-CN.js"></script>
</head>
<style>
</style>
<script type="text/javascript">
$("#myModal").modal({
keyboard : false,
backdrop : false
});
$(function() {
$("#lo")
.click(
function() {
$
.ajax({
type : 'post',
url : '${pageContext.request.contextPath}/user/checkLogin.action',
contentType : 'application/json;charset=utf-8',
data : JSON.stringify({
"userName" : $("#loginusername")
.val(),
"password" : $("#loginpassword")
.val()
}),
success : function(data) {
if (data == "" || data == null) {
$("#message").html("用户名或密码错误");
} else {
window.location.href = "${pageContext.request.contextPath}/index.jsp"; //登录成功后转主页面
}
}
});
});
});
</script>
<style>
#login {
width: 450px;
height: 100px;
margin: 50px auto;
}
</style>
<body>
<div class="container">
<div id="login">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">用户名</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="loginusername"
name="userName" placeholder="请输入您的用户名" required autofocus>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">密码</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="loginpassword"
name="password" placeholder="请输入您的密码" required> <label
class="control-label" for="inputSuccess1" style="color: red;"
id="message"></label>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-info" id="lo">登陆</button>
<button type="button" class="btn btn-danger" data-toggle="modal"
data-target="#myModal">点击注册新用户</button>
</div>
</div>
</form>
<!-- 注册模态框 -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">用户注册</h4>
</div>
<form class="form-horizontal" role="form"
action="${pageContext.request.contextPath}/user/register.action"
method="post" id="form">
<div class="modal-body">
<!-- 表单 -->
<div class="form-group">
<label for="inputEmail3" class="col-sm-3 control-label">用户名</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="userName"
name="userName" placeholder="请输入您的用户名" required autofocus>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-3 control-label">密码</label>
<div class="col-sm-6">
<input type="password" class="form-control" id="password"
name="password" placeholder="请输入您的密码" required autofocus>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">关闭</button>
<button type="submit" class="btn btn-primary" id="save">注册</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
user/userform.jsp springmvc表单处理的例子用于注册新用户
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Spring MVC表单处理</title>
</head>
<body>
<h2>User Information</h2>
<form action="${pageContext.request.contextPath}/user/register" method="post">
编号:<input type="text" name="userId"/>
用户名:<input type="text" name="userName"/>
密码:<input type="text" name="password"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
注册后转到regsuccess.jsp显示信息
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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 'success.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">
</head>
<body>
<h1>${msg }</h1> </body>
</html>
userslist.jsp用于显示t_user表的内容
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<title>JSP显示用户</title>
</head>
<body>
<table border="1">
<tr>
<th>编号</th>
<th>名字</th>
<th>密码</th>
</tr>
<c:forEach items="${userslist}" var="users">
<tr>
<td>${users.userId}</td>
<td>${users.userName}</td>
<td>${users.password}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
八、运行截图:
未登录时点击菜单的条目都会转到登录页面
登录后会转到首页,再点击t_user数据库页面就会显示t_user表的内容
新增用户表单页面
MyBatis+PageHelper实现分页
原文地址:https://my.oschina.net/u/2245781/blog/1595860