springmvc的基本使用

一、springmvc的基本配置和使用
       1、导包(springmvc单独使用的包)
              springmvc的基本使用_第1张图片
2、在src下创建springmvc.xml配置文件

3、在web.xml中配置前端控制器
   

springmvc
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath:springmvc.xml




springmvc
*.action


4、使用spring注解方式书写controller类
        /**
* 商品Controller

* @author Administrator

*/
@Controller
public class CommodityController {
@RequestMapping("/CommodityList.action")//url映射
public ModelAndView CommodityList() {
ModelAndView modelAndView = new ModelAndView();
List cItems =new ArrayList<>();
cItems.add(new CommodityItem(1, "1华为 荣耀8", 2399f, new Date(), "质量好!1"));
cItems.add(new CommodityItem(2, "2华为 荣耀8", 2399f, new Date(), "质量好!2"));
cItems.add(new CommodityItem(3, "3华为 荣耀8", 2399f, new Date(), "质量好!3"));

//设置数据
modelAndView.addObject("cItems", cItems);
//设置视图
modelAndView.setViewName("/WEB-INF/jsp/commodityList.jsp");

return modelAndView;
}
}

5、在springmvc.xml中配置注解扫描包
      xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

 
 
 

  
6、在浏览器中输入http://localhost:8080/springmvc_demo1/CommodityList.action测试

7、配置三大组件(映射器、适配器、视图解释器)
先在springmvc中引入mvc约束









class="org.springframework.web.servlet.view.InternalResourceViewResolver">



刚才CommodityController中的代码
   //设置视图
modelAndView.setViewName("/WEB-INF/jsp/commodityList.jsp");
可以简化为
   //设置视图
   modelAndView.setViewName("commodityList");

二、ssm的整合
        1、导包(spring和mybatis整合、springmvc和mybatis整合、ssm整合导入的jar包是一样的,可以参照spring和mybatis整合导的jar包)

2、在src下书写db.properties、applicationContext.xml、sqlMapConfig.xml、springmvc.xml
       db.properties:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123

sqlMapConfig.xml:
   
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">







springmvc.xml:
   
  xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd                                                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd                                                                                      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd                                                                                                        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">








class="org.springframework.web.servlet.view.InternalResourceViewResolver">




applicationContext.xml:
   
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
       
 
 
  




destroy-method="close">






















3、在web.xml中配置
   

org.springframework.web.context.ContextLoaderListener


contextConfigLocation
classpath:applicationContext.xml




springmvc
org.springframework.web.servlet.DispatcherServlet

contextConfigLocation
classpath:springmvc.xml




springmvc
*.action


4、展示商品列表的示例代码:
  A、书写dao(Mapper)层接口,和dao(Mapper)的xml文件,两者要名称一样并放在一个目录下(具体原因查看mybatis的基本使用)
/**
* 商品dao层接口

* @author Administrator

*/
public interface ItemsDao {
List getItemList();
}


PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">




B、书写service层
/**
* 商品service层
* @author Administrator
*
*/
@Service
public class ItemsServiceImpl implements ItemsService {

//依赖dao层,通过注解从spring中获取dao
@Autowired
private ItemsDao itemsDao;

@Override
public List getItemList() {
return itemsDao.getItemList();
}
}

C、书写controller层
   /**
* 商品Controller

* @author Administrator

*/
@Controller
public class ItemsController {

// 依赖service层,从spring中获取service
@Autowired
private ItemsService itemsService;

@RequestMapping("/ItemList.action")
public ModelAndView CommodityList() {

//获取数据
List itemsList = itemsService.getItemList();

ModelAndView modelAndView = new ModelAndView();
// 设置数据
modelAndView.addObject("itemList", itemsList);
// 设置视图
modelAndView.setViewName("itemList");

return modelAndView;
}
}

D、访问http://localhost:8080/springmvc_mybatis/ItemList.action测试

    5、简单类型参数绑定
  dao层和service层代码省略,controller中添加方法:
  //根据商品id查询商品
@RequestMapping("/itemEdit.action")
public ModelAndView getItemById(Integer id) {

//获取数据
Items items = itemsService.getItemById(id);

ModelAndView modelAndView = new ModelAndView();
// 设置数据
modelAndView.addObject("item", items);
// 设置视图
modelAndView.setViewName("editItem");

return modelAndView;
}
绑定的是参数,方法中的参数是jsp中传递过来的,形参名称要和jsp中的参数名称相同(这里方法中的形参名称是id,jsp中的参数名称也是id)
jsp代码:
修改

6、对象类型参数绑定(pojo类型,包装类型参数绑定和这种方式一样,只是多叠加一层)
  dao层和service层代码省略,controller中添加方法:
   //修改商品信息
@RequestMapping("/updateitem.action")
public ModelAndView updateItem(Items items) {

//获取数据
Items itemsNew = itemsService.updateItem(items);

ModelAndView modelAndView = new ModelAndView();
// 设置视图
modelAndView.setViewName("success");

return modelAndView;
}
方法形参items和jsp没有关系,可以任意命名,但是jsp中的每个字段的名称必须和Items类中的属性一样
jsp代码:
 
  
7、自定义参数类型绑定
  A、先在springmvc中配置转换器




class="org.springframework.format.support.FormattingConversionServiceFactoryBean">








