Spring MVC入门程序编写
实验要求:
掌握Spring MVC入门程序的编写方法,及简单数据类型的绑定。
实验内容:
实验1:按照教材10.2小节的内容和案例的实现步骤,完成Spring MVC应用案例代码的编写。
实验2: 编写客户信息(客户名称、客户单位、客户职位、客户生日、客户性别、客户联系方式)注册页面customer.jsp,提交到控制器customerController中,控制器判断客户是否是“zhangsan”,如果是则将客户信息显示在customerdisp.jsp页面上,否则在页面上提示“注册客户不是zhangsan”。(通过Mybatis访问用户表,获取用户信息,做用户的校验)
实验分析:
- 实验1主要考查对Spring MVC的核心类和注解的掌握。
- 实验2使用的Spring MVC注解方式实现页面显示及跳转。并利用之前学习的MyBatis相关知识实现对数据库的连接。
- 如果没有标注实验一,那么就是实验二或者共用的代码。
- 实验还需要配置Tomcat服务器,读者可根据自己电脑的tomcat版本自行配置。
根据实验在数据库中建立的 t_customer表
实验操作所用工具(软件):
IntelliJ IDEA 2021.2.1
实验代码
pom.xml
<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 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>test8</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>test8 Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.23</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>test8</finalName>
</build>
</project>
Resource
jdbc.properties(数据库连接配置文件)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useSSL=false
jdbc.username=root
jdbc.password=1
log4j.properties(MyBatis和控制台日志配置文件)(非必要)
#全局日志配置
log4j.rootLogger=DEBUG,Console
#控制台输出配置
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
#日志输出级别
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
mybatis-config.xml(MyBatis的核心配置文件)
<?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="jdbc.properties"/>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<package name="com.cqust.pojo"/>
</typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.cqust.mapper"/>
</mappers>
</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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--配置Spring MVC要扫描的包-->
<context:component-scan base-package="com.cqust"/>
<!-- 配置视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 查找视图页面的前缀 -->
<property name="prefix" value="/WEB-INF/pages/"/>
<!-- 查找视图页面的后缀 -->
<property name="suffix" value=".jsp"/>
</bean>
<!-- -->
<mvc:annotation-driven/>
<!-- 配置一个Handler来处理静态资源(img壁纸) -->
<mvc:resources mapping="/img/**/" location="/img/"/>
</beans>
在Resource下建立com.cqust.mapper包,在该包下建立ClientMapper.xml文件
ClientMapper.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.cqust.mapper.ClientMapper">
<resultMap id="BaseResultMap" type="com.cqust.pojo.Client">
<id property="id" column="id" jdbcType="INTEGER"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="sex" column="sex" jdbcType="VARCHAR"/>
<result property="job" column="job" jdbcType="VARCHAR"/>
<result property="phone" column="phone" jdbcType="VARCHAR"/>
<result property="birthday" column="birthday" jdbcType="DATE"/>
<result property="unit" column="unit" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id,name,sex,
job,phone,birthday,
unit
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_customer
where id = #{id,jdbcType=INTEGER}
</select>
<!--根据名字查询用户信息-->
<select id="selectByName" resultType="com.cqust.pojo.Client">
select *
from t_customer
where name = #{name};
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
delete from t_customer
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.cqust.pojo.Client" useGeneratedKeys="true">
insert into t_customer
( id,name,sex
,job,phone,birthday
,unit)
values (#{id,jdbcType=INTEGER},#{name,jdbcType=VARCHAR},#{sex,jdbcType=VARCHAR}
,#{job,jdbcType=VARCHAR},#{phone,jdbcType=VARCHAR},#{birthday,jdbcType=DATE}
,#{unit,jdbcType=VARCHAR})
</insert>
<!--插入用户信息-->
<insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.cqust.pojo.Client" useGeneratedKeys="true">
insert into t_customer
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">id,</if>
<if test="name != null">name,</if>
<if test="unit != null">unit,</if>
<if test="birthday != null">birthday,</if>
<if test="sex != null">sex,</if>
<if test="job != null">job,</if>
<if test="phone != null">phone,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">#{id,jdbcType=INTEGER},</if>
<if test="name != null">#{name,jdbcType=VARCHAR},</if>
<if test="unit != null">#{unit,jdbcType=VARCHAR},</if>
<if test="birthday != null">#{birthday,jdbcType=DATE},</if>
<if test="sex != null">#{sex,jdbcType=VARCHAR},</if>
<if test="job != null">#{job,jdbcType=VARCHAR},</if>
<if test="phone != null">#{phone,jdbcType=VARCHAR},</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.cqust.pojo.Client">
update t_customer
<set>
<if test="name != null">
name = #{name,jdbcType=VARCHAR},
</if>
<if test="sex != null">
sex = #{sex,jdbcType=VARCHAR},
</if>
<if test="job != null">
job = #{job,jdbcType=VARCHAR},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="birthday != null">
birthday = #{birthday,jdbcType=DATE},
</if>
<if test="unit != null">
unit = #{unit,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.cqust.pojo.Client">
update t_customer
set
name = #{name,jdbcType=VARCHAR},
sex = #{sex,jdbcType=VARCHAR},
job = #{job,jdbcType=VARCHAR},
phone = #{phone,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=DATE},
unit = #{unit,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
webapp层
index.jsp(实验一)
<html>
<body>
<div style="text-align: center;">
<h2>Hello Spring MVC!</h2>
</div>
</body>
</html>
customer.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户注册</title>
<style>
body{
margin:0;
padding:0;
font-family:sans-serif;
/*壁纸*/
background: url("img/wallpaper.jpg");
background-size:cover;
/*background-color:rgba(240,255,255,0.5);*/
}
#box
{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
width:400px;
padding:40px;
font-size: 18px;
/*background:rgba(75,81,95,0.3);*/
box-sizing:border-box;
/*盒子阴影颜色*/
box-shadow:7px 7px 17px rgba(52,56,66,0.5);
border-radius:10px;/*登录窗口边角圆滑*/
}
</style>
</head>
<body>
<div id="box" style="text-align: left;">
<form action="client" method="post">
用户姓名:<input type="text" name="name"/><br/>
用户单位:<input type="text" name="unit"/><br/>
用户职位:<input type="text" name="jobs"/><br/>
用户生日:<input type="date" name="birthday"/><br/>
用户性别:<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女<br/>
联系方式:<input type="tel" name="phone"/><br/><br/>
<div style="text-align: center">
<input type="submit" value="注册" />
<input type="reset" value="重置"/>
</div>
</form>
</div>
</body>
</html>
img包
wallpaper.jpg
WEB-INF包
web.xml
<?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">
<servlet>
<servlet-name>myweb</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myweb</servlet-name>
<url-pattern>/</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>
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<!-- /*:表示强制所有请求先通过过滤器-->
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
pages包
success.jsp(实验一)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>success</title>
</head>
<body>
<div style="text-align: center;">
<h2>Hello FirstController!</h2>
</div>
</body>
</html>
customerdisp.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册成功</title>
<style>
body{
margin:0;
padding:0;
font-family:sans-serif;
/*background-color: darkseagreen;*/
background-image: image("../../img/wallpaper.jpg");
background-size:cover;
/*更改背景颜色*/
background-color: rgba(7, 255, 255, 0.5);
}
#box
{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
width:400px;
padding:40px;
font-size: 18px;
/*更改背景颜色*/
background: rgba(238, 238, 238, 0.3);
box-sizing:border-box;
/*更改阴影背景颜色*/
box-shadow:7px 7px 17px rgba(92, 92, 92, 0.5);
border-radius:10px;/*登录窗口边角圆滑*/
}
</style>
</head>
<body>
<div id="box" style="text-align: left;">
<h2>${client}</h2>
</div>
</body>
</html>
default.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册失败</title>
<style>
body{
margin:0;
padding:0;
font-family:sans-serif;
/*背景颜色*/
background-color: #4ae642;
background-image: image("../../img/wallpaper.jpg");
background-size:cover;
/*background-color:rgba(240,255,255,0.5);*/
}
#box
{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
width:400px;
padding:40px;
font-size: 18px;
/*盒子背景颜色*/
background: rgb(10, 2, 2);
box-sizing:border-box;
/*盒子阴影背景颜色*/
box-shadow:7px 7px 17px rgba(52,56,66,0.5);
border-radius:10px;/*登录窗口边角圆滑*/
}
h2{
/*标题背景颜色*/
color: #ff2626;
}
</style>
</head>
<body>
<div id="box" style="text-align: left;">
<h2>${msg}</h2>
</div>
</body>
</html>
实验1
controller层
FirstController类
package com.cqust.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class FirstController {
@RequestMapping(value = "/firstController")
public String sayHello(){
System.out.println("访问到FirstController!");
return "success";
}
}
实验2
controller层
ClientController类
package com.cqust.controller;
import com.cqust.pojo.Client;
import com.cqust.service.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
@RestController
@RequestMapping("/client")
public class ClientController {
@Autowired
private ClientService clientService;
@PostMapping
public ModelAndView register(Client client){
ModelAndView mv = new ModelAndView();
Client client1 = clientService.getbyName(client.getName());
if (client1!=null){
mv.addObject(client1);
mv.setViewName("customerdisp");
}else{
clientService.save(client);
mv.addObject("msg","注册客户不是zhangsan");
mv.setViewName("default");
}
return mv;
}
}
mapper层
ClientMapper接口
package com.cqust.mapper;
import com.cqust.pojo.Client;
public interface ClientMapper {
Client selectByName(String name);
int insertSelective(Client record);
int deleteByPrimaryKey(Long id);
int insert(Client record);
Client selectByPrimaryKey(Long id);
int updateByPrimaryKeySelective(Client record);
int updateByPrimaryKey(Client record);
}
pojo层
Client类
package com.cqust.pojo;
import java.io.Serializable;
import lombok.Data;
@Data
public class Client implements Serializable {
private Integer id;
private String name;
private String sex;
private String job;
private String phone;
private String birthday;
private String unit;
private static final long serialVersionUID = 1L;
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
Client other = (Client) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName()))
&& (this.getSex() == null ? other.getSex() == null : this.getSex().equals(other.getSex()))
&& (this.getJob() == null ? other.getJob() == null : this.getJob().equals(other.getJob()))
&& (this.getPhone() == null ? other.getPhone() == null : this.getPhone().equals(other.getPhone()))
&& (this.getBirthday() == null ? other.getBirthday() == null : this.getBirthday().equals(other.getBirthday()))
&& (this.getUnit() == null ? other.getUnit() == null : this.getUnit().equals(other.getUnit()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
result = prime * result + ((getSex() == null) ? 0 : getSex().hashCode());
result = prime * result + ((getJob() == null) ? 0 : getJob().hashCode());
result = prime * result + ((getPhone() == null) ? 0 : getPhone().hashCode());
result = prime * result + ((getBirthday() == null) ? 0 : getBirthday().hashCode());
result = prime * result + ((getUnit() == null) ? 0 : getUnit().hashCode());
return result;
}
@Override
public String toString() {
return
"姓名:" + name
+"<br/>"+
"性别:" + sex
+"<br/>"+
"生日:" + birthday
+"<br/>"+
"单位:" + unit
+"<br/>"+
"职位:" + job
+"<br/>"+
"电话:" + phone;
}
}
service层
ClientService类
package com.cqust.service;
import com.cqust.pojo.Client;
public interface ClientService {
Client getbyName(String name);
boolean save(Client client);
}
Impl包
ClientServiceImpl类
package com.cqust.service.impl;
import com.cqust.pojo.Client;
import com.cqust.mapper.ClientMapper;
import com.cqust.service.ClientService;
import com.cqust.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;
@Service
public class ClientServiceImpl implements ClientService {
SqlSession sqlSession;
ClientMapper clientMapper;
{
sqlSession = MyBatisUtils.getSession();
clientMapper = sqlSession.getMapper(ClientMapper.class);
}
public Client getbyName(String name) {
return clientMapper.selectByName(name);
}
public boolean save(Client client) {
return clientMapper.insertSelective(client)>0?true:false;
}
}
utils层
MyBatisUtils类
package com.cqust.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.Reader;
/**
* 工具类
*/
public class MyBatisUtils {
private static SqlSessionFactory sqlSessionFactory = null;
//初始化SQLSessionFactory对象
static {
try{
//使用MyBatis提供的Resource类加载MyBatis的配置文件
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
//构建SQLSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e){
e.printStackTrace();
}
}
//获取SqlSession对象的方法
public static SqlSession getSession(){
//若传入true表示关闭事务控制,自动提交;false表示开启事务控制
return sqlSessionFactory.openSession(true);
}
}
程序运行结果:
实验1:
实验2:
注册界面:
注册成功:
注册失败:
实验总结:
本次实验主要是对实验2的书写,实验2主要运用了Spring MVC注解方式编写,这期博客打算再水一下,这个版本的代码写的非常的粗糙鄙陋,主要是我自己对Spring MVC的理解还是很模糊,希望后期学到新知识后能进行改进(本人真的很懒哈哈哈!)。
写在最后:各位看到此博客的小伙伴,如有疑问或者不对的地方请及时通过私信我或者评论此博客的方式指出,以免误人子弟。多谢!
谢谢浏览!