1单例模式
懒汉模式: 延迟加载
public class User(){
private static User u;
//私有构造 可以保证操作只执行一次
private User(){
//操作
}
public User getUser(){
return u=new User();
}
}
饿汉模式:在创建类的时候加载
public class User(){
private static User u=new User();
private User(){
}
public User getUser(){
return u;
}
}
2 SpringMVC Controller 默认为单例模式 不可以创建成员变量 否则会造成线程不安全(A用户查询 B用户也查询 数据显示有可能B显示A的)
SpringMvc Controller 的成员变量 只能创建 Service层的接口 因为都会调用
- 输入查询条件时候 若输入中文,会出现乱码的解决方案
在web.xml文件中添加
<filter>
<filter-name>encodingFilter</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>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
</url-pattern>/*</url-pattern>
</filter-mapping>
4 修改超市系统 Spring MVC+Spring+JDBC
1.加入Spring Spring MVC的jar文件
2.Spring配置文件(通过context:component-scan/标签扫秒包下的所有类 让类的注解生效)
<context:component-scan base-package="cn.smbms.service"/>
<context:component-scan base-package="cn.smbms.dao"/>
3.配置web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
登录功能改造
1改Dao层 在实现类加@Respository注解
2改service层 在实现类加@Service dao的成员变量加@Service
3改Controller
return "redirect:/index.html"
//相当于 response.sendRedirect("index.jsp");
return "forword:/index.html"
//相当于 request.xxxxx("index.html");
4改造View层
5部署运行
登录后如何将信息存入session中
使用Servlet API作为处理方法的入参 (Servlet API 就是 HttpSession HttpServletRequest这种)
静态资源文件引用
1.将css js等文件放在WebRoot下的statics文件夹下
2.在spring mvc配置文件中加 <mvc:resources mapping="/statics/**" location="/statics/"/>
异常处理
1.局部异常处理(只能处理Controller中的异常)使用@ExceptionHandler注解完成
@ExceptionHandler(value="exlogin.html",method=RequestMethod.GET)
public String exLogin(@RequestParam String usercode,@RequestParam String userPassword){
//登录失败
if(true){
return throw new RuntimeException("用户名和密码不对");
}
return "redirect:index"
}
@ExceptionHandler(value={RuntimeException.class})
public String handlerException(RuntimeExcepiton e,HttpServletRequest req){
req.serAttribute("e",e);
return "error";//跳转到error页面 然后error 通过${e}来展示数据
}
}
2 全局异常处理
在Springmvc 配置文件中配置全局异常
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<prop key="java.lang.RuntimeException">error</prop>
</property>
</bean>
修改上个例子 删除ExceptionHandler处理方法
在error中用显示数据改为${exception.message}