B、书写转换器类(这里是日期转换器)
        /**
* 日期转换器,第一个泛型参数是转换之前的格式,第二个泛型参数转换后的类型格式

* @author Administrator

*/
public class DateConversion implements Converter {

@Override
public Date convert(String strDate) {
DateFormat dFormat = new SimpleDateFormat("yyyy_MM_dd");
try {
return dFormat.parse(strDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

C、正常接收参数(yyyy_MM_dd格式的字符串形式的日期,在controller里接收参数时,会自动转换为Date类型)

8、数组参数类型绑定(如果是list类型则必须放在包装类中,让list作为包装类的一个属性,springmvc不支持单独接收list数据)
// 删除多个商品
@RequestMapping("/deletes.action")
public ModelAndView deleteItems(Integer[] ids) {

// 获取数据
Items itemsNew = itemsService.deleteItems(ids);

System.out.print(ids.length);

ModelAndView modelAndView = new ModelAndView();
// 设置视图
modelAndView.setViewName("success");

return modelAndView;
}
多选框,一次提交多个商品id
   
  
9、解决post乱码问题

 
encoding
org.springframework.web.filter.CharacterEncodingFilter

encoding
UTF-8

 

 
 
encoding
*.action
 

     
10、上面所写的controller层的方法的返回值都是ModelAndView,其实这种方式并不常用,因为耦合性太强了。还有其他两种返回值:
   A、返回string,返回的是视图路径,数据放在形参里的Model中。这样使视图和数据解耦。
B、返回值是void,不需要跳转视图的时候使用,比如客户端网络请求,返回json数据时。


三、异常处理器
    springmvc提供一个异常处理器接口HandlerExceptionResolver,我们需要写出它的实现类,然后在自己写的实现类中处理异常。
A、基本使用
/**
* 自定义异常处理类,实现springmvc中的异常处理器接口HandlerExceptionResolver
* @author Administrator
*
*/
@Component
public class CustomExceptionDeal implements HandlerExceptionResolver {

/**
* request 请求 
* response 响应 
* object 出错的位置,能定位到具体的出错的方法(包含能找到方法的完整信息,包+类+方法名+返回值+参数) 
* exception 异常信息
*/
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object object, Exception exception) {
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("error",exception.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
可以在程序中定义一个除0异常进行测试,错误方法位置信息为:
   public org.springframework.web.servlet.ModelAndView cn.znh.springmvc.controller.ItemsController.CommodityList()

B、根据业务需求,手动抛出异常,在根据异常进行业务处理,比如接收的参数为空,就可以手动抛出异常,跳转到指定错误页面。
/**
* 自定义异常类,处理一些自己预期的业务上的异常(根据业务需要,自己手动抛出的异常)

* @author Administrator

*/
public class MessageException extends Exception {

private String msg;

public MessageException(String msg) {
super();
this.msg = msg;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

   // 根据商品id查询商品
@RequestMapping("/itemEdit.action")
public ModelAndView getItemById(Integer id) throws MessageException {
   //id为空就抛自定义异常
if(id==null){
throw new MessageException("id不能为空");
}

// 获取数据
Items items = itemsService.getItemById(id);
ModelAndView modelAndView = new ModelAndView();
// 设置数据
modelAndView.addObject("item", items);
// 设置视图
modelAndView.setViewName("editItem");
return modelAndView;
}

/**
* 自定义异常处理类,实现springmvc中的异常处理器接口HandlerExceptionResolver

* @author Administrator

*/
@Component
public class CustomExceptionDeal implements HandlerExceptionResolver {

/**
* request 请求
* response 响应
* object 出错的位置,能定位到具体的出错的方法(包含能找到方法的完整信息,包+类+方法名+返回值+参数)
* exception 异常信息
*/
@Override
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object object, Exception exception) {

ModelAndView modelAndView = new ModelAndView();
if (exception instanceof MessageException) {//自己预期的异常,进行业务处理
modelAndView.addObject("error", ((MessageException) exception).getMsg());
} else {//不是自己预期的异常
modelAndView.addObject("error", "未知异常");
}
modelAndView.setViewName("error");
return modelAndView;
}
}


四、json交互

        A、引入jquery,放在WebContent目录下。

              

B、导包  

             

C、在jsp中书写js测试代码



D、书写controller层的代码
   // json数据交互
@RequestMapping(value = "/json.action")
public @ResponseBody
CommodityItem json(@RequestBody CommodityItem item) {
System.out.println(item);
return item;
}


五、springmvc中的拦截器使用(可以在里面做全局操作)
        在springmvc.xml中配置拦截器



//拦截所有








 


书写拦截器类(Interceptor1和Interceptor2,这里只书写Interceptor1)
   public class Interceptor1 implements HandlerInterceptor{
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

System.out.println("方法前执行----------1");

//可以在这做全局登录判断,如果没有登陆就重定向到登陆页面(不放行),如果登陆了就放行,继续执行后面的业务逻辑

String requestURI = request.getRequestURI();
if(!requestURI.contains("/login")){//登录页面不拦截
String username = (String) request.getSession().getAttribute("user_name");
if(null == username){
response.sendRedirect(request.getContextPath() + "/login.action");
return false;
}
}
return true;
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {

System.out.println("方法后执行----------1");

}
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {

System.out.println("页面渲染后执行----------1");

}
}






你可能感兴趣的:(javaweb)