截图:
目录
1.项目结构
2.配置文件
2.1spring配置文件(applicationContent.xml)
2.2 sqlConfig.xml(mybatis配置文件)
2.3log4j.properties
2.4springmvc.xml (springmvc的配置文件)
2.5jdbc.properties
2.6 web.xml
3.后端代码
3.1 实体类
3.2:创建DAO接口【在mybatis中 mapper就相当于dao]
3.3实现dao接口【mybatis中就是UserMapper.xml文件】
3.4建立service以及service实现【UserService.java】
3.5service实现类 【UserServiceImpl.java】
3.6建立controller
3.6.1 UserController.java
3.6.2 LoginController.java
简单制作的demo,初衷是搭建一个:可以通过后台数据配置,形成页面内容可定制的企业门户网站,现在还在开发中,下面是详细步骤,会加入一些提示和自己在敲码时学习到的知识和一些遇到的问题。
使用到的"工具":IDEA旗舰版,MySQL8.0,JDK11,apache-maven-3.8.6,apache-tomcat-8.5.81,Dbeaver
ps:建议用IDEA旗舰版(可免费试用30天或者破解),社区版配置tomcat很麻烦会导致配置失败~
1.项目结构
一张图显示不下放了两张,用的是idea,eclipse基本上差不多
ps:两个工具最大的区别就是,idea的project=eclipse的workspace,其他对应关系如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>untitled1</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><properties><piler.source>11</piler.source><piler.target>11</piler.target></properties><dependencies><!-- springMVC --><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>4.3.7.RELEASE</version></dependency><!-- spring jdbc --><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>4.3.7.RELEASE</version></dependency><!-- spring aop --><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>4.3.7.RELEASE</version></dependency><!-- mybatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.2</version></dependency><!-- mybatis与spring整合 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version></dependency><!-- 数据库连接池 和驱动--><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>0.9.1.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.29</version></dependency><!-- jstl junit servlet-api --><dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version><scope>provided</scope></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- spring单元测试 --><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>4.3.7.RELEASE</version><scope>test</scope></dependency><!-- 引入Mybatis分页插件 --><!-- 引入5.0版本在测试的时候会报错 4.2版本也会报错4.2版本总是出现String无法转换为某个对象的错误--><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>4.1.5</version></dependency></dependencies><build><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build></project>
根据pom.xml中的dependency导入后的jar包:
2.配置文件
2.1spring配置文件(applicationContent.xml)
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:aop="/schema/aop"xmlns:tx="/schema/tx" xmlns:mvc="/schema/mvc"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd/schema/context/schema/context/spring-context.xsd/schema/tx/schema/tx/spring-tx.xsd/schema/mvc/schema/mvc/spring-mvc.xsd"><!-- 注解扫描包 --><context:component-scan base-package="com.ssm" /><!-- 加载jdbc.properties文件 --><context:property-placeholder location="classpath:jdbc.properties"/><!--第一步: 配置数据源 --><bean id="dataSource" class="com.mchange.boPooledDataSource"><property name="jdbcUrl" value="${jdbc.url}"></property><property name="driverClass" value="${jdbc.driver}"></property><property name="user" value="${jdbc.username}"></property><property name="password" value="${jdbc.password}"></property></bean><!-- 配置和mybatis的整合 --><!--第二步: 创建sqlSessionFactory工厂 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource"></property><!-- 指定Mybatis全局配置文件的位置 --><property name="configLocation" value="classpath:sqlConfig.xml"></property></bean><!-- 配置mybatis的代理接口开发 * 接口类名和映射文件必须同名 * 接口类和映射文件必须在同一个目录下 * 接口的映射文件的namespace名称必须是接口的全限定名* 接口的方法名必须和映射的statement的id一致 --><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 扫描所有dao接口的实现,加入到ioc容器中 --><property name="basePackage" value="com.ssm.mapper"></property><property name="SqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean><!--第三步: 事物 --><bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"></property></bean><!-- 配置拦截service --><aop:config><aop:pointcut expression="execution(* com.ssm.service..*(..))" id="txPoint"/><aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/></aop:config><!-- 配置事物增强,事物如何切入--><tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><!-- 所有方法都是事物方法 --><tx:method name="*"/><!-- 以get开始的所有方法 --><tx:method name="get*" read-only="true"/></tx:attributes></tx:advice></beans>
2.2 sqlConfig.xml(mybatis配置文件)
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-////DTD Config 3.0//EN""/dtd/mybatis-3-config.dtd"><configuration><!-- 别名设置 --><typeAliases><package name="com.ssm.model" /></typeAliases><!-- mybatis分页插件 --><plugins><plugin interceptor="com.github.pagehelper.PageHelper"></plugin></plugins></configuration>
2.3log4j.properties
### set log levels ###log4j.rootLogger = INFO , console , debug , error ### console ###log4j.appender.console = org.apache.log4j.ConsoleAppender log4j.appender.console.Target = System.out log4j.appender.console.layout = org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n ### log file ###log4j.appender.debug = org.apache.log4j.DailyRollingFileAppender log4j.appender.debug.File = ../logs/springmvc-demo.log log4j.appender.debug.Append = true log4j.appender.debug.Threshold = INFO log4j.appender.debug.layout = org.apache.log4j.PatternLayout log4j.appender.debug.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n ### exception ###log4j.appender.error = org.apache.log4j.DailyRollingFileAppender log4j.appender.error.File = ../logs/springmvc-demo_error.log log4j.appender.error.Append = true log4j.appender.error.Threshold = ERROR log4j.appender.error.layout = org.apache.log4j.PatternLayout log4j.appender.error.layout.ConversionPattern = %-d{yyyy-MM-dd HH\:mm\:ss} [%p]-[%c] %m%n ###\u9700\u8981\u58F0\u660E\uFF0C\u7136\u540E\u4E0B\u65B9\u624D\u53EF\u4EE5\u4F7Fdruid sql\u8F93\u51FA\uFF0C\u5426\u5219\u4F1A\u629B\u51FAlog4j.error.key not foundlog4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %l %c%n%p: %m%n ### druid sql ###log4j.logger.druid.sql=warn,stdout log4j.logger.druid.sql.DataSource=warn,stdout log4j.logger.druid.sql.Connection=warn,stdout log4j.logger.druid.sql.Statement=warn,stdout log4j.logger.druid.sql.ResultSet=warn,stdout
2.4springmvc.xml (springmvc的配置文件)
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance"xmlns:aop="/schema/aop"xmlns:tx="/schema/tx"xmlns:mvc="/schema/mvc"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans/schema/beans/spring-beans.xsd/schema/aop/schema/aop/spring-aop.xsd/schema/context/schema/context/spring-context.xsd/schema/tx/schema/context/spring-tx.xsd/schema/mvc/schema/mvc/spring-mvc.xsd"><!-- 扫描注解包 --><context:component-scan base-package="com.ssm"></context:component-scan><!-- 配置sprigmvc视图解析器:解析逻辑试图后台返回逻辑试图:index视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/page/index.jsp--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/page/"></property><property name="suffix" value=".jsp"></property></bean><!--1: mvc:annotation-driven默认创建了 RequestMappingHandlerMapping和 RequestMappingHandlerAdapter对象提供对JSon数据格式的支持--><mvc:annotation-driven /><!-- 2.配置静态资源访问 --><mvc:default-servlet-handler/></beans>
2.5jdbc.properties
jdbc.url = jdbc:mysql://localhost:3306/mtcs?useSSL=falsejdbc.driver = com.mysql.cj.jdbc.Driverjdbc.username= rootjdbc.password= root
ps:
1.一开始jdbc.driver写的是com.mysql.jdbc.Driver(没有添加cj),项目能运行,但是到了数据库操作层的时候报错了,原因是我用的是mysql8.0,需要加上cj;如果是mysql5版本,可不用添加cj。
2.mysql5.7之后的版本必须要加上useSSL=false,因为MySQL在高版本需要指明是否进行SSL连接,mysql5.7以及之前的版本则不用进行添加useSSL=false,会默认为false,一般情况下都是使用useSSL=false,尤其是在将项目部署到linux上时,一定要使用useSSL=false!!!,useSSL=true是进行安全验证,一般通过证书或者令牌什么的,useSSL=false就是通过账号密码进行连接
2.6 web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"xmlns="/xml/ns/javaee"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/xml/ns/javaee/xml/ns/javaee/web-app_2_5.xsd"><display-name>untitled1</display-name><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list><!-- 加载Spring容器配置 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- 配置SpringMVC核心控制器 --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><!-- 拦截所有请求 --><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.jpg</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.png</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.ico</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.gif</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.js</url-pattern></servlet-mapping><servlet-mapping><servlet-name>default</servlet-name><url-pattern>*.css</url-pattern></servlet-mapping><!-- 字符编码过滤器 --><filter><filter-name>CharacterEncodingFilter</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>utf-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>
3.后端代码
3.1 实体类
package com.ssm.model;/*** 描述:用户实体类<BR>* 创建人:<MT>* @version*/public class User {//主键private int id;//用户名private String username;//年龄private String age;//登录账号private String account;//登录密码private String pass;public User() {super();}public User(int id, String username, String age, String account, String pass) {super();this.id = id;this.username = username;this.age = age;this.account = account;this.pass = pass;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getAccount() {return account;}public void setAccount(String account) {this.account = account;}public String getPass() {return pass;}public void setPass(String pass) {this.pass = pass;}}
3.2:创建DAO接口【在mybatis中 mapper就相当于dao]
package com.ssm.mapper;import java.util.List;import com.ssm.model.User;import org.apache.ibatis.annotations.Param;/*** 描述:用户mapper接口<BR>* 创建人:<MT>* @version*/public interface UserMapper {void saveUser(User user);boolean updateUser(User user);boolean deleteUser(int id);User findUserById(int id);User findUserByAccountAndPass(@Param("account")String account, @Param("pass")String pass);List<User> findAll();}
3.3实现dao接口【mybatis中就是UserMapper.xml文件】
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><!--namespace:必须与对应的接口全类名一致 UserMapper.javaid :必须与对应接口的某个对应的方法名一致即必须要和UserMapper.java接口中的方法同名。--><mapper namespace="com.ssm.mapper.UserMapper"><!-- 新增 --><insert id="saveUser" parameterType="User" >insert into t_user(user_name,user_age) values (#{username},#{age})</insert><!-- 修改 --><update id="updateUser" parameterType="User" >update t_user set user_name=#{username},user_age=#{age} where user_id=#{id}</update><!-- 删除 --><delete id="deleteUser" parameterType="int">delete from t_user where user_id=#{id}</delete><!-- 根据id查找单个用户 --><select id="findUserById" parameterType="int" resultType="User">select user_id id,user_name username,user_age age from t_user where user_id=#{id}</select><!-- 根据账号和密码查找单个用户,用于登录 --><select id="findUserByAccountAndPass" parameterType="String" resultType="User">select user_id id,user_name username,user_age age from t_user where user_account=#{account} and user_pass=#{pass}</select><!-- 查询所有 --><select id="findAll" resultType="User">select user_id id,user_name userName,user_age age from t_user</select></mapper>
3.4建立service以及service实现【UserService.java】
package com.ssm.service;import java.util.List;import com.ssm.model.User;/*** 描述:用户service<BR>* 创建人:<MT>* @version*/public interface UserService {void saveUser(User user);boolean updateUser(User user);boolean deleteUser(int id);User findUserById(int id);User findUserByAccountAndPass(String account,String pass);List<User> findAll();}
3.5service实现类 【UserServiceImpl.java】
package com.ssm.service.impl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.ssm.mapper.UserMapper;import com.ssm.model.User;import com.ssm.service.UserService;@Service/*** 描述:用户service实现类<BR>* 创建人:<MT>* @version*/public class UserServiceImpl implements UserService {/*** 注入UserMapper接口*/@Autowiredprivate UserMapper userMapper;/*** 新增用户*/@Overridepublic void saveUser(User user) {userMapper.saveUser(user);}/*** 更新用户*/@Overridepublic boolean updateUser(User user) {return userMapper.updateUser(user);}/*** 根据Id删除用户*/@Overridepublic boolean deleteUser(int id) {return userMapper.deleteUser(id);}/*** 根据id查找用户*/@Overridepublic User findUserById(int id) {User user = userMapper.findUserById(id);return user;}/*** 根据账号密码查找用户*/@Overridepublic User findUserByAccountAndPass(String account,String pass) {User user = userMapper.findUserByAccountAndPass(account,pass);return user;}/*** 查询所有用户*/@Overridepublic List<User> findAll() {List<User> allUser = userMapper.findAll();return allUser;}}
3.6建立controller
3.6.1 UserController.java
package com.ssm.controller;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import com.ssm.model.User;import com.ssm.service.UserService;@Controller@RequestMapping("/user")/*** 描述:用户controller<BR>* 创建人:<MT>* @version*/public class UserController {@Autowiredprivate UserService userService;/***跳转到添加用户界面*/@RequestMapping("toAddUser")public String toAddUser(){return "addUser";}/*** 添加用户并重定向* @param model* @param user* @return*/@RequestMapping("addUser")public String addUser(Model model,User user){if(user != null){userService.saveUser(user);}return "redirect:/user/userInfo";}/*** 修改用户* @param model* @param user* @return*/@RequestMapping("updateUser")public String UpdateUser(Model model,User user){if(userService.updateUser(user)){user = userService.findUserById(user.getId());model.addAttribute("user", user);return "redirect:/user/userInfo";}return "/error";}/*** 查询所有用户* @param model* @return*/@RequestMapping("getAllUser")public String getAllUser(Model model){List<User> user = userService.findAll();model.addAttribute("userList",user);return "allUser";}/*** 查询单个用户* @param id* @param model* @return*/@RequestMapping("/getUser")public String getUser(int id,Model model){model.addAttribute("user", userService.findUserById(id));return "editUser";}/*** 根据id删除用户* @param id*/@RequestMapping("/delUser")public String deleteUser(int id,Model model){model.addAttribute("user", userService.deleteUser(id));return "redirect:/user/userInfo";}/*** 分页查询用户信息* @param pn 默认从第一页开始 请求参数* @param model* @return*/@RequestMapping("userInfo")public String getUsers(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model){//从第一条开始 每页查询五条数据PageHelper.startPage(pn, 5);List<User> users = userService.findAll();//将用户信息放入PageInfo对象里PageInfo page = new PageInfo(users,5);model.addAttribute("pageInfo", page);return "allUser";}}
3.6.2 LoginController.java
登录接口目前写的比较简单,之后再完善,大家可自己发挥一下
package com.ssm.controller;import com.github.pagehelper.PageHelper;import com.github.pagehelper.PageInfo;import com.ssm.model.User;import com.ssm.service.LoginService;import com.ssm.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import java.util.List;@Controller@RequestMapping("/login")/*** 描述:用户controller<BR>* 创建人:<MT>* @version*/public class LoginController {@Autowiredprivate UserService userService;private LoginService loginService;/***跳转到登录界面*/@RequestMapping("toLogin")public String toLogin(){return "login";}@RequestMapping("login")public String UpdateUser(Model model,User user){user = userService.findUserByAccountAndPass(user.getAccount(),user.getPass());if (user!=null){return "manage";}else{return "ERROR";}}}
到这里后端代码已经差不多好了,自行参照修改吧~
前端代码过一会更新,休息一下~
如果觉得《基于SSM实现简单企业/公司门户网站制作》对你有帮助,请点赞、收藏,并留下你的观点哦!