1.项目搭建汇总
最终结果
1.如何创建一个javaweb项目
点击finish完成
2.配置pom.xml文件
如下的pom文件整合了spring框架与mybatis以及thymeleaf,您可以按需索取部分的jar包,但是请注意应当保证jar包版本的兼容一致否则可能会报错,这将在第二部分的问题笔记中提到。您可在报错时查阅问题笔记。
以下是我的配置文件,关联的jar包版本已经一致兼容。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>Spring-mybatis-zhenghe</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Spring-mybatis-zhenghe</name>
<packaging>war</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.7.1</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.9.1</version>
</dependency>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.8</version>
</dependency>
<!--Spring java数据库访问包,提供数据源 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.8</version>
</dependency>
<!--mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!--log4j日志包 -->
<!--<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-</artifactId>
<version>2.6.1</version>
</dependency>-->
<!--start mybatis ORM框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!--mybatis-spring适配器 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--end mybatis数据库-->
<!--el表达式-->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jstl/jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--end el表达式-->
<!--数据池-->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<!--end 数据池-->
<!--start thymeleaf-->
<!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring3</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<!--end thymeleaf-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--以下系统自动生成 包含单元测试-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.1</version>
</plugin>
</plugins>
</build>
</project>
3.部署开发环境
1.部署tomcat
如果您发现您的idea并没有tomcat,或者提示找不到tomcat目录而您又遗忘了tomcat的位置,您可以按照如下流程操作
1.官网下载tomcat包
https://tomcat.apache.org/
2.设置服务器根目录
这样idea就能够找到tomcat服务器所在,并运行其中的bin
2.使用git管理你的项目
这是一个很现实的问题,协同开发是不可避免的,你需要一个好帮手而git就是这样的角色
如果你不知道如何部署git并建立安全的链接,很多时候我们需要密匙来开发我们的项目,这些操作您可以参考我的另一篇文章:
Git入门使用——知晓变更控制的决策者
关于git基本指令,您可以参考我的这篇文章:
https://blog.csdn.net/qq_43398404/article/details/110282376
在本项目中,我建议您为gitignore添加如下代码
target/
*.jar
.idea
*.iml
*.ipr
这将减少git推送的流量,并节省您的时间
4.添加applicationContext文件
在开始创建之前我们先写个参数文件
下面是最基本的参数,您可以直接复制
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/2021shixi
username=root
password=root
现在我们来处理appcontext文件
下面是添加了thymeleaf框架后的整合appcontext文件,您可以看到org.thymeleaf.spring3.templateresolver.SpringResourceTemplateResolver
取代了org.springframework.web.servlet.view.InternalResourceViewResolver
这意味这我们不再依赖servlet的视图管理。
如果您依然选择老旧的jsp页面去做项目,那么请注释掉关于thymeleaf的三个声明bean。并将org.springframework.web.servlet.view.InternalResourceViewResolver注释回来。
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-5.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<util:properties id="dataparam" location="classpath:db.properties">
</util:properties>
<!--data source -->
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="#{dataparam.driver}"></property>
<property name="url" value="#{dataparam.url}"></property>
<property name="username" value="#{dataparam.username}"></property>
<property name="password" value="#{dataparam.password}"></property>
<!--<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>-->
</bean>
<!--3 会话工厂bean sqlSessionFactoryBean 这是为数据源创建的临时对话-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据源 -->
<property name="dataSource" ref="datasource"></property>
<!--<!– 配置MyBatis的核心配置文件所在位置 –>
<property name="configLocation"
value="classpath:mybatis-config.xml" />-->
<!-- sql映射文件路径 -->
<property name="mapperLocations" value="classpath*:com/example/Spring_mybatis_zhenghe/mapper/*Mapper.xml"></property>
</bean>
<!--4 自动扫描对象关系映射 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定会话工厂,如果当前上下文中只定义了一个则该属性可省去 -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
<!-- 指定要自动扫描接口的基础包,实现接口 -->
<property name="basePackage" value="com.example.Spring_mybatis_zhenghe.mapper"></property>
</bean>
<!--5 声明式事务管理 -->
<!--定义事物管理器,由spring管理事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="datasource"></property>
</bean>
<!--支持注解驱动的事务管理,指定事务管理器 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!--以下是spring mvc的内容配置-->
<!--采用注解的方式将controller注解到urlhandlermapping-->
<!--6 qidongsaomiao容器自动扫描IOC组件 -->
<context:component-scan base-package="com.example.Spring_mybatis_zhenghe"></context:component-scan>
<!--开启mvc的注解扫描-->
<!-- <mvc:annotation-driven></mvc:annotation-driven>-->
<!-- 注册视图解析器 五大组件之一 必须声明-->
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp" ></property>
</bean>-->
<!--springMVC+thymeleaf的跳转页面配置-->
<bean id="templateResolver"
class="org.thymeleaf.spring3.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".html" />
<property name="templateMode" value="HTML5" />
<property name="characterEncoding" value="UTF-8"/>
</bean>
<bean id="templateEngine"
class="org.thymeleaf.spring3.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
</bean>
<bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8"></property>
</bean>
<!--以下是当不使用注解方式 要声明controller同时还要创建handlermapping对象并为其中注入controller-->
<!--<!–声明controller–>
<bean id="helloController" class="com.example.Spring_mvc.controller.HelloController"></bean>
<!–定义处理映射的handlermapping–>
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<!–指定请求和Controller对应关系 –>
<property name="mappings">
<props>
<!––>
<prop key="/demo/hello.do" >helloController</prop>
</props>
</property>
</bean>-->
</beans>
5.配置您的web文件
以下是最简单的配置模板您可一直接复制
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!--应用上下文对象servletContext-->
<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>
<!--配置过滤器进行对编码的处理-->
<filter>
<filter-name>encodingFiler</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>encodingFiler</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>ssm</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ssm</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
我建议您充分了解五大组件,因为我们的配置文件基本是对这些组件的声明配置。
至此我们的项目配置基本完结可以准备业务逻辑,数据库连接了
6.后端业务逻辑
1.建立数据库接口
ssm使用mybatis连接数据库,在上面的配置文件中我们已经写好了数据连接的必要声明配置。
mybatis框架结构非常清晰而且优化很好,我们只需要配置xml文件并在spring中注入一个mapper的bean就能连接数据库了。
请注意xml文件的包名与mapper接口类保持相同,这也是一种最简单的方法。
usermapper.xml如下
注意修改namespace,和resultype
<?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.example.Spring_mybatis_zhenghe.mapper.UserMapper">
<select id="findById" resultType="com.example.Spring_mybatis_zhenghe.entity.User" parameterType="int">
select
*
from user
where id = #{id}
</select>
<select id="findByName" resultType="com.example.Spring_mybatis_zhenghe.entity.User" parameterType="String">
select * from user where uname=#{uname}
</select>
<select id="findByNamePassword" resultType="com.example.Spring_mybatis_zhenghe.entity.User">
select * from user where uname=#{arg0} and password=#{arg1}
</select>
<select id="addUser" parameterType="com.example.Spring_mybatis_zhenghe.entity.User" >
INSERT INTO `2021shixi`.`user` ( `uname`, `password`) VALUES (#{uname}, #{password});
</select>
</mapper>
usermapper.interface
package com.example.Spring_mybatis_zhenghe.mapper;
import com.example.Spring_mybatis_zhenghe.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
public User findById(int id);
public User findByName(String name);
public User findByNamePassword(String uname,String password);
public void addUser(User user);
}
2.传递数据到业务层
spring通过注解来管理对象,所以自创建的接口都没有注解也不能有注解否则spring无法通过接口创建类,会报createbean异常,但是实现类要有注解。
dao层
接口
package com.example.Spring_mybatis_zhenghe.dao;
import com.example.Spring_mybatis_zhenghe.entity.User;
public interface UserDao {
public int getUserId(int id);
public User login(String uname, String password);
public int register(User user);
public User findById(int id);
}
实现类
package com.example.Spring_mybatis_zhenghe.dao.impl;
import com.example.Spring_mybatis_zhenghe.dao.UserDao;
import com.example.Spring_mybatis_zhenghe.entity.User;
import com.example.Spring_mybatis_zhenghe.mapper.UserMapper;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Resource
UserMapper userMapper;
public int getUserId(int id){
User user=userMapper.findById(id);
return user.getId();
}
//名字与密码通过mapper层获得用户对象
public User login(String uname,String password){
User user=userMapper.findByNamePassword(uname,password);
return user;
}
public int register(User user){
try{userMapper.addUser(user);
System.out.println("dao添加用户");
return 1;
}catch (Exception e){
System.out.println(e.toString());
return 0;
}
}
public User findById(int id){
/*ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
userMapper = applicationContext.getBean("userMapper",UserMapper.class);*/
/*userMapper = (UserMapper) MapperContextUtil.getMapper("userMapper",UserMapper.class);*/
return userMapper.findById(id);
/*SqlSession session = MyBatisUtil.getSession();
//use mapper to find data
User user = session.selectOne("com.example.Spring_mybatis.mapper.UserMapper.findById",id);
System.out.println("is user is null? "+user);
session.close();
return user;*/
}
}
逻辑层service
接口
package com.example.Spring_mybatis_zhenghe.service;
import com.example.Spring_mybatis_zhenghe.entity.User;
public interface UserService {
public User findById(int id);
public User findByName(String name);
public User findByNamePassword(String uname, String password);
public void addUser(User user);
}
实现类
package com.example.Spring_mybatis_zhenghe.service.impl;
import com.example.Spring_mybatis_zhenghe.dao.UserDao;
import com.example.Spring_mybatis_zhenghe.entity.User;
import com.example.Spring_mybatis_zhenghe.service.UserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao ;
@Override
public User findById(int id) {
return userDao.findById(id);
}
@Override
public User findByName(String name) {
return null;
}
@Override
public User findByNamePassword(String uname, String password) {
User user = userDao.login(uname,password);
return user;
}
@Override
public void addUser(User user) {
userDao.register(user);
}
}
控制层
package com.example.Spring_mybatis_zhenghe.controller;
import com.example.Spring_mybatis_zhenghe.entity.User;
import com.example.Spring_mybatis_zhenghe.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@Controller
/*@RequestMapping("/user")*/
public class UserController {
@Resource
UserService userService;
@RequestMapping("/login.do")
public String login(String uname,String password,ModelMap model,HttpSession session){
User user;
user = userService.findByNamePassword(uname,password);
if (user == null){
model.addAttribute("msg","用户名或密码错误!");
return "login";
}
session.setAttribute("user",user);
return "index";
}
@RequestMapping("/register.do")
public String register(String uname, String password, ModelMap model, HttpSession session){
User user = new User();
user.setUname(uname);
user.setPassword(password);
session.setAttribute("user",user);
userService.addUser(user);
model.addAttribute("uname",user.getUname());
return "index";
}
@RequestMapping("/findById.do")
public ModelAndView findById(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
if ((httpServletRequest.getParameter("id")) !=null){
int id = Integer.parseInt(httpServletRequest.getParameter("id"));
User user = userService.findById(id);
}
httpServletResponse.getOutputStream().write("".getBytes(StandardCharsets.UTF_8));
return new ModelAndView("index");
}
@RequestMapping("/ajax.do")
public void ajax(HttpServletRequest request,HttpServletResponse response) throws IOException{
response.getOutputStream().write("响应ajax".getBytes(StandardCharsets.UTF_8));
}
}
注意观察注解的使用方式,另外控制层提供了很多参数的传递方法请注意细看。
3.编写测试类
检验数据传输,您可以使用如下模板
import com.example.Spring_mybatis_zhenghe.entity.User;
import com.example.Spring_mybatis_zhenghe.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.jupiter.api.Test
public void test(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = applicationContext.getBean("userService", UserService.class);
/*User byId = userService.findById(1);
System.out.println(byId);*/
User user = new User();
user.setUname("a");
user.setPassword("123");
userService.addUser(user);
}
}
7.前端
1.前端框架thymeleaf
该框架提供html原型能够方便及时查看页面设计,而且在数据为空时不会出现错误,很好的脱离了后端,是目前开发的主流选择。
关于详解请参照*
https://www.jianshu.com/p/ac31a0b2c74b
下面是本项目的选例,可帮助理解th标签
(1)用户登陆报错:
(2)页面共享
请参考这篇文章
https://blog.csdn.net/spurs611/article/details/105092943/
2.问题笔记汇总
1.关于controller
controller返回视图的多种方法
需要注意方法体形参需要与前台一致,同时我们建议声明httpsession来保存一些数据
@RequestMapping("/register.do")
public String register(String uname, String password, ModelMap model, HttpSession session){
User user;
user = userService.findByNamePassword(uname,password);
session.setAttribute("user",user);
model.addAttribute("uname",user.getUname());
return "index";
}
一些解析详见
https://www.cnblogs.com/zhaojiankai/p/8184207.html
2.关于项目结构的问题:
1.标准项目结构
2.资源无法展示问题
web资源例如jsp文件应当放在webapp下(也是你的web项目的根目录)不应当放在WEB-INF下
WEB-INF是安全目录,其下的静态资源将不能访问。
3.校验target文件夹
校验生成文件夹是排查错误的一种途径,很多时候,jar包,class文件没有更新或者是文件没有被取代。
4.手动添加jar包
这种方式不推荐,因为在target当中并不能发现导入的jar包,这可能与我选择使用maven管理jar包有关。
另外请结合官方库进行判断是否有该jar包,pom程序报红并不意味没有该包请手动刷新同步。
官方库地址:https://mvnrepository.com/artifact/org.springframework/
手动添加jar包的方式:
选择file-project structure-moulde-dependency
3.如何理解springmvc配置文件
该配置文件是结合注释部分来理解的
文章先写到这里,后续补坑~