一、SpringMvc学习笔记
1、使用SpringMvc时需在web.xml文件中添加配置
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
springMVC
*.do
2、SpringMvc配置文件:spring-mvc.xml文件配置
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
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/context
http://www.springframework.org/schema/context/spring-context.xsd">
<-- 视图解析器-->
3、controller配置:@Controller(注解形式)
@Controller
public class HelloWorldController {
@RequestMapping("/helloWorld")
public String helloWorld(Model model){
model.addAttribute("message", "问候SpringMvc他大爷");
return "helloWorld"; //直接返回 /WEB-INF/jsp/helloWorld.jsp
}
}
4、防止乱码:在web.xml文件中加入
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
characterEncodingFilter
/
5、
6、ModelAndView详解:
@RequestMapping("/list")
public ModelAndView list(){
ModelAndView mav=new ModelAndView();
mav.addObject("studentList", studentList);
mav.setViewName("student/list");
return mav;
}
@RequestMapping("/preSave")
public ModelAndView preSave(@RequestParam(value="id",required=false) String id){
ModelAndView mav=new ModelAndView();
if (id != null) {
mav.addObject("student", studentList.get(Integer.parseInt(id)-1));
mav.setViewName("student/update");
}else {
mav.setViewName("student/add");
}
return mav;
}
@RequestMapping("/save")
public String save(Student student){
if (student.getId() != 0) {
Student s = studentList.get(student.getId()-1);
s.setName(student.getName());
s.setAge(student.getAge());
}else {
studentList.add(student);
}
return "redirect:/student/list.do";//重定向
}
@RequestMapping("/delete")
public String delete(@RequestParam(value="id",required=false) int id){
studentList.remove(id-1);
return "redirect:/student/list.do";//重定向
}
7、@RequestMapping("/login")
public String login(HttpServletRequest request,HttpServletResponse response){
System.out.println("---------登录验证--------");
String userName = request.getParameter("userName");
String password = request.getParameter("password");
Cookie cookie = new Cookie("user", userName+"-"+password);
User currentUser = new User(userName, password);
cookie.setMaxAge(1*60*60*24*7);
response.addCookie(cookie);
HttpSession session = request.getSession();
session.setAttribute("currentUser", currentUser);
return "redirect:/main.jsp";
}
@RequestMapping("/login2")
public String login2(HttpServletRequest request){
System.out.println("---------登录验证--------");
return "redirect:/main.jsp";
}
@RequestMapping("/login3")
public String login3(HttpSession session){
System.out.println("---------登录验证--------");
session.setAttribute("currentUser", "");
return "redirect:/main.jsp";
}
//直接返回user对象的ajax形式信息
@RequestMapping("/ajax")
public @ResponseBody User ajax(){
User user = new User("张三", "admin");
return user;
}
@RequestMapping("/list")
public String list(Model model){
return "article/list";
}
//restful风格的url
//请求地址形式为:
//
文章一
//
文章二
@RequestMapping("/details/{id}")
public ModelAndView details(@PathVariable("id") int id){
ModelAndView mav=new ModelAndView();
if(id==1){
mav.addObject("article", new Article("文章一","文章一的内容"));
}else if(id==2){
mav.addObject("article", new Article("文章二","文章二的内容"));
}
mav.setViewName("article/details");
return mav;
}
8、SpringMvc配置支持文件上传:
前台页面:
1、单文件上传
前台页面配置:
后台controller:
@RequestMapping("/upload")
public String uploadFile(@RequestParam("file1") MultipartFile file1,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
file1.transferTo(new File(filePath+"upload/"+file1.getOriginalFilename()));
return "redirect:success.html";
}
2、多文件上传
前台页面:
后台controller:
@RequestMapping("/upLoadPic2")
public String uploadFiles(@RequestParam("file") MultipartFile[] files,HttpServletRequest request)throws Exception{
String filePath=request.getServletContext().getRealPath("/");
System.out.println(filePath);
for(MultipartFile file:files){
file.transferTo(new File(filePath+"upload/"+file.getOriginalFilename()));
}
return "redirect:success.html";
}
二、Spring学习笔记
1、bean配置
2、获取ApplicationContext对象:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
3、bean的注入方法:
属性注入、构造注入(通过类型、索引、联合使用类型和索引)、非静态工厂注入、工厂注入、泛型依赖注入
public class PeopleFactory {
public People createPeople(){
People people = new People();
people.setId(6);
people.setAge(29);
people.setName("李伟");
return people;
}
}
public class PeopleFactory2 {
public static People createPeople(){
People people = new People();
people.setId(5);
people.setAge(23);
people.setName("刘锡");
return people;
}
}
4、各种类型注入(包括集合属性)
唱歌
跳舞
唱歌
跳舞
唱歌2
跳舞2
唱歌
跳舞
唱歌2
跳舞2
唱歌
跳舞
唱歌2
跳舞2
address1
address2
People类主体:
private int id;
private String name;
private int age;
private Dog dog;
private List
hobbies = new ArrayList();
private Set loves = new HashSet();
private Map works = new HashMap();
private Properties address = new Properties();
//测试类主体
private ApplicationContext ac;
@Before
public void setUp() throws Exception {
ac = new ClassPathXmlApplicationContext("beans.xml");
}
/*注入基本类型值*/
@Test
public void test() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people1 = (People) ac.getBean("people1");
System.out.println(people1);
}
/*注入bean*/
@Test
public void test2() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people2 = (People) ac.getBean("people2");
System.out.println(people2);
}
/*注入内部bean*/
@Test
public void test3() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people3 = (People) ac.getBean("people3");
System.out.println(people3);
}
/*注入null*/
@Test
public void test4() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people4 = (People) ac.getBean("people4");
System.out.println(people4);
}
/*级联属性*/
@Test
public void test5() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people5 = (People) ac.getBean("people5");
System.out.println(people5);
}
/*注入list集合*/
@Test
public void test6() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people6 = (People) ac.getBean("people6");
System.out.println(people6);
}
/*注入set集合*/
@Test
public void test7() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people7 = (People) ac.getBean("people7");
System.out.println(people7);
}
/*注入map集合*/
@Test
public void test8() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people8 = (People) ac.getBean("people8");
System.out.println(people8);
}
/*注入properties属性*/
@Test
public void test9() {
ac = new ClassPathXmlApplicationContext("beans.xml");
People people9 = (People) ac.getBean("people9");
System.out.println(people9);
}
5、自动注入:
default-autowire="byType">
6、设置bean实例为多例:
public abstract Dog getDog();//让srping去动态实现dog的多例
7、Spring中的方法替换:
People实体类:
public class People {
private int id;
private String name;
private int age;
private Dog dog;//byName时,自动注入beans中名称为dog的属性
public int getId() {
return id;
}
public Dog getDog(){
Dog dog = new Dog();
dog.setName("jack");
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
People2实体类,实现接口org.springframework.beans.factory.support.MethodReplacerMethodReplacer
public class People2 implements MethodReplacer{
@Override
public Object reimplement(Object arg0, Method arg1, Object[] arg2)
throws Throwable {
Dog dog = new Dog();
dog.setName("tom");
return dog;
}
}
8、bean的作用范围:prototype多例,request即每次请求创建一个新的bean,session,global session,
application,singleton单例 ,request
Authority实体类:
public class Authority {
public Authority() {
System.out.println("获取权限");
}
}
9、Spring AOP
public class StudentServiceImpl implements StudentService {
@Override
public void addStudent(String name) {
//未使用aop的话,只会增加代码耦合度
System.out.println("开始添加学生:"+name);
System.out.println("添加学生:"+name);
System.out.println("完成学生"+name+"添加");
}
}
AOP配置:
StudentServiceAspect实体类:
public class StudentServiceAspect {
//前置通知
public void doBefore(JoinPoint jp){
System.out.println("类名:"+jp.getTarget().getClass().getName());
System.out.println("方法名:"+jp.getSignature().getName());
System.out.println("开始添加学生:"+jp.getArgs()[0]);
}
//后置通知
public void doAfter(JoinPoint jp){
System.out.println("类名:"+jp.getTarget().getClass().getName());
System.out.println("方法名:"+jp.getSignature().getName());
System.out.println("学生添加完成:"+jp.getArgs()[0]);
}
//环绕通知
public Object doAround(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("添加学生前");
Object retVal = pjp.proceed();//代表方法执行,如果配置了环绕通知,则不必在配置前后置通知,
//retVal即为所执行的方法的返回值
System.out.println(retVal);
System.out.println("添加学生后");
return retVal;
}
//返回通知,方法return之前调用
public void doAfterReturning(JoinPoint jp) throws Throwable{
System.out.println("返回通知");
}
//异常通知,方法return之前调用
public void doAfterThrowing(JoinPoint jp,Throwable ex) throws Throwable{
System.out.println("异常通知");
System.out.println("异常信息:"+ex.getMessage());
}
}
10、Spring JDBC的支持
1)JdbcTemplate使用:
jdbc.properties文件:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_spring
jdbc.username=root
jdbc.password=123
StudentDaoImpl类实体:
public class StudentDaoImpl implements StudentDao{
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,?,?)";
Object []params=new Object[]{student.getName(),student.getAge()};
return jdbcTemplate.update(sql,params);
}
@Override
public int updateStudent(Student student) {
String sql="update t_student set name=?,age=? where id=?";
Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};
return jdbcTemplate.update(sql,params);
}
@Override
public int deleteStudent(int id) {
String sql="delete from t_student where id=?";
Object []params=new Object[]{id};
return jdbcTemplate.update(sql,params);
}
@Override
public List findStudents() {
String sql="select * from t_student";
final List studentList=new ArrayList();
jdbcTemplate.query(sql, new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
Student student=new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
}
});
return studentList;
}
}
2)JdbcDaoSupport使用
StudentDaoImpl实体类:
public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao{
//extends之后 只需为id=studentDao的bean添加dataSource即可
@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,?,?)";
Object []params=new Object[]{student.getName(),student.getAge()};
return this.getJdbcTemplate().update(sql,params);
}
@Override
public int updateStudent(Student student) {
String sql="update t_student set name=?,age=? where id=?";
Object []params=new Object[]{student.getName(),student.getAge(),student.getId()};
return this.getJdbcTemplate().update(sql,params);
}
@Override
public int deleteStudent(int id) {
String sql="delete from t_student where id=?";
Object []params=new Object[]{id};
return this.getJdbcTemplate().update(sql,params);
}
@Override
public List findStudents() {
String sql="select * from t_student";
final List studentList=new ArrayList();
this.getJdbcTemplate().query(sql, new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
Student student=new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
}
});
return studentList;
}
}
3)使用namedParameterJdbcTemplate
StudentDaoImpl实体类:
public class StudentDaoImpl implements StudentDao{
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}
public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,:name,:age)";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("name", student.getName());
mps.addValue("age", student.getAge());
return namedParameterJdbcTemplate.update(sql, mps);
}
@Override
public int updateStudent(Student student) {
String sql="update t_student set name=:name,age=:age where id=:id";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("name", student.getName());
mps.addValue("age", student.getAge());
mps.addValue("id", student.getId());
return namedParameterJdbcTemplate.update(sql,mps);
}
@Override
public int deleteStudent(int id) {
MapSqlParameterSource mps = new MapSqlParameterSource();
String sql="delete from t_student where id=:id";
mps.addValue("id", id);
return namedParameterJdbcTemplate.update(sql,mps);
}
@Override
public List findStudents() {
String sql="select * from t_student";
final List studentList=new ArrayList();
namedParameterJdbcTemplate.query(sql, new RowCallbackHandler(){
@Override
public void processRow(ResultSet rs) throws SQLException {
Student student=new Student();
student.setId(rs.getInt("id"));
student.setName(rs.getString("name"));
student.setAge(rs.getInt("age"));
studentList.add(student);
}
});
return studentList;
}
}
测试类:
public class T {
private ApplicationContext ac;
@Before
public void setUp() throws Exception {
ac=new ClassPathXmlApplicationContext("beans.xml");
}
@Test
public void addStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int addNums=studentService.addStudent(new Student("王五", 1));
if(addNums==1){
System.out.println("添加成功");
}
}
@Test
public void updateStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int updateNums=studentService.updateStudent(new Student(6,"王五2", 2));
if(updateNums==1){
System.out.println("更新成功");
}
}
@Test
public void deleteStudent() {
StudentService studentService=(StudentService)ac.getBean("studentService");
int deleteNums=studentService.deleteStudent(6);
if(deleteNums==1){
System.out.println("删除成功");
}
}
@Test
public void findStudents() {
StudentService studentService=(StudentService)ac.getBean("studentService");
List studentList=studentService.findStudents();
for(Student student:studentList){
System.out.println(student);
}
}
}
11、Spring 事务管理器
BankDaoImpl实体类:
public class BankDaoImpl implements BankDao {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}
public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public void inMoney(int money, int userId) {
String sql = "update t_count set count = count + :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}
@Override
public void outMoney(int money, int userId) {
String sql = "update t_count set count = count - :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}
}
BankServiceImpl实体类:
public class BankServiceImpl implements BankService{
private BankDao bankDao;
private TransactionTemplate transactionTemplate;
/*要使用TransactionTemplate,需要加jdbc事务管理器*/
/*编程式事务管理*/
@Override
public void transferAccounts(final int count,final int userIdA,final int userIdB) {
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
bankDao.outMoney(count, userIdA);
bankDao.inMoney(count, userIdB);
}
});
}
public void setBankDao(BankDao bankDao) {
this.bankDao = bankDao;
}
public TransactionTemplate getTransactionTemplate() {
return transactionTemplate;
}
public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
this.transactionTemplate = transactionTemplate;
}
}
public class BankDaoImpl implements BankDao {
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
public NamedParameterJdbcTemplate getNamedParameterJdbcTemplate() {
return namedParameterJdbcTemplate;
}
public void setNamedParameterJdbcTemplate(
NamedParameterJdbcTemplate namedParameterJdbcTemplate) {
this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
}
@Override
public void inMoney(int money, int userId) {
String sql = "update t_count2 set count = count + :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}
@Override
public void outMoney(int money, int userId) {
String sql = "update t_count set count = count - :money where userId = :userId";
MapSqlParameterSource mps = new MapSqlParameterSource();
mps.addValue("money", money);
mps.addValue("userId", userId);
namedParameterJdbcTemplate.update(sql, mps);
}
}
public class BankServiceImpl implements BankService{
private BankDao bankDao;
@Override
public void transferAccounts(final int count,final int userIdA,final int userIdB) {
bankDao.outMoney(count, userIdA);
bankDao.inMoney(count, userIdB);
}
public void setBankDao(BankDao bankDao) {
this.bankDao = bankDao;
}
}