我的代码展示
创建一个动态项目新建项目:File-New,选择Dynamic web project,并取项目名称SpringMvc2
和我一样是小白的可以先照着把所有的包和文件都创建起来
index.html可以不用写【没用】
1.导入包
包的文件链接:https://pan.baidu.com/s/1OIfHmlvocoONvzCSZZhZPw
提取码:y5u4
复制这段内容后打开百度网盘手机App,操作更方便哦
2.最好先写web.xml
代码如下:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SpringMVC2</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- 配置springmvc分发器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置Spring mvc下的配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
<!-- <url-pattern>/</url-pattern> -->
</servlet-mapping>
<!-- 这里的servlet-mapping表示拦截的模式,这里如果是“/”,
表示对于所有的请求的拦截,包括静态资源如html, js, jpg等。
这时候对于静态资源的访问就会报404的错误。 -->
</web-app>
springmvc-config.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 自动扫描注解所在的包 -->
<!-- spring监听的范围,这里是在com.ddb.springmvc下 -->
<context:component-scan base-package="com.ddb.springmvc.controller"></context:component-scan>
<context:component-scan base-package="com.ddb.springmvc.service.*"></context:component-scan>
<!-- mvc:resources元素指示springmvc哪些静态资源需要单独处理
(不经过dispatcher servlet)如果没有<mvc:annotation-driven> <mvc:resources
元素会阻止任意控制器被调用,若不需要使用resource则不需要<mvc:annotation-driven>
-->
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:resources location="/" mapping="/*.html"></mvc:resources>
<!-- 配置springmvc的视图解析器
视图解析器自动增加前缀和后缀 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value="/WEB-INF/jsp/"></property>
<property name = "suffix" value = ".jsp"></property>
</bean>
</beans>
prefix表示前缀【在jstl中核心标签库出现过】 suffix后缀
product.java
package com.ddb.springmvc.domain;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class Product {
private Long id;
private String name;
private String description;
private Double price;
}
ProductForm.java
package com.ddb.springmvc.form;
import lombok.Getter;
import lombok.Setter;
@Setter
@Getter
public class ProductForm {
private String name;
private String description;
private String price;
}
ProductService.java
package com.ddb.springmvc.service;
import com.ddb.springmvc.domain.Product;
public interface ProductService {
Product add(Product product);
Product get(long id);
}
ProductServiceImpl.java
package com.ddb.springmvc.service.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import com.ddb.springmvc.domain.Product;
import com.ddb.springmvc.service.ProductService;
@Service
public class ProductServiceImpl implements ProductService {
private Map<Long, Product> products=new HashMap<Long, Product>();
//模数据库的保存与获取
private AtomicLong generator=new AtomicLong();
public ProductServiceImpl() {
Product product=new Product();
product.setName("pencial");
product.setDescription("huahua good");
product.setPrice(400.0d);
add(product);
}
@Override
public Product add(Product product) {
// TODO Auto-generated method stub
long newid=generator.incrementAndGet();
product.setId(newid);
//保存到MAP中,此步模拟数据保存到数据库
products.put(newid, product);
return product;
}
@Override
public Product get(long id) {
// TODO Auto-generated method stub
return products.get(id);
}
}
@service 不要忘记了!!!!
ProductController.java
package com.ddb.springmvc.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.ddb.springmvc.domain.Product;
import com.ddb.springmvc.form.ProductForm;
import com.ddb.springmvc.service.ProductService;
@Controller
public class ProductController {
private static final Logger logger=Logger.getLogger(ProductController.class);
//自动注入向后端数据库写数据的组件
@Autowired
private ProductService productService;
@RequestMapping(value = "/product_input")
private String inputProduct() {
logger.info("inputProduct被调用!");
return "ProductForm";
}
@RequestMapping(value = "/product_save",method =RequestMethod.POST)
private String saveProduct(ProductForm productForm,RedirectAttributes redirectAttributes) {
logger.info("saveProduct被调用!");
Product product=new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try {
product.setPrice(Double.parseDouble(productForm.getPrice()));
}catch(Exception e) {
e.printStackTrace();
}
//add product
Product saveProduct=productService.add(product);
redirectAttributes.addFlashAttribute("message","The product was successfully added!");
return "redirect:/product_view/"+saveProduct.getId()+".action";
}
@RequestMapping(value="/product_view/{id}")
public String viewProduct(@PathVariable Long id,Model model) {
Product product =productService.get(id);
model.addAttribute("product",product);
return "ProductView";
}
@RequestMapping(value="/product_retrieve")
public String sendProduct(@PathVariable Long id,Model model) {
Product product =productService.get(id);
model.addAttribute("product",product);
return "ProductView";
}
}
ProductForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div>
<form action="product_save.action" method="post">
<fieldset>
<legend>Add a product</legend>
<label for="name">Product Name:</label>
<input type="text" id="name" name="name"value="" tabindex="1"/>
<label for="description">Description:</label>
<input type="text" id="description" name="description" value="" tabindex="2"/>
<label for="price">Price:</label>
<input type="text" id="price" name="price" value="" tabindex="3"/>
<div id="buttons">
<label for="dummy"></label>
<input id="reset" type="reset" tabindex="4"/>
<input id="submit" type="submit" tabindex="5" value="Add Product"/>
</div>
</fieldset>
</form>
</div>
</body>
</html>
ProductView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<div id="global">
<h4>The product has been saved</h4>
<h5>Details:</h5>
Tips:${message} <br/>
Product ID:${product.id}<br/>
Product Name:${product.name}<br/>
Description:${product.description}<br/>
Price:¥${product.price}<br/>
</div>
</body>
</html>
运行在项目右击 run as
地址栏中输入 如下👇
/项目名称后/product_input.action
输入中文会出现乱码问题
解决方式有两种:我是直接在web.xml中增加过滤器
↓↓↓
web.xml
<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>
等等方法可以百度搜索over
还有如果不想在地址栏输入product_input.action 可以在web.xml中
<welcome-file-list>
<welcome-file>product_input.action</welcome-file>
</welcome-file-list>
会遇到的问题有:
1、tomcat服务器的添加
从前面的介绍可以看出,我们的程序是通过浏览器发请求来获取想要的页面,那么这里就免不了要有一个web服务器,这里就是tomcat。
首先你需要下载个tomcat,然后在eclipse->windows->preference->servers中绑定这个tomcat服务器;
其次你需要在你新建的spring mvc项目中添加tomcat的支持,否则在新建的jsp文件中会提示报错“The superclass javax.servlet.http.HttpServlet was not found on the Java Build Path”
右键项目->build path->configure build path->add library->server runtime, 选择你的tomcat即可
2、spring mvc如何访问静态资源
关于使用spring mvc处理静态资源,比如html(发现之前的springmvc.xml中定义为jsp结尾就可以成功跳转,但是如果改为html并在web-inf下面新建了html文件后,并将suffix这里的”.jsp”改为”.html”,无法跳转到想要的html页面,并且给出404错误,同时console给出错误信息为:No mapping found for HTTP request with URI [/springTest/WEB-INF/views/result.html] in DispatcherServ)
最后发现是需要让spring明确要处理静态资源,原来的web.xml中只有
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
其匹配的都是controller中类似@RequestMapping(“/springmvc/helloworld”)这样的注解配置的请求,而对于类似html/css/jpg等资源的访问就会得不到,所以需要在web.xml中加入以下类型的支持
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</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>*.png</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>*.html</url-pattern>
</servlet-mapping>
web.xml中
property name = “suffix” value = “.png” value更改为png就可以访问图片资源了
这样就可以保证spring 能够拦截并处理静态资源了。