SpringMVC web 注解实现
1,配置web.xml
实现将所有的web访问引入到SpringMVC框架中
<servlet>
<servlet-name>aaa</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>
</servlet>
<servlet-mapping>
<servlet-name>aaa</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
2,引入maven的依赖
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.star</groupId>
<artifactId>StarShow</artifactId>
<version>1.0-SNAPSHOT</version>
<!--将当前工程打包为web-->
<packaging>war</packaging>
<build>
<!--引入maven插件-->
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!--引入junit单元测试依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--引入SpringContext的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!--引入SpringWebMVC的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<!--引入AspectJ框架(xml方式)实现aop(可不用)-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!--引入jsp的依赖-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--引入servlet的依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!--引入jstl的依赖-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.4</version>
</dependency>
</dependencies>
</project>
3,配置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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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">
<!--配置视图路径,自动在前面添加部分路径-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--在前面添加路径 例子:WEB-INF/view/show.jsp-->
<property name="prefix" value="/WEB-INF/view/"/>
</bean>
<!--配置默认的servlet,静态资源可以直接访问-->
<mvc:default-servlet-handler/>
<!--上下文组件扫描,扫描指定包内的组件-->
<context:component-scan base-package="com.star.controller"/>
<!--配置注解驱动,使得Spring的注解可以使用-->
<mvc:annotation-driven/>
<!--配置MessageSource,消息源,存储properties-->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/msg" />
</bean>
</beans>
4,创建数据库
create table shows(
id int primary key auto_increment,
name varchar(100) not null,
author varchar(50) not null,
publish varchar(100) not null,
price double not null);
5,创建show.jsp updata.jsp add.jsp err.jsp
使用bootstop框架,jstl,web的http://www.springframework.org/tags/form
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/3/4
Time: 21:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page errorPage="err.jsp" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>welcome</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<table class="table">
<tr>
<td><a href="/add">add</a></td>
</tr>
<tr>
<td>id</td>
<td>name</td>
<td>author</td>
<td>publish</td>
<td>price</td>
<td>manage</td>
</tr>
<c:forEach items="${showlist}" var="s">
<tr>
<td> ${s.id}</td>
<td> ${s.name}</td>
<td> ${s.author}</td>
<td> ${s.publish}</td>
<td> ${s.price}</td>
<td> <a href="/show/showDelete/${s.id}">delete</a> <a href="/show/showSelectOne/${s.id}">updata</a></td>
</tr>
</c:forEach>
</table>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/3/4
Time: 21:16
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="err.jsp" %>
<html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="f" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>welcome</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<f:form method="post" action="/show/showUpdate" commandName="show">
id:<f:input path="id" readonly="true"/><font color="red"><f:errors path="id" /></font> <br>
name:<f:input path="name" /><f:errors path="name" /><br>
author:<f:input path="author" /><f:errors path="author" /><br>
publish:<f:input path="publish" /><f:errors path="publish" /><br>
price:<f:input path="price" /><f:errors path="price" /><br>
<input type="submit" value="submit" /> <br>
</f:form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/3/8
Time: 10:12
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page errorPage="err.jsp" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>welcome</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<form role="form" method="post" action="/show/showInsert">
<div class="form-group">
<label for="name">书名</label>
<input type="text" class="form-control" id="name" placeholder="name" name="name">
</div>
<div class="form-group">
<label for="name">作者</label>
<input type="text" class="form-control" placeholder="name" name="author">
</div>
<div class="form-group">
<label for="name">出版社</label>
<input type="text" class="form-control" placeholder="name" name="publish">
</div>
<div class="form-group">
<label for="name">价格</label>
<input type="text" class="form-control" placeholder="name" name="price">
</div>
<button type="submit" class="btn btn-default">提交</button>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/3/8
Time: 9:58
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page errorPage="err.jsp" isErrorPage="true" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>sorry i can not</h1>
</body>
</html>
6,创建bean下的Show
与数据库中字段相同
package com.star.bean;
/**
* Created by Administrator on 2020/3/4.
*/
public class Show {
private int id;
private String name;
private String author;
private String publish;
private double price;
public Show() {
}
public Show(int id, String name, String author, String publish, double price) {
this.id = id;
this.name = name;
this.author = author;
this.publish = publish;
this.price = price;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPublish() {
return publish;
}
public void setPublish(String publish) {
this.publish = publish;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
7,创建PathController
访问通配,不写比较好。
package com.star.controller;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.nio.file.Path;
/**
* Created by Administrator on 2020/3/4.
*/
@Component //代表当前为控制器组件
public class PathController {
@RequestMapping("/{path}")//获取任何的地址请求
public String goPath(@PathVariable String path){//将当前路径的最后一部分路径作为参数取值
return path;
}
}
8.创建ShowController
实现对show的操作控制
package com.star.controller;
import com.star.bean.Show;
import com.star.server.ShowServer;
import com.star.server.impl.ShowServerImpl;
import com.star.validate.ShowValidate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* Created by Administrator on 2020/3/4.
*/
@Controller
@RequestMapping("/show")
public class ShowController {
@RequestMapping("/showInsert")
public String showInsert(Show show) {
ShowServer ss = new ShowServerImpl();
int res = ss.insert(show);
if (res > 0)
return "redirect:/show/showSelect";
else
return "err.jsp";
}
@RequestMapping("/showSelect")
public String showSelect(Model model) {
ShowServer ss = new ShowServerImpl();
List<Show> list = ss.select();
model.addAttribute("showlist", list);
return "show.jsp";
}
@RequestMapping("/showSelectOne/{id}")
public String showSelectOne(@PathVariable int id, Model model) {
ShowServer ss = new ShowServerImpl();
Show show = ss.selectOne(id);
model.addAttribute("show", show);
return "update.jsp";
}
@RequestMapping("/showUpdate")
public String showUpdate(Show show, BindingResult err,Model model){
ShowValidate sv = new ShowValidate();
sv.validate(show,err);
if (err.hasErrors()){
model.addAttribute("show",show);
return "update.jsp";
}
ShowServer ss = new ShowServerImpl();
int a = ss.update(show);
if (a > 0) {
return "redirect:/show/showSelect";
} else
return "err.jsp";
}
@RequestMapping("/showDelete/{id}")
public String showDelete(@PathVariable int id) {
ShowServer ss = new ShowServerImpl();
int res = ss.delete(id);
if (res > 0)
return "redirect:/show/showSelect";
else
return "err.jsp";
}
}
9,创建servlet,servletimpl
package com.star.server;
import com.star.bean.Show;
import java.util.List;
/**
* Created by Administrator on 2020/3/4.
*/
public interface ShowServer {
Show selectOne(int id);
List<Show> select();
int insert(Show s);
int delete(int id);
int update(Show s);
}
package com.star.server.impl;
import com.star.bean.Show;
import com.star.dao.ShowDao;
import com.star.dao.impl.ShowDaoImpl;
import com.star.server.ShowServer;
import java.util.List;
/**
* Created by Administrator on 2020/3/4.
*/
public class ShowServerImpl implements ShowServer {
@Override
public Show selectOne(int id) {
ShowDao sd= new ShowDaoImpl();
return sd.selectOne(id);
}
@Override
public List<Show> select() {
ShowDao sd = new ShowDaoImpl();
List<Show> list = sd.select();
return list;
}
@Override
public int insert(Show s) {
ShowDao sd = new ShowDaoImpl();
return sd.insert(s);
}
@Override
public int delete(int id) {
ShowDao sd = new ShowDaoImpl();
return sd.delete(id);
}
@Override
public int update(Show s) {
ShowDao sd = new ShowDaoImpl();
return sd.update(s);
}
}
11,创建dbtools
连接数据库的工具类
package com.star.util;
import java.sql.*;
/**
* Created by Administrator on 2020/3/4.
*/
public class DBtools {
public static Connection getConn(){
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://localhost:3306/star","root","123456");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn, ResultSet result, PreparedStatement state){
try {
if (result != null) {
result.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (state != null) {
state.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
10.创建dao,daoimpl
连接数据库
package com.star.dao;
import com.star.bean.Show;
import java.util.List;
/**
* Created by Administrator on 2020/3/4.
*/
public interface ShowDao {
Show selectOne(int id);
List<Show> select();
int insert(Show s);
int delete(int id);
int update(Show s);
}
package com.star.dao.impl;
import com.star.bean.Show;
import com.star.dao.ShowDao;
import com.star.util.DBtools;
import com.sun.org.apache.xpath.internal.WhitespaceStrippingElementMatcher;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2020/3/4.
*/
public class ShowDaoImpl implements ShowDao {
private Connection conn;
private PreparedStatement ps;
private ResultSet rs;
@Override
public Show selectOne(int id) {
conn = DBtools.getConn();
try {
ps = conn.prepareStatement("select id, name, author, publish, price from shows where id =?");
ps.setInt(1,id);
rs = ps.executeQuery();
if (rs.next()){
return new Show(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getDouble(5));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBtools.close(conn,rs,ps);
}
return null;
}
@Override
public List<Show> select() {
List<Show> list = new ArrayList<>();
conn = DBtools.getConn();
try {
ps = conn.prepareStatement("select id, name, author, publish, price from shows");
rs = ps.executeQuery();
while (rs.next()){
list.add(new Show(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getString(4),rs.getDouble(5)));
}
return list;
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBtools.close(conn,rs,ps);
}
return null;
}
@Override
public int insert(Show s) {
conn = DBtools.getConn();
try {
ps = conn.prepareStatement("insert into shows values(null, ?, ?, ?, ?)");
ps.setString(1,s.getName());
ps.setString(2,s.getAuthor());
ps.setString(3,s.getPublish());
ps.setDouble(4,s.getPrice());
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBtools.close(conn,rs,ps);
}
return 0;
}
@Override
public int delete(int id) {
conn = DBtools.getConn();
try {
ps = conn.prepareStatement("delete from shows where id=?");
ps.setInt(1,id);
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBtools.close(conn,rs,ps);
}
return 0;
}
@Override
public int update(Show s) {
conn = DBtools.getConn();
try {
ps = conn.prepareStatement("UPDATE shows set name=?,author=?,publish=?,price=? where id=?");
ps.setString(1,s.getName());
ps.setString(2,s.getAuthor());
ps.setString(3,s.getPublish());
ps.setDouble(4,s.getPrice());
ps.setInt(5,s.getId());
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBtools.close(conn,rs,ps);
}
return 0;
}
}
11,创建validate校验数据
package com.star.validate;
import com.star.bean.Show;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
/**
* Created by Administrator on 2020/3/4.
*/
public class ShowValidate implements Validator {
//判断当前类型是否为校验类型
@Override
public boolean supports(Class<?> clazz) {
return Show.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
Show s = (Show) target;
ValidationUtils.rejectIfEmpty(errors, "id", "show.id");
ValidationUtils.rejectIfEmpty(errors, "name", "show.name");
ValidationUtils.rejectIfEmpty(errors, "author", "show.author");
ValidationUtils.rejectIfEmpty(errors, "publish", "show.publish");
ValidationUtils.rejectIfEmpty(errors, "price", "show.price");
}
}
12.创建国际化的文件
show.id=this is not null
show.name=this is not null
show.author=this is not null
show.publish=this is not null
show.price=this is not null
13,项目结构
来源:CSDN
作者:bloody box
链接:https://blog.csdn.net/weixin_44047709/article/details/104737593