目录
1.整体框架
2.对应代码展示
2.1 引入所需依赖
<dependencies>
<!--加载驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<!--加载测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
<!--加载lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!--加载spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
<!--加载servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--加载json-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
<!--加载mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!--加载日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
2.2 连接数据库
2.2.1 配置conf.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>
<!--注意此处放置位置-->
<properties resource="db.properties"/>
<!--若没有则不能正常显示日志,注意setting位置-->
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<package name="com.qy151wd.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<!--映射-->
<mappers>
<mapper resource="mapper/userMapper.xml"/>
<mapper resource="mapper/studentMapper.xml"/>
</mappers>
</configuration>
db.properties内容
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?serverTimezone=Asia/Shanghai
username=root
password=123456
2.2.2 配置mapper下的内容
userMapper.xml:
因为所作登录界面简单,只考虑输入账号和密码对应问题
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qy151wd.dao.UserDao">
<!--此处起了别名User-->
<select id="getNameAndPass" resultType="User" parameterType="String">
<!--uername=#{name}此处name本应该为uername但dao包下的多参输入,名字对应改变了-->
select * from tb_user where uername=#{name} and password=#{pass}
</select>
</mapper>
StudentMapper.xml:
因为所作学生界面简单,只考虑查询所有问题
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qy151wd.dao.StudentDao">
<!--此处前面改别名Student-->
<select id="findAll" resultType="Student">
select * from student
</select>
</mapper>
2.2.3 entity类下的内容
user:
注意此处命名与数据库相对应,若命名不一致则需要进行之后的重新映射,参见之前的mybatis的博客。
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String uername;
private String password;
public User(String uername, String password) {
this.uername = uername;
this.password = password;
}
}
Student:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private int id;
private String name;
private int age;
private String address;
private int sex;
public Student(String name, int age, String address, int sex) {
this.name = name;
this.age = age;
this.address = address;
this.sex = sex;
}
}
2.2.4 dao包下的内容
UserDao注意两者都为接口类型:
public interface UserDao {
//多参传入方法,相当于给传参的数据进行重命名,@Param("name")内是新替换的名称
public User getNameAndPass(@Param("name")String uername,@Param("pass") String password);
}
StudentDao:
public interface StudentDao {
//注意此处查询结果返回的是List型
public List<Student> findAll();
}
2.3.5 测试方法是否正确
public class Test01 {
SqlSession sqlSession;
UserDao mapper;
StudentDao mapper1;
{
try{
Reader reader= Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
sqlSession= sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(UserDao.class);
mapper1 = sqlSession.getMapper(StudentDao.class);
}catch (Exception e){
e.printStackTrace();
}
}
@Test
public void testGetName(){
User nameAndPass = mapper.getNameAndPass("admin", "123456");
System.out.println(nameAndPass);
}
@Test
public void testFindAll(){
List<Student> all = mapper1.findAll();
for (Student stu:all
) {
System.out.println(stu.getId()+"\t"+stu.getName()+"\t"
+stu.getAge()+"\t"+stu.getAddress()+"\t"+stu.getSex());
}
}
}
3.SpringMvc下编写方法
3.1 controller层下的配置
UserController:
@Controller
public class UserController {
SqlSession sqlSession;
UserDao mapper;
{
try{
Reader reader= Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
sqlSession=sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(UserDao.class);
}catch (Exception e){
e.printStackTrace();
}
}
@RequestMapping("/loginPage")
@ResponseBody
//username与之前的表单名字一致
public CommonResult getName(String username, String password, HttpSession httpSession){
User nameAndPass = mapper.getNameAndPass(username, password);
if(nameAndPass!=null){
System.out.println(nameAndPass);
httpSession.setAttribute("user",nameAndPass);
return CommonResult.success(200);
}else{
return CommonResult.notFount();
}
}
}
StudentController:
@Controller
public class StudentController {
SqlSession sqlSession;
StudentDao mapper;
{
try{
Reader reader= Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(reader);
sqlSession= sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(StudentDao.class);
}catch (Exception e){
e.printStackTrace();
}
}
@RequestMapping("/student")
@ResponseBody//返回的json类型的数据
public CommonResult getFind(){
List<Student> all = mapper.findAll();
if(all!=null){
return CommonResult.success(all);
}else{
return CommonResult.notFount();
}
}
}
3.2 公共类下的内容
commonResult:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult {
private final static int success=200;
private final static int error=500;
private final static int not_fount=404;
private int code;
private String msg;
//注意此处的date,后续要是不能打印注意看此处
private Object date;
public static CommonResult success(Object date){
return new CommonResult(CommonResult.success,"success",date);
}
public static CommonResult error(Object date){
return new CommonResult(CommonResult.error,"未知错误,请联系管理员",date);
}
public static CommonResult notFount(){
return new CommonResult(CommonResult.not_fount,"资源不存在",null);
}
}
3.3 springmvc的配置内容
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:contnx="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<contnx:component-scan base-package="com.qy151wd"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<mvc:exclude-mapping path="/css/**"/>
<mvc:exclude-mapping path="/js/**"/>
<mvc:exclude-mapping path="/loginPage"/>
<mvc:exclude-mapping path="/login.jsp"/>
<bean class="com.qy151wd.interceptor.LoginInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
</beans>
4.elementui界面显示
4.1 登录界面代码展示
login.jsp:
注意要引入样式,不然不能正常显示。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
<link type="text/css" rel="stylesheet" href="css/index.css">
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<style>
html,body{
width: 100%;
height: 100%;
}
#con{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 340px;
height: 300px;
border: 1px solid;
padding-right: 15px;
background-color: rgba(255, 255, 255, 0.9);
border-radius: 50px;
text-align:center;
}
</style>
</head>
<body>
<div id="con">
<el-row :gutter="1" style="margin-top: 40px">
<el-col :span="22">
<el-form label-width="80px" :model="form" style="margin-top: 50px" :rules="rules">
<el-form-item label="账号" prop="username">
<el-input v-model="form.username" placeholder="请输入账号名"></el-input>
</el-form-item>
<el-form-item label="密码" style="color: #000000" prop="password">
<el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">提交</el-button>
</el-form-item>
</el-form>
</el-col>
</el-row>
</div>
</body>
<script>
var con=new Vue({
el:"#con",
data: {
form: {
username: "",
password: ""
}
},
methods:{
submitForm(){
var that=this;
var qs = Qs;
axios.post("loginPage", qs.stringify(this.form)).then(function (result) {
if(result.data.code==200){
that.$message.success(result.data.msg);
window.location.href="success.jsp";
}else{
that.$message.error(result.data.msg);
}
})
}
}
})
</script>
</html>
4.2 登录成功界面代码
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功界面</title>
<link type="text/css" rel="stylesheet" href="css/index.css">
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="con">
<el-table
:data="tableData"
border
style="width: 100%">
<el-table-column
prop="id"
label="编号"
>
</el-table-column>
<el-table-column
prop="name"
label="姓名"
>
</el-table-column>
<el-table-column
prop="age"
label="年龄"
>
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
<el-table-column
label="性别">
<template slot-scope="scope">
{{scope.row.sex==1?'男':'女'}}
</template>
</el-table-column>
</el-table>
</div>
</body>
<script>
var app=new Vue({
el:"#con",
data:{
tableData:[]
},
created(){
this.init();
},
methods: {
init() {
var that = this;
axios.post("student").then(function (result) {
if (result.data.code === 200) {
//注意此处的date是否在json数据所传输的名称是否一致,不然不能正常显示
that.tableData = result.data.date;
}else{
window.location.href="login.jsp";
}
})
}
}
})
</script>
</html>
5.拦截器拦截未登录者查看信息
interceptor包下的LoginInterceptor:
注意不要忘了在springmvc.xml中配置所要释放信息。
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
Object user = session.getAttribute("user");
if(user!=null){
return true;
}
PrintWriter writer = response.getWriter();
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
writer.write(new ObjectMapper().writeValueAsString(CommonResult.error("未知异常")));
writer.flush();
writer.close();
return false;
}
}