JavaWeb学习——SSM框架实现登陆、注册与增删查改
- 1.各项配置
-
- 1. 依赖配置(pom.xml)
- 2. web配置(web.xml)
- 3. Spring配置(applicationContext.xml)
- 4. SpringMV配置(spring-mvc.xml)
- 5. Mybatis配置
-
- 2.视图层
-
- 3.web层
- 4.service层
-
- 1.service接口
- 2.service接口实现
- 5.mapper层
1.各项配置
1. 依赖配置(pom.xml)
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.28version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.6version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.7version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.2.8version>
dependency>
<dependency>
<groupId>org.jsoupgroupId>
<artifactId>jsoupartifactId>
<version>1.11.2version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-coreartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-annotationsartifactId>
<version>2.9.0version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>commons-beanutilsgroupId>
<artifactId>commons-beanutilsartifactId>
<version>1.9.4version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.1.10.RELEASEversion>
dependency>
dependencies>
2. web配置(web.xml)
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
3. Spring配置(applicationContext.xml)
<context:component-scan base-package="com.Rendan">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<context:property-placeholder location="classpath:druid.properties"/>
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${druid.url}">property>
<property name="username" value="${druid.username}">property>
<property name="password" value="${druid.password}">property>
<property name="driverClassName" value="${druid.driverClassName}">property>
<property name="initialSize" value="${druid.initialSize}">property>
<property name="maxActive" value="${druid.maxActive}">property>
<property name="maxWait" value="${druid.maxWait}">property>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="druidDataSource">property>
<property name="configLocation" value="classpath:sqlMapConfig.xml">property>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.Rendan.mapper">property>
bean>
4. SpringMV配置(spring-mvc.xml)
<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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.Rendan.web"/>
<mvc:default-servlet-handler/>
beans>
5. Mybatis配置
核心文件
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.Rendan.domain"/>
typeAliases>
configuration>
实现接口配置(sql语句)
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.Rendan.mapper.MangerMapper">
<select id="findAll" resultType="user">
select *
from user
select>
<select id="manger_login" parameterType="manger" resultType="manger">
select *
from manger
where mangerName = #{mangerName}
and password = #{password}
select>
<insert id="addUser" parameterType="user">
insert into user
values (null, #{userName}, #{gender}, #{age}, #{tel}, #{password})
insert>
<select id="findAllFood" resultType="food">
select *
from food
select>
<insert id="addFood" parameterType="food">
insert into food
values (null, #{foodName}, #{foodDescription}, #{price}, #{unit})
insert>
<select id="findFoodById" parameterType="int" resultType="food">
select *
from food
where id = #{id}
select>
<update id="updateFood" parameterType="food">
update food
set foodName = #{foodName},
foodDescription = #{foodDescription},
price = #{price},
unit = #{unit}
where id = #{id}
update>
<delete id="deleteFoodById" parameterType="int">
delete
from food
where id = #{id}
delete>
<select id="findFoodsById" parameterType="int" resultType="food">
select *
from user_food uf,
food f
where uf.foodId = f.id
and uf.userId = #{id}
select>
mapper>
2.视图层
1. 登陆视图层
<body>
<%--动态获取虚拟目录--%>
<form action="${pageContext.request.contextPath}/manger/login" method="post">
<div class="wapper">
<img class="logo" src="../images/logo-main.jpg">
<h2>你好管理员!h2>
<div class="a">
<span>用户名:span>
<input class="user" type="text" placeholder="请输入用户名" name="mangerName"><br>
div>
<div class="b">
<span>密 码:span>
<input class="user" type="password" placeholder="请输入密码" name="password"><br>
div>
<input class="three" type="submit" value="登 录">
<div class="focus">
<%--el获取域中数据--%>
<%--验证码--%>
${requestScope.cc_error}
<%--用户名与密码--%>
${requestScope.longin_error}
<%--登录过滤器--%>
${requestScope.login_msg}
div>
div>
<%
//获取所有Cookie
Cookie[] cookies = request.getCookies();
boolean flag = false;//没有cookie为lastTime
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
//获取cookie名称
String name = cookie.getName();
if ("lastTime".equals(name)) {
flag = true;
//有该cookie,不是第一次访问
//响应数据
//获取cookie的value实际时间
String time = cookie.getValue();
//URL解码
time = URLDecoder.decode(time, "utf-8");
%>
<div class="time">
<span>欢迎回来,您上次访问的时间为: <%= time%> span>
div>
<%
//设置cookie的value
//获取当前时间字符,重新设置Cookie,重新发送Cookie
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
//URL编码解决特殊字符无法识别
str_date = URLEncoder.encode(str_date, "utf-8");
cookie.setValue(str_date);
//设置cookie存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
response.addCookie(cookie);
break;
}
}
}
if (cookies == null || cookies.length == 0 || flag == false) {
//没有 第一次访问
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
String str_date = sdf.format(date);
//URL编码解决特殊字符无法识别
str_date = URLEncoder.encode(str_date, "utf-8");
Cookie cookie = new Cookie("lastTime", str_date);
//设置cookie存活时间
cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
response.addCookie(cookie);
%>
<div class="time">
<span>您好,欢迎首次访问!!!span>
div>
<%
}
%>
form>
2. 操作视图层
<script>
function deleteUser(userId) {
if (confirm("您当真要删除?")){
location.href="${pageContext.request.contextPath}/deleteUser/"+userId;
}
}
script>
head>
<body>
<div class="wapper">
<h2>用户信息列表h2>
<table border="1" class="a">
<tr class="a1">
<th>idth>
<th>用户名th>
<th>性别th>
<th>年龄th>
<th>电话号th>
<th>密码th>
<th>订单th>
<th>操作th>
tr>
<%--jstl简化java书写遍历--%>
<c:forEach items="${users}" var="user" varStatus="s">
<tr>
<td> ${s.count} td>
<td> ${user.userName} td>
<td> ${user.gender} td>
<td> ${user.age} td>
<td>${user.tel}td>
<td> ${user.password} td>
<td>
<c:forEach items="${user.foods}" var="food">
${food.foodName}
c:forEach>
td>
<td>
<a class="cha" href="${pageContext.request.contextPath}/manger/findUserById?id=${user.id}">修改a>
<a class="dle" href="javascript:deleteUser(${user.id})">删除a>
<a class="check" href="${pageContext.request.contextPath}/findUserOrder">查询订单a>
td>
tr>
c:forEach>
table>
<a class="add" href="${pageContext.request.contextPath}/user/add.jsp">添加用户a>
<a class="return"href="${pageContext.request.contextPath}/manger/manger.jsp">返回a>
div>
body>
3.web层
@Controller
@RequestMapping("/manger")
public class MangerController {
@Autowired
private MangerService mangerService;
@Autowired
private UserService userService;
@RequestMapping("/login")
public String login(Manger manger, HttpSession session, Model model) {
try {
Manger manger_login = mangerService.manger_login(manger);
session.setAttribute("manger", manger_login.getMangerName());
return "redirect:/manger/manger.jsp";
} catch (Exception e) {
e.printStackTrace();
model.addAttribute("longin_error", "用户名或密码错误!");
return "/manger/manger_login.jsp";
}
}
@RequestMapping("/findAllUser")
public String FindAllUser(Model model) {
List<User> users = mangerService.findAll();
model.addAttribute("users", users);
return "/manger/allUsers.jsp";
}
@RequestMapping("/updateUser")
public String UpdateUser(User user, String flag, Model model, HttpServletRequest request) {
userService.updateUser(user);
if (flag.equals("reg_success")) {
model.addAttribute("users", user);
request.removeAttribute("flag");
return "/user/userInformation.jsp";
} else {
return "/manger/findAllUser";
}
}
@RequestMapping("/addUser")
public String AddUser(User user){
mangerService.AddUser(user);
return "/manger/findAllUser";
}
@RequestMapping("/findUserById")
public String FindUserById(String id, Model model,String flag){
User user = userService.findUserById(id);
model.addAttribute("user",user);
model.addAttribute("flag",flag);
return "/manger/update.jsp";
}
@RequestMapping("/findAllFood")
public String FindAllFood(Model model){
List<Food> foods = mangerService.findAllFood();
model.addAttribute("foods",foods);
return "/manger/allFoods.jsp";
}
@RequestMapping("/addFood")
public String AddFood(Food foods){
mangerService.AddFood(foods);
return "/manger/findAllFood";
}
@RequestMapping("/findFoodById")
public String FindFoodById(String id, Model model){
Food foods = mangerService.findFoodById(id);
model.addAttribute("foods",foods);
return "/manger/updateFood.jsp";
}
@RequestMapping("/updateFood")
public String UpdateFood(Food food){
mangerService.updateFood(food);
return "/manger/findAllFood";
}
@RequestMapping("/deleteFood")
public String DeleteFood(String id){
mangerService.deleteFood(id);
return "/manger/findAllFood";
}
}
4.service层
1.service接口
public interface MangerService {
public List<User> findAll();
void AddUser(User user);
public Manger manger_login(Manger manger);
List<Food> findAllFood();
void AddFood(Food foods);
Food findFoodById(String id);
void updateFood(Food food);
void deleteFood(String id);
}
2.service接口实现
@Service
public class MangerServiceImpl implements MangerService {
@Autowired
private MangerMapper mangerMapper;
@Override
public List<User> findAll() {
List<User> userList = mangerMapper.findAll();
for (User user : userList) {
int id = user.getId();
List<Food> foods =mangerMapper.findFoodsById(id);
user.setFoods(foods);
}
return userList;
}
@Override
public void AddUser(User user) {
mangerMapper.addUser(user);
}
@Override
public Manger manger_login(Manger manger) {
return mangerMapper.manger_login(manger);
}
@Override
public List<Food> findAllFood() {
return mangerMapper.findAllFood();
}
@Override
public void AddFood(Food foods) {
mangerMapper.addFood(foods);
}
@Override
public Food findFoodById(String id) {
return mangerMapper.findFoodById(Integer.parseInt(id));
}
@Override
public void updateFood(Food food) {
mangerMapper.updateFood(food);
}
@Override
public void deleteFood(String id) {
mangerMapper.deleteFoodById(Integer.parseInt(id));
}
}
5.mapper层
public interface MangerMapper {
public List<User> findAll();
Manger manger_login(Manger manger);
void addUser(User user);
List<Food> findAllFood();
void addFood(Food foods);
Food findFoodById(int id);
void updateFood(Food food);
void deleteFoodById(int id);
List<Food> findFoodsById(int id);
}