概述
1.先来看一下完成的效果图:
注册账号:
登录账号:
首页展示:
修改账号:
显示所有账号信息(点击按钮可删除该条信息):
2.使用idea新建一个Maven webapp项目
记得打钩:
取名字:
设置版本号:
OK!
3.搭建目录结构
4.设置,让IDEA识别目录的作用
5.相关代码的编写
chatrobot.sql新建数据库
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '用户ID',
`email` varchar(255) NOT NULL COMMENT '用户邮箱',
`password` varchar(255) NOT NULL COMMENT '用户密码',
`username` varchar(255) NOT NULL COMMENT '用户昵称',
`role` varchar(255) NOT NULL COMMENT '用户身份',
`status` int(1) NOT NULL COMMENT '用户状态',
`regTime` datetime NOT NULL COMMENT '注册时间',
`regIp` varchar(255) NOT NULL COMMENT '注册IP',
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `user` VALUES ('1', 'xxx', 'xxxxx', 'xxxxx', 'root', '0', '2017-03-28 09:40:31', '127.0.0.1');
SET FOREIGN_KEY_CHECKS=1;
User.java
package com.chatRobot.model;
import java.util.Date;
public class User {
private long id;
private String email;
private String password;
private String username;
private String role;
private int status;
private Date regTime;
private String regIp;
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
public String getRegIp() {
return regIp;
}
public void setRegIp(String regIp) {
this.regIp = regIp;
}
}
IUserDao.java
package com.chatRobot.dao;
import com.chatRobot.model.User;
import java.util.List;
public interface IUserDao {
User selectUser(long id);
List<User> selectAllUser();
User selectUserByEmail(String email);
User addUser(User user);
User removeUser(long id);
User modifyUser(User user);
}
IUserService.java
package com.chatRobot.service;
import com.chatRobot.model.User;
import java.util.List;
public interface IUserService {
public User selectUser(long userId);
public List<User> selectAllUser();
public User selectUserByEmail(String email);
public User addUser(User user);
public User removeUser(long userId);
public User modifyUser(User user);
}
UserServiceImpl.java
package com.chatRobot.service.impl;
import com.chatRobot.dao.IUserDao;
import com.chatRobot.model.User;
import com.chatRobot.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
public User selectUser(long userId) {
return this.userDao.selectUser(userId);
}
public List<User> selectAllUser() {
return this.userDao.selectAllUser();
}
public User selectUserByEmail(String email) {
return this.userDao.selectUserByEmail(email);
}
public User addUser(User user) {
return this.userDao.addUser(user);
}
public User removeUser(long userId) {
return this.userDao.removeUser(userId);
}
public User modifyUser(User user) {
return this.userDao.modifyUser(user);
}
}
UserController.java
package com.chatRobot.controller;
import javax.servlet.http.HttpServletRequest;
import com.chatRobot.model.User;
import com.chatRobot.service.IUserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
private long userId;
private ObjectMapper mapper;
//Ok!!!
@RequestMapping(value = "/showUser/{id}", method = RequestMethod.GET)
public void getUser(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
long userId = Long.parseLong(id);
User user = this.userService.selectUser(userId);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(user));
response.getWriter().close();
}
//Ok!!!!
@RequestMapping(value = "/loginUser", method = RequestMethod.GET)
public void loginUser(User loginUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
User user = this.userService.selectUserByEmail(loginUser.getEmail());
ObjectMapper mapper = new ObjectMapper();
if (user == null) {
response.getWriter().write("账号不存在!");
} else if (!loginUser.getPassword().equals(user.getPassword())) {
response.getWriter().write("密码输入错误!");
} else {
response.getWriter().write(mapper.writeValueAsString(user));
}
response.getWriter().close();
}
//Ok!!!!
@RequestMapping(value = "/allUser", method = RequestMethod.GET)
public void allUser(ModelMap model, HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
List<User> userList = userService.selectAllUser();
String userMsg = "";
for (User user : userList) {
userMsg = userMsg + "<tr>";
userMsg = userMsg + "<td>" + user.getId() + "</td>";
userMsg = userMsg + "<td>" + user.getUsername() + "</td>";
userMsg = userMsg + "<td>" + user.getPassword() + "</td>";
userMsg = userMsg + "<td>" + user.getEmail() + "</td>";
userMsg = userMsg + "<td>" + user.getRole() + "</td>";
userMsg = userMsg + "<td>" + user.getStatus() + "</td>";
userMsg = userMsg + "<td>" + user.getRegTime() + "</td>";
userMsg = userMsg + "<td>" + user.getRegIp() + "</td>";
userMsg = userMsg + "<td><input type='button' value='删 除' οnclick='removeUser(" + user.getId() + ")'/></td>";
userMsg = userMsg + "</tr>";
}
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write(mapper.writeValueAsString(userMsg));
}
//Ok!!!!
@RequestMapping(value = "/showUser", method = RequestMethod.POST)
public void postUser(User registUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
ObjectMapper mapper = new ObjectMapper();
User user = this.userService.selectUserByEmail(registUser.getEmail());
if (user != null) {
response.getWriter().write("该账号已经注册过!");
} else {
registUser.setStatus(1);
registUser.setRegTime(new Date());
registUser.setRegIp("127.0.0.6");
this.userService.addUser(registUser);
response.getWriter().write(mapper.writeValueAsString(user));
}
response.getWriter().close();
}
//Ok!!!
@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
public void putUser(User updateUser, HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
System.out.println(updateUser.getUsername());
System.out.println(updateUser.getPassword());
ObjectMapper mapper = new ObjectMapper();
User user = this.userService.modifyUser(updateUser);
response.getWriter().write(mapper.writeValueAsString(user));
response.getWriter().close();
}
//Ok!!!!
@RequestMapping(value = "/removeUser/{id}", method = RequestMethod.DELETE)
public void deleteUser(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
long userId = Long.parseLong(id);
this.userService.removeUser(userId);
ObjectMapper mapper = new ObjectMapper();
response.getWriter().write("remove success!");
response.getWriter().close();
}
}
UserDao.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">
<!-- 设置为IUserDao接口方法提供sql语句配置 -->
<mapper namespace="com.chatRobot.dao.IUserDao">
<select id="selectUser" resultType="User" parameterType="long">
select * from user where id = #{id}
</select>
<select id="selectAllUser" resultType="User">
select * from user
</select>
<select id="selectUserByEmail" resultType="User" parameterType="string">
select * from user where email = #{email}
</select>
<select id="addUser" resultType="User" parameterType="User">
insert into user (email,password,username,role,status,regTime,regIp) values (#{email},#{password},#{username},#{role},#{status},#{regTime},#{regIp})
</select>
<select id="removeUser" resultType="User" parameterType="long">
delete from user where id = #{id}
</select>
<select id="modifyUser" resultType="User" parameterType="User">
update user set
email = #{email},
password = #{password},
username = #{username},
role = #{role},
status = #{status},
regIp = #{regIp}
where id = #{id}
</select>
</mapper>
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://127.0.0.1:3306/chatrobot?useUnicode=true&characterEncoding=utf8
#用户名
jdbc.username=root
#密码
jdbc.password=root
#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
spring-mvc.xml
<?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.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 扫描web相关的bean -->
<context:component-scan base-package="com.chatRobot.controller"/>
<!-- 开启SpringMVC注解模式 -->
<mvc:annotation-driven/>
<!-- 静态资源默认servlet配置 -->
<mvc:default-servlet-handler/>
<!-- 配置jsp 显示ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
spring-mybatis.xml
<?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:tx="http://www.springframework.org/schema/tx"
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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 扫描service包下所有使用注解的类型 -->
<context:component-scan base-package="com.chatRobot.service"/>
<!-- 配置数据库相关参数properties的属性:${url} -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="autoCommitOnClose" value="${c3p0.autoCommitOnClose}"/>
<property name="checkoutTimeout" value="${c3p0.checkoutTimeout}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
</bean>
<!-- 配置SqlSessionFactory对象 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 扫描model包 使用别名 -->
<property name="typeAliasesPackage" value="com.chatRobot.model"/>
<!-- 扫描sql配置文件:mapper需要的xml文件 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 给出需要扫描Dao接口包 -->
<property name="basePackage" value="com.chatRobot.dao"/>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置基于注解的声明式事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
func.js
//Ok!!
function addUser() {
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var role = $("#role").val();
var user = {
"username": username,
"password": password,
"email": email,
"role": role
};
var _url = "http://localhost:8080/ChatRobot/user/showUser";
$.ajax({
url: _url,
type: "POST",
data: user,
contentType: "application/x-www-form-urlencoded",
}).done(function (data) {
if (data == "该账号已经注册过!") {
alert("该账号已经注册过!");
return false;
} else {
window.sessionStorage.setItem("user", data);
window.location.replace("http://localhost:8080/ChatRobot/user_index.html");
}
}).fail(function (res) {
alert("注册失败!");
});
}
//Ok!!
function loginUser() {
var password = $("#password").val();
var email = $("#email").val();
var role = $("#role").val();
var user = {
"password": password,
"email": email,
"role": role
};
var _url = "http://localhost:8080/ChatRobot/user/loginUser";
$.ajax({
url: _url,
type: "GET",
data: user,
contentType: "application/x-www-form-urlencoded",
}).done(function (data) {
if (data == "密码输入错误!") {
alert("密码错误!");
return false;
} else if (data == "账号不存在!") {
alert("账号不存在!");
return false;
} else {
window.sessionStorage.setItem("user", data);
window.location.replace("http://localhost:8080/ChatRobot/user_index.html");
}
}).fail(function (res) {
alert("登录失败!");
});
}
//Ok!!!
function updateUser() {
var user = {
"id": $("#id").val(),
"username": $("#username").val(),
"password": $("#password").val(),
"email": $("#email").val(),
"role": $("#role").val(),
"status": $("#status").val(),
"regTime": new Date(),
"regIp": $("#regIp").val()
};
console.log(user);
var _url = "http://localhost:8080/ChatRobot/user/updateUser";
$.ajax({
url: _url,
type: "POST",
data: user,
contentType: "application/x-www-form-urlencoded",
}).done(function (data) {
window.location.replace("http://localhost:8080/ChatRobot/user_info.html");
}).fail(function (res) {
window.location.replace("http://localhost:8080/ChatRobot/user_info.html");
});
}
//Ok!!!
function removeUser(id) {
var _url = "http://localhost:8080/ChatRobot/user/removeUser";
alert("第" + id + "条数据已被删除!");
$.ajax({
type: "DELETE",
url: _url + "/" + id,
dataType: "json",
success: function (data) {
window.location.reload();
},
error: function (res) {
window.location.reload();
}
});
}
//Ok!!!
function removeSession() {
window.sessionStorage.removeItem("user");
}
html文件里面的js
<script>
$(document).ready(function () {
var data = window.sessionStorage.getItem("user");
if (data != null) {
var user = $.parseJSON(data);
$("#showName").html(user.username);
} else {
$("#showName").append("欢迎");
}
});
</script>
<script>
$(document).ready(function () {
var data = window.sessionStorage.getItem("user");
if (data != null) {
var user = $.parseJSON(data);
$("#showName").html(user.username);
} else {
$("#showName").append("欢迎");
}
if (data != null) {
var user = $.parseJSON(data);
$("#id").val(user.id);
$("#email").val(user.email);
$("#username").val(user.username);
$("#password").val(user.password);
$("#role").val(user.role);
$("#status").val(user.status);
$("#regTime").val(user.regTime);
$("#regIp").val(user.regIp);
}
});
</script>
<script>
$(document).ready(function () {
var data = window.sessionStorage.getItem("user");
if (data != null) {
var user = $.parseJSON(data);
$("#showName").html(user.username);
} else {
$("#showName").append("欢迎");
}
var _url = "http://localhost:8080/ChatRobot/user/allUser";
$.ajax({
url: _url,
type: "GET",
cache: false,
processData: false,
contentType: "application/x-www-form-urlencoded"
}).done(function (data) {
console.log("success!" + data);
$("table").append(data);
}).fail(function (res) {
console.log("sorry,failed!" + res);
});
});
</script>
OK!前端页面的代码没有贴出来,因为代码量实在是太庞大,不过可以前往我的资源https://download.csdn.net/download/qq_29656961/10498799里面去下载,这是我第一次写SSM框架,不足之处还会在后续的学习之中慢慢改进。
最后
以上就是跳跃哈密瓜为你收集整理的IDEA 2018搭建SSM框架实现登录、注册、删除用户、修改个人信息、退出登录等功能的全部内容,希望文章能够帮你解决IDEA 2018搭建SSM框架实现登录、注册、删除用户、修改个人信息、退出登录等功能所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复