入门案例
配置web.xml,需要配置一个核心控制器(servlet)
< servlet>
< servlet-name> springmvc</ 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>
</ servlet>
< servlet-mapping>
< servlet-name> springmvc</ servlet-name>
< url-pattern> *.do</ url-pattern>
</ servlet-mapping>
配置springmvc.xml,配置处理器映射器(HandlerMapping)、处理器适配器(HandlerAdapter)、自定义controller以及视图解析器(ViewResolver)
<?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"
xmlns: aop= " http://www.springframework.org/schema/aop" xmlns: tx= " http://www.springframework.org/schema/tx"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" >
< bean class = " org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" > </ bean>
< bean class = " org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
< property name = " mappings" >
< props>
< prop key = " /abc.do" > myController</ prop>
< prop key = " /ss.do" > http</ prop>
< prop key = " /mine.do" > https</ prop>
</ props>
</ property>
</ bean>
< bean class = " org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" > </ bean>
< bean class = " org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" > </ bean>
< bean class = " org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" > </ bean>
< bean id = " myController" name = " /hello.do" class = " cn.itcast.controller.MyController" > </ bean>
< bean id = " http" class = " controller.HttpController" > </ bean>
< bean name = " /command.do" class = " controller.CommandController" > </ bean>
< bean name = " /toAdd.do" class = " controller.ToAddController" > </ bean>
< bean class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/jsps/" > </ property>
< property name = " suffix" value = " .jsp" > </ property>
</ bean>
</ beans>
package controller;
import javax. servlet. http. HttpServletRequest;
import javax. servlet. http. HttpServletResponse;
import org. springframework. web. servlet. ModelAndView;
import org. springframework. web. servlet. mvc. Controller;
public class MyController implements Controller {
public ModelAndView handleRequest ( HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
ModelAndView mv = new ModelAndView ( ) ;
mv. addObject ( "hello" , "欢迎学习springmvc!" ) ;
mv. setViewName ( "index" ) ;
return mv;
}
}
请求乱码
< filter>
< filter-name> characterEncoding</ 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> characterEncoding</ filter-name>
< url-pattern> /*</ url-pattern>
</ filter-mapping>
基于注解开发
web.xml没有什么改变 springmvc的配置如下:
<?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"
xmlns: aop= " http://www.springframework.org/schema/aop" xmlns: tx= " http://www.springframework.org/schema/tx"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" >
< context: component-scan base-package = " controller" > </ context: component-scan>
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" > </ bean>
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > </ bean>
< bean class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/jsps/" > </ property>
< property name = " suffix" value = " .jsp" > </ property>
</ bean>
</ beans>
@Controller
@RequestMapping ( "/user" )
public class UserController {
@RequestMapping ( value= "/hello.do" )
public String hello ( ) {
return "index" ;
}
}
RequestMapping注解分为两种,一种是标注在controller类之上,一种是标注在方法之上。
标注在controller类之上的RequestMapping标注,其参数表示访问url的根路径 标注在controller类中方法之上的RequestMapping标注,其参数表示访问url的子路径
封装参数
参数封装是指将页面中的数据传到controller中 根据传输参数类型的不同,可以分为以下几种类型
基本参数
<form action="${pageContext.request.contextPath }/user/recieveInt.do" method="post">
ID:<input type="text" name="id" id="id">
<input type="submit" value="提交">
</form>
<hr size="12" color="blue"/>
<form action="${pageContext.request.contextPath }/user/recieveStr.do" method="post">
姓名:<input type="text" name="username" id="username">
<input type="submit" value="提交">
</form>
//接受int类型参数
@RequestMapping("recieveInt")
public String recieveInt(Integer id){
System.out.println(id);
return "success";
}
//接受字符类型参数
@RequestMapping("recieveStr")
public String recieveStr(String username)
{
System.out.println(username);
return "success";
}
数组
<form action="${pageContext.request.contextPath }/user/recieveArray.do" method="post">
ID:<input type="checkbox" name="ids" value="1" id="ids">
ID:<input type="checkbox" name="ids" value="2" id="ids">
ID:<input type="checkbox" name="ids" value="3" id="ids">
<input type="submit" value="提交">
</form>
//接受数组类型参数
@RequestMapping("recieveArray")
public String recieveArray(Integer[] ids){
System.out.println(ids);
return "success";
}
JavaBean对象
<form action="${pageContext.request.contextPath }/user/recieveUser.do" method="post">
姓名:<input type="text" name="username" id="username">
生日:<input type="text" name="birthday" id="birthday">
性别:<input type="text" name="sex" id="sex">
地址:<input type="text" name="address" id="address">
<input type="submit" value="提交">
</form>
//接受参数封装User对象
@RequestMapping("recieveUser")
public String recieveUser(User user){
System.out.println(user);
return "success";
}
package domain;
import java. util. Date;
public class User {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public Integer getId ( ) {
return id;
}
public void setId ( Integer id) {
this . id = id;
}
public String getUsername ( ) {
return username;
}
public void setUsername ( String username) {
this . username = username;
}
public Date getBirthday ( ) {
return birthday;
}
public void setBirthday ( Date birthday) {
this . birthday = birthday;
}
public String getSex ( ) {
return sex;
}
public void setSex ( String sex) {
this . sex = sex;
}
public String getAddress ( ) {
return address;
}
public void setAddress ( String address) {
this . address = address;
}
}
包装类型参数
<form action="${pageContext.request.contextPath }/user/recieveUserCustom.do" method="post">
姓名:<input type="text" name="user.username" id="username">
生日:<input type="text" name="user.birthday" id="birthday">
性别:<input type="text" name="user.sex" id="sex">
地址:<input type="text" name="user.address" id="address">
<input type="submit" value="提交">
</form>
//接受包装类型参数
@RequestMapping("recieveUserCustom")
public String recieveUserCustom(UserCustom userCustom){
System.out.println(userCustom);
return "success";
}
package domain;
import java. util. HashMap;
import java. util. List;
import java. util. Map;
public class UserCustom {
private User user;
private List< User> userList;
private Map< String, Object> maps = new HashMap < String, Object> ( ) ;
public Map< String, Object> getMaps ( ) {
return maps;
}
public void setMaps ( Map< String, Object> maps) {
this . maps = maps;
}
public User getUser ( ) {
return user;
}
public void setUser ( User user) {
this . user = user;
}
public List< User> getUserList ( ) {
return userList;
}
public void setUserList ( List< User> userList) {
this . userList = userList;
}
}
集合类型参数(list)
<form action="${pageContext.request.contextPath }/user/recieveList.do" method="post">
姓名:<input type="text" name="userList[0].username" id="username">
地址:<input type="text" name="userList[0].address" id="address">
姓名:<input type="text" name="userList[1].username" id="username">
地址:<input type="text" name="userList[1].address" id="address">
<input type="submit" value="提交">
</form>
//接受集合类型参数
@RequestMapping("recieveList")
public String recieveList(UserCustom userCustom){
System.out.println(userCustom);
return "success";
}
集合类型参数(map)
<form action="${pageContext.request.contextPath }/user/recieveMap.do" method="post">
姓名:<input type="text" name="maps['username']" id="username">
地址:<input type="text" name="maps['address']" id="address">
<input type="submit" value="提交">
</form>
//接受集合类型参数
@RequestMapping("recieveMap")
public String recieveMap(UserCustom userCustom){
System.out.println(userCustom);
return "success";
}
页面回显
@RequestMapping ( "list" )
public String list ( Model model) {
List< User> userList = new ArrayList < User> ( ) ;
User user1 = new User ( ) ;
user1. setId ( 1 ) ;
user1. setSex ( "男" ) ;
user1. setUsername ( "张山峰" ) ;
user1. setAddress ( "武当山" ) ;
user1. setBirthday ( new Date ( ) ) ;
User user2 = new User ( ) ;
user2. setId ( 2 ) ;
user2. setSex ( "男2" ) ;
user2. setUsername ( "张山峰222" ) ;
user2. setAddress ( "武当山222" ) ;
user2. setBirthday ( new Date ( ) ) ;
User user3 = new User ( ) ;
user3. setId ( 3 ) ;
user3. setSex ( "男3" ) ;
user3. setUsername ( "张山峰333" ) ;
user3. setAddress ( "武当山333" ) ;
user3. setBirthday ( new Date ( ) ) ;
userList. add ( user1) ;
userList. add ( user2) ;
userList. add ( user3) ;
model. addAttribute ( "userList" , userList) ;
return "list" ;
}
<body>
<table border="1" style="color: blue">
<tr>
<td>姓名</td>
<td>生日</td>
<td>性别</td>
<td>地址</td>
<td>操作</td>
</tr>
<c:forEach items="${userList }" var="user">
<tr>
<td>${user.username }</td>
<td>${user.birthday }</td>
<td>${user.sex }</td>
<td>${user.address }</td>
</tr>
</c:forEach>
</table>
</body>
转发和重定向
@RequestMapping ( "forward" )
public String forward ( ) {
return "forward:/items/list.do" ;
}
@RequestMapping ( "redirect" )
public String redirect ( ) {
return "redirect:/items/list.do" ;
}
@ResponseBody和@RequestBody注解
@ResponseBody把后台pojo转换json对象,返回到页面。 @RequestBody接受前台json数据,把json数据自动封装javaBean。 要使用这两个注解需要导入jackson相关的两个jar包:jackson-core-asl
和jackson-mapper-asl
需要在HandlerAdapter中注入一个messageConverters参数
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
< property name = " messageConverters" >
< bean class = " org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" > </ bean>
</ property>
</ bean>
也可以在springmvc.xml中通过添加<mvc:annotation-driven/>
来代替HandlerMapping和HandlerAdapter这两个配置。 annotation-driven:默认创建了多个对象:RequestMappingHandlerMapping,RequestMappingHandlerAdapter。也提供对json格式支持,即在HandlerAdapter中默认注入了messageConverters参数。 Ajax传递json数据
< script type = " text/javascript" src = " ${pageContext.request.contextPath}/js/jquery.js" > </ script>
< script type = " text/javascript" >
function requestJson ( ) {
var jsonObj = JSON . stringify ( { "username" : "东哥" , "address" : "宝山" } )
$. ajax ( {
type: "post" ,
url: "${pageContext.request.contextPath}/user/requestJson.do" ,
contentType: 'application/json;charset=utf-8' ,
data: jsonObj,
sucess: function ( data) {
alert ( data. username) ;
}
} )
}
</ script>
@RequestMapping ( "requestJson" )
public @ResponseBody User requestJson ( @RequestBody User user) {
System. out. println ( user) ;
return user;
}
多视图解析
< servlet-mapping>
< servlet-name> springmvc</ servlet-name>
< url-pattern> /rest/*</ url-pattern>
</ servlet-mapping>
<?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"
xmlns: aop= " http://www.springframework.org/schema/aop" xmlns: tx= " http://www.springframework.org/schema/tx"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" >
< context: component-scan base-package = " com.gaishi_hero" > </ context: component-scan>
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" > </ bean>
< bean class = " org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" > </ bean>
< bean id = " viewResolver"
class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/jsps/" > </ property>
< property name = " suffix" value = " .jsp" > </ property>
</ bean>
< bean
class = " org.springframework.web.servlet.view.ContentNegotiatingViewResolver" >
< property name = " order" value = " 1" > </ property>
< property name = " contentNegotiationManager" >
< bean
class = " org.springframework.web.accept.ContentNegotiationManagerFactoryBean" >
< property name = " mediaTypes" >
< map>
< entry key = " json" value = " application/json" > </ entry>
< entry key = " xml" value = " application/xml" > </ entry>
</ map>
</ property>
</ bean>
</ property>
< property name = " defaultViews" >
< list>
< bean class = " org.springframework.web.servlet.view.json.MappingJacksonJsonView" > </ bean>
< bean class = " org.springframework.web.servlet.view.xml.MarshallingView" >
< constructor-arg>
< bean class = " org.springframework.oxm.jaxb.Jaxb2Marshaller" >
< property name = " classesToBeBound" >
< list>
< value> com.gaishi_hero.domain.Person</ value>
</ list>
</ property>
</ bean>
</ constructor-arg>
</ bean>
</ list>
</ property>
</ bean>
</ beans>
@Controller
@ResquestMapping ( "view" )
public class MyController {
@RequestMapping ( "view" )
public String getPerson ( Model model) {
Person person = new Person ( ) ;
person. setName ( "东哥" ) ;
person. setAddress ( "宝山" ) ;
model. addAttribute ( "person" , person)
return person;
}
}
此时在地址栏中输入项目地址/rest/view/view.xml
就会得到xml形式的返回结果;当输入项目地址/rest/view/view.json
时,就会得到json形式的返回结果。 要想实现将pojo对象转为xml内容,还需要在Person类的前面加上注解@XmlRootElement
ssm整合
< filter>
< filter-name> characterEncoding</ 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> characterEncoding</ filter-name>
< url-pattern> /*</ url-pattern>
</ filter-mapping>
< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener</ listener-class>
</ listener>
< context-param>
< param-name> contextConfigLocation</ param-name>
< param-value> classpath:beans.xml</ param-value>
</ context-param>
< servlet>
< servlet-name> springmvc</ 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>
</ servlet>
< servlet-mapping>
< servlet-name> springmvc</ servlet-name>
< url-pattern> *.do</ url-pattern>
</ servlet-mapping>
< servlet-mapping>
< servlet-name> springmvc</ servlet-name>
< url-pattern> /rest/*</ url-pattern>
</ servlet-mapping>
<?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"
xmlns: aop= " http://www.springframework.org/schema/aop" xmlns: tx= " http://www.springframework.org/schema/tx"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" >
< context: component-scan base-package = " com.gaishi_hero" > </ context: component-scan>
< context: property-placeholder location = " classpath:jdbc.properties" />
< bean id = " dataSource" class = " com.mchange.v2.c3p0.ComboPooledDataSource" >
< 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>
< bean id = " sqlSessionFactory" class = " org.mybatis.spring.SqlSessionFactoryBean" >
< property name = " dataSource" ref = " dataSource" > </ property>
< property name = " configLocation" value = " classpath:sqlMapConfig.xml" > </ property>
</ bean>
< bean class = " org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name = " basePackage" value = " com.gaishi_hero.dao" > </ property>
< property name = " sqlSessionFactoryBeanName" value = " sqlSessionFactory" > </ property>
</ bean>
< bean id = " transactionManager" class = " org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name = " dataSource" ref = " dataSource" > </ property>
</ bean>
< tx: advice id = " txAdvice" transaction-manager = " transactionManager" >
< tx: attributes>
< tx: method name = " save*" propagation = " REQUIRED" />
< tx: method name = " update*" propagation = " REQUIRED" />
< tx: method name = " delete*" propagation = " REQUIRED" />
< tx: method name = " insert*" propagation = " REQUIRED" />
< tx: method name = " *" propagation = " REQUIRED" />
</ tx: attributes>
</ tx: advice>
< aop: config>
< aop: advisor advice-ref = " txAdvice" pointcut = " execution(* com.gaishi_hero.service.*.*(..))" />
</ aop: config>
</ beans>
<?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>
< !—使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers -- >
< mappers>
< package name = " com.gaishi_hero.dao" />
</ mappers>
</ configuration>
springmvc配置文件springmvc.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"
xmlns: aop= " http://www.springframework.org/schema/aop" xmlns: tx= " http://www.springframework.org/schema/tx"
xsi: schemaLocation= " http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd" >
< context: component-scan base-package = " com.gaishi_hero" > </ context: component-scan>
< mvc: annotation-driven/>
< bean
class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< property name = " prefix" value = " /WEB-INF/jsps/" > </ property>
< property name = " suffix" value = " .jsp" > </ property>
</ bean>
</ beans>
package com. gaishi_hero. controller;
import java. util. List;
import javax. annotation. Resource;
import org. springframework. stereotype. Controller;
import org. springframework. ui. Model;
import org. springframework. web. bind. annotation. RequestMapping;
import com. gaishi_hero. domain. Items;
import com. gaishi_hero. service. ItemsService;
@Controller
@RequestMapping ( "/items" )
public class ItemsController {
@Resource
private ItemsService itemsService;
@RequestMapping ( "list" )
public String list ( Model model) {
List< Items> list = itemsService. findAll ( ) ;
model. addAttribute ( "itemsList" , list) ;
return "itemsList" ;
}
@RequestMapping ( "edit" )
public String edit ( Integer id , Model model) {
Items items = itemsService. findByID ( id) ;
model. addAttribute ( "item" , items) ;
return "editItem" ;
}
@RequestMapping ( "saveOrUpdate" )
public String saveOrUpdate ( Items items) {
itemsService. saveOrUpdate ( items) ;
return "redirect:list.do" ;
}
@RequestMapping ( "deleteByID" )
public String deleteByID ( Integer id)
{
itemsService. deleteByID ( id) ;
return "redirect: list.do" ;
}
@RequestMapping ( "deleteByIds" )
public String deleteByIds ( Integer[ ] id) {
for ( Integer ids : id) {
itemsService. deleteByID ( ids) ;
}
return "redirect: list.do" ;
}
}
package com. gaishi_hero. service. impl;
import java. util. List;
import javax. annotation. Resource;
import org. springframework. stereotype. Service;
import com. gaishi_hero. dao. ItemsMapper;
import com. gaishi_hero. domain. Items;
import com. gaishi_hero. service. ItemsService;
@Service
public class ItemsServiceImpl implements ItemsService {
@Resource
private ItemsMapper itemsMapper;
public List< Items> findAll ( ) {
List< Items> list = itemsMapper. findAll ( ) ;
return list;
}
public Items findByID ( Integer id) {
Items items = itemsMapper. selectByPrimaryKey ( id) ;
return items;
}
public void saveOrUpdate ( Items items) {
itemsMapper. updateByPrimaryKey ( items) ;
}
public void deleteByID ( Integer id) {
itemsMapper. deleteByPrimaryKey ( id) ;
}
}
mapper Java代码和xml代码都是用逆向工程生成出来
文件上传
需求:使用ajax异步上传图片,并将上传图片实时显示出来。且上传图片的位置时另外的一台服务器。 需要导入的jar包包括com.springsource.org.apache.commons.fileupload
,commons-io
,jersey-client
,jersey-core
。后面两个jar包专门用来实现跨服务器上传。 首先在springmvc.xml中进行配置
< bean id = " multipartResolver" class = " org.springframework.web.multipart.commons.CommonsMultipartResolver" >
< property name = " maxUploadSize" value = " 10240000" > </ property>
</ bean>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
< c: set var = " picPath" value = " http://127.0.0.1:8003/ssmImage19" > </ c: set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
< html>
< head>
< meta http-equiv = " Content-Type" content = " text/html; charset=UTF-8" >
< title> 修改商品信息</ title>
< script type = " text/javascript" src = " ${pageContext.request.contextPath }/js/jquery.js" > </ script>
< script type = " text/javascript" src = " ${pageContext.request.contextPath }/js/jquery.form.js" > </ script>
< script type = " text/javascript" >
function submitImgSize1Upload ( ) {
var option = {
type: 'POST' ,
url: '${pageContext.request.contextPath }/upload/uploadPic.do' ,
dataType: 'text' ,
data: {
fileName: 'imgSize1File'
} ,
success: function ( data) {
var jsonObj = $. parseJSON ( data) ;
$ ( "#imgSize1ImgSrc" ) . attr ( "src" , jsonObj. fullPath) ;
$ ( "#imgSize1" ) . val ( jsonObj. relativePath) ;
}
} ;
$ ( "#itemForm" ) . ajaxSubmit ( option) ;
}
</ script>
</ head>
< body>
< form id = " itemForm" action = " ${pageContext.request.contextPath }/items/saveOrUpdate.do" method = " post" >
< input type = " hidden" name = " id" value = " ${item.id }" />
修改商品信息:
< table width = " 100%" border = 1>
< tr>
< td> 商品名称</ td>
< td> < input type = " text" name = " name" value = " ${item.name }" /> </ td>
</ tr>
< tr>
< td> 商品价格</ td>
< td> < input type = " text" name = " price" value = " ${item.price }" /> </ td>
</ tr>
< tr>
< td> 商品生产日期</ td>
< td> <input type="text" name="createtime"
value="< fmt: formatDate value = " ${item.createtime}" pattern = " yyyy-MM-dd HH:mm:ss" /> "/></ td>
</ tr>
< tr>
< td> 商品图片</ td>
< td>
< p> < label> </ label>
< img id = ' imgSize1ImgSrc' src = ' ${picPath }${item.pic }' height = " 100" width = " 100" />
< input type = ' file' id = ' imgSize1File' name = ' imgSize1File' class = " file"
onchange = ' submitImgSize1Upload()' /> < span class = " pos"
id = " imgSize1FileSpan" > 请上传图片的大小不超过3MB</ span>
< input type = ' hidden' id = ' imgSize1' name = ' pic' value = ' ' reg = " ^.+$" tip = " 亲!您忘记上传图片了。" />
</ p>
</ td>
</ tr>
< tr>
< td> 商品简介</ td>
< td>
< textarea rows = " 3" cols = " 30" name = " detail" > ${item.detail }</ textarea>
</ td>
</ tr>
< tr>
< td colspan = " 2" align = " center" > < input type = " submit" value = " 提交" />
</ td>
</ tr>
</ table>
</ form>
</ body>
</ html>
package com. gaishi_hero. controller;
import java. io. PrintWriter;
import java. text. SimpleDateFormat;
import java. util. Date;
import java. util. Random;
import javax. servlet. http. HttpServletRequest;
import org. springframework. stereotype. Controller;
import org. springframework. web. bind. annotation. RequestMapping;
import org. springframework. web. multipart. MultipartHttpServletRequest;
import org. springframework. web. multipart. commons. CommonsMultipartFile;
import com. gaishi_hero. utils. Commons;
import com. sun. jersey. api. client. Client;
import com. sun. jersey. api. client. WebResource;
@Controller
@RequestMapping ( "/upload" )
public class UploadController {
@RequestMapping ( "uploadPic" )
public void uploadPic ( HttpServletRequest request, String fileName, PrintWriter out) {
MultipartHttpServletRequest mh = ( MultipartHttpServletRequest) request;
CommonsMultipartFile cm = ( CommonsMultipartFile) mh. getFile ( fileName) ;
byte [ ] fbytes = cm. getBytes ( ) ;
String newFileName= "" ;
SimpleDateFormat sdf = new SimpleDateFormat ( "yyyyMMddHHmmssSSS" ) ;
newFileName = sdf. format ( new Date ( ) ) ;
Random r = new Random ( ) ;
for ( int i = 0 ; i< 3 ; i++ ) {
newFileName= newFileName+ r. nextInt ( 10 ) ;
}
String originalFilename = cm. getOriginalFilename ( ) ;
String suffix = originalFilename. substring ( originalFilename. lastIndexOf ( "." ) ) ;
Client client = Client. create ( ) ;
WebResource resource = client. resource ( Commons. PIC_HOST+ "/upload/" + newFileName+ suffix) ;
resource. put ( String. class , fbytes) ;
String fullPath = Commons. PIC_HOST+ "/upload/" + newFileName+ suffix;
String relativePath= "/upload/" + newFileName+ suffix;
String result= "{\"fullPath\":\"" + fullPath+ "\",\"relativePath\":\"" + relativePath+ "\"}" ;
out. print ( result) ;
}
}
页面缓存
使用Oscache实现页面缓存 需要导入两个jar包:oscash
和commons-logging
在web.xml中配置一个filter用来过滤特定的请求实现页面缓存
< filter>
< filter-name> oscache</ filter-name>
< filter-class> com.opensymphony.oscache.web.filter.CacheFilter</ filter-class>
< init-param>
< param-name> time</ param-name>
< param-value> 3600</ param-value>
</ init-param>
< init-param>
< param-name> scope</ param-name>
< param-value> application</ param-value>
</ init-param>
</ filter>
< filter-mapping>
< filter-name> oscache</ filter-name>
< url-pattern> /items/*</ url-pattern>
</ filter-mapping>
要实现缓存持久化,需要在src路径下添加配置文件oscache.properties
cache.memory=false
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.DiskPersistenceListener
cache.path=F:\\cache
页面静态化freemarker
需要导入两个jar包:com.springsource.freemarker
和spring-context-support
在springmvc的配置文件中,将视图解析器进行替换,原来的视图解析器用来解析jsp页面,现在用来解析ftl静态页面
< bean class = " org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer" >
< property name = " templateLoaderPath" value = " /WEB-INF/jsps/" > </ property>
< property name = " defaultEncoding" value = " UTF-8" > </ property>
< property name = " freemarkerSettings" >
< props>
< prop key = " template_update_delay" > 0</ prop>
< prop key = " default_encoding" > UTF-8</ prop>
< prop key = " number_format" > 0.##########</ prop>
< prop key = " datetime_format" > yyyy-MM-dd HH:mm:ss</ prop>
< prop key = " classic_compatible" > true</ prop>
< prop key = " template_exception_handler" > ignore</ prop>
</ props>
</ property>
</ bean>
< bean class = " org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver" >
< property name = " suffix" value = " .ftl" > </ property>
< property name = " contentType" value = " text/html;charset=utf-8" > </ property>
</ bean>
此时使用.ftl静态页面来替换.jsp动态页面,能够提高访问速度 freemarker语法之遍历list
//定义数据
Map root = new HashMap();
List<String> persons = new ArrayList<String>();
persons.add("范冰冰");
persons.add("李冰冰");
persons.add("何灵");
root.put("persons", persons);
//页面
<#list persons as p>
${p.id}/${p.name}
</#list>
<#assign x="haha" />
${x}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
< c: set var = " picPath" value = " http://127.0.0.1:8003/ssmImage19" > </ c: set>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
< html>
< head>
< meta http-equiv = " Content-Type" content = " text/html; charset=UTF-8" >
< title> 查询商品列表</ title>
</ head>
< body>
< form action = " ${pageContext.request.contextPath }/items/deleteByIds.do" method = " post" >
查询条件:
< table width = " 100%" border = 1>
< tr>
< td> < input type = " submit" value = " 查询" /> </ td>
< td> < input type = " submit" value = " 批量删除" /> </ td>
</ tr>
</ table>
商品列表:
< table width = " 100%" border = 1>
< tr>
< td> ID</ td>
< td> 商品名称</ td>
< td> 商品图片</ td>
< td> 商品价格</ td>
< td> 生产日期</ td>
< td> 商品描述</ td>
< td> 操作</ td>
</ tr>
< c: forEach items = " ${itemsList }" var = " item" >
< tr>
< td>
< input type = " checkbox" name = " id" value = " ${item.id }" >
</ td>
< td> ${item.name }</ td>
< td>
< img id = ' imgSize1ImgSrc' src = ' ${picPath }${item.pic }' height = " 100" width = " 100" />
</ td>
< td> ${item.price }</ td>
< td> < fmt: formatDate value = " ${item.createtime}" pattern = " yyyy-MM-dd HH:mm:ss" /> </ td>
< td> ${item.detail }</ td>
< td> < a href = " ${pageContext.request.contextPath }/items/edit.do?id=${item.id}" > 修改</ a>
< a href = " ${pageContext.request.contextPath }/items/deleteByID.do?id=${item.id}" > 删除</ a>
</ td>
</ tr>
</ c: forEach>
</ table>
</ form>
</ body>
</ html>
< #assign picPath = " http://127.0.0.1:8003/ssmImage19" />
< #assign projectName = " springmvc19_day02_02" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
< html>
< head>
< meta http-equiv = " Content-Type" content = " text/html; charset=UTF-8" >
< title> 查询商品列表</ title>
</ head>
< body>
< form action = " ${projectName }/items/deleteByIds.do" method = " post" >
查询条件:
< table width = " 100%" border = 1>
< tr>
< td> < input type = " submit" value = " 查询" /> </ td>
< td> < input type = " submit" value = " 批量删除" /> </ td>
</ tr>
</ table>
商品列表:
< table width = " 100%" border = 1>
< tr>
< td> ID</ td>
< td> 商品名称</ td>
< td> 商品图片</ td>
< td> 商品价格</ td>
< td> 生产日期</ td>
< td> 商品描述</ td>
< td> 操作</ td>
</ tr>
< #list itemsList as item >
< tr>
< td>
< input type = " checkbox" name = " id" value = " ${item.id }" >
</ td>
< td> ${item.name }</ td>
< td>
< img id = ' imgSize1ImgSrc' src = ' ${picPath }${item.pic }' height = " 100" width = " 100" />
</ td>
< td> ${item.price }</ td>
< td> </ td>
< td> ${item.detail }</ td>
< td> < a href = " ${projectName }/items/edit.do?id=${item.id}" > 修改</ a>
< a href = " ${projectName }/items/deleteByID.do?id=${item.id}" > 删除</ a>
</ td>
</ tr>
</ #list>
</ table>
</ form>
</ body>
</ html>
拦截器
< mvc: interceptors>
< mvc: interceptor>
< mvc: mapping path = " /**" />
< bean class = " com.gaishi_hero.interceptor.Interceptor1" > </ bean>
</ mvc: interceptor>
< mvc: interceptor>
< mvc: mapping path = " /**" />
< bean class = " com.gaishi_hero.interceptor.Interceptor2" > </ bean>
</ mvc: interceptor>
</ mvc: interceptors>
拦截器需要实现HandlerInterceptor
package com. gaishi_hero. interceptor;
import javax. servlet. http. HttpServletRequest;
import javax. servlet. http. HttpServletResponse;
import org. springframework. web. servlet. HandlerInterceptor;
import org. springframework. web. servlet. ModelAndView;
public class Interceptor1 implements HandlerInterceptor {
public boolean preHandle ( HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System. out. println ( "这是第一个拦截器Interceptor1。。。preHandle" ) ;
return true ;
}
public void postHandle ( HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System. out. println ( "这是第一个拦截器Interceptor1。。。postHandle" ) ;
}
public void afterCompletion ( HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System. out. println ( "这是第一个拦截器Interceptor1。。。afterCompletion" ) ;
}
}
第二个拦截器相同的写法 访问任何一个路径,后台的打印结果如下:
这是第一个拦截器Interceptor1。。。preHandle
这是第二个拦截器Interceptor2。。。preHandle
这是第二个拦截器Interceptor2。。。postHandle
这是第一个拦截器Interceptor1。。。postHandle
这是第二个拦截器Interceptor2。。。afterCompletion
这是第一个拦截器Interceptor1。。。afterCompletion
这是第一个拦截器Interceptor1。。。preHandle
这是第二个拦截器Interceptor2。。。preHandle
这是第一个拦截器Interceptor1。。。afterCompletion
Springmvc规定:凡是preHandle返回true,afterCompletion必须执行。