导入jar包 创建配置文件 SpringMVC的配置文件与Spring一致
修改web.xml添加MVC核心控制器
创建Controller类用于处理请求
添加@Controller注解 让容器加载该类 为了使注解生效需要在配置文件中添加注解驱动
创建名为getUser的方法
当请求路径为getUser.action时 该方法被调用 ModelAndView用来封装视图资源和所需数据
测试
创建list.jsp 浏览器输入地址 访问getUser.action 查看页面是否跳转到list.jsp 如果成功跳转则意味着SpringMVC配置成功
参数绑定
1. 基础数据类型绑定
int float double boolean...
注意:默认参数是可选的 不传也行 但是如果你的参数是基础类型 比如int 那就必须传 因为不传的话
后台取到的是null 视图会把null 转为int 异常
所以:建议基础数据类型全部使用包装类型
2. RequestParam 注解
用来指定参数的映射规则
例如:
@RequestPram(value ="sid" ,request=false ,defaultValue="1" )
value 表示将请求中的sid映射到当前参数
required表示该参数可选
defaultValue表示默认值为1
3. POJO参数绑定
在方法中添加POJO类型的参数
前台参数名与POJO内的属性一致即可
4. 包装类型
例如 有一个ClassRoom对象 属性中包含一个Student对象
处理器方法中声明参数类型为ClassRoom
前台传参数时 name="student.s_name"
5. 默认支持的参数
HTTPServletRequest
HTTPServletRsponse
HTTPServletSession
Controller处理请求的方法的返回值
1. ModelAndView 将视图名字 与 视图需要的数据打包成一个对象
2. String 将返回值作为视图的名字
此时没有了ModelAndView 数据无法传给页面
方案一:在方法中添加Model类型参数
将要发给页面的数据添加到Model中
处理适配器会自动将model中的数据放到request 中
方案二:在方法中添加ModelMap
原理同方案一
请求转发与请求重定向
主要通过给返回的视图资源加上前缀
转发:
请求 forward :xxxxx .action
页面 forward :xxxxx .jsp
重定向:
请求 redirect :xxxxx .action
页面 redirect :xxxxx .jsp
Post请求乱码处理
tomcat 8 以上版本默认会将IOS8859-1转UTF-8
POST 默认UTF-8 tomcat把它当成8859-1 造成乱码
解决方案:
过滤器
代码示例
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 > SpringMVC01</display-name >
<welcome-file-list >
<welcome-file > index.html</welcome-file >
<welcome-file > index.htm</welcome-file >
<welcome-file > index.jsp</welcome-file >
<welcome-file > default.html</welcome-file >
<welcome-file > default.htm</welcome-file >
<welcome-file > default.jsp</welcome-file >
</welcome-file-list >
<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 >
</filter >
<filter-mapping >
<filter-name > encodingFilter</filter-name >
<url-pattern > *.action</url-pattern >
</filter-mapping >
<servlet >
<servlet-name > Spring</servlet-name >
<servlet-class > org.springframework.web.servlet.DispatcherServlet</servlet-class >
<init-param >
<param-name > contextConfigLocation</param-name >
<param-value > classpath:SpringMVC-servlet2.xml</param-value >
</init-param >
</servlet >
<servlet-mapping >
<servlet-name > Spring</servlet-name >
<url-pattern > *.action</url-pattern >
</servlet-mapping >
</web-app >
SpringMVC-servlet.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:tx ="http://www.springframework.org/schema/tx"
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-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd" >
<bean name ="dataSource" class ="com.mchange.v2.c3p0.ComboPooledDataSource" >
<property name ="user" value ="root" > </property >
<property name ="password" value ="123456" > </property >
<property name ="jdbcUrl" value ="jdbc:mysql:///MVCDB" > </property >
<property name ="driverClass" value ="com.mysql.jdbc.Driver" > </property >
</bean >
<bean name ="sqlSessionFactory" class ="org.mybatis.spring.SqlSessionFactoryBean" >
<property name ="dataSource" ref ="dataSource" > </property >
</bean >
<bean class ="org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name ="basePackage" value ="com.lanou.dao" />
</bean >
<bean name ="transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
<property name ="dataSource" ref ="dataSource" />
</bean >
<tx:annotation-driven />
<context:component-scan base-package ="com.lanou" > </context:component-scan >
</beans >
Student.java
public class Student {
private int s_id;
private int s_age;
private String s_name;
private String s_gender;
public Student () {
super ();
}
public Student (int s_id, int s_age, String s_name, String s_gender) {
super ();
this .s_id = s_id;
this .s_age = s_age;
this .s_name = s_name;
this .s_gender = s_gender;
}
public int getS_id () {
return s_id;
}
public void setS_id (int s_id) {
this .s_id = s_id;
}
public int getS_age () {
return s_age;
}
public void setS_age (int s_age) {
this .s_age = s_age;
}
public String getS_name () {
return s_name;
}
public void setS_name (String s_name) {
this .s_name = s_name;
}
public String getS_gender () {
return s_gender;
}
public void setS_gender (String s_gender) {
this .s_gender = s_gender;
}
@Override
public String toString () {
return "Student [s_id=" + s_id + ", s_age=" + s_age + ", s_name=" + s_name + ", s_gender=" + s_gender + "]" ;
}
}
StudentDao.java
package com.lanou.dao;
import java.util.List;
import com.lanou.bean.Student;
public interface StudentDao {
public List<Student> getAllStudent ();
public Student getStudentById (Integer id);
public boolean updateStudent (Student stu);
public Student getStudentByName (String name);
public List<Student> getStudentsByGender (String gender);
}
StudentDao.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace ="com.lanou.dao.StudentDao" >
<select id="getAllStudent" resultType="com.lanou.bean.Student" >
select * from Student
</select >
<select id="getStudentById" resultType="com.lanou.bean.Student" >
select * from Student where s_id = #{param}
</select >
<update id="updateStudent" parameterType="com.lanou.bean.Student" >
update Student set
s_name=#{s_name},
s_age=#{s_age},
s_gender=#{s_gender}
where s_id = #{s_id}
</update>
<select id="getStudentByName" resultType="com.lanou.bean.Student" >
select * from Student where s_name = #{param}
</select >
<select id="getStudentsByGender" resultType="com.lanou.bean.Student" >
select * from Student where s_gender = #{param}
</select >
</mapper>
StudentService.java
package com.lanou.Service;
import java.util.List;
import com.lanou.bean.Student;
public interface StudentService {
public List<Student> getAllStudent ();
public Student getStudentById (Integer id);
public boolean updateStudent (Student stu);
public Student getStudentByName (String name);
public List<Student> getStudentsByGender (String gender);
}
StudentServiceImpl.java
package com.lanou.ServiceImpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lanou.Service.StudentService;
import com.lanou.bean.Student;
import com.lanou.dao.StudentDao;
@Service ("studentService" )
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public List<Student> getAllStudent () {
List<Student> students = studentDao.getAllStudent();
return students;
}
@Override
public Student getStudentById (Integer id) {
Student student = studentDao.getStudentById(id);
return student;
}
@Override
public boolean updateStudent (Student stu) {
return studentDao.updateStudent(stu);
}
@Override
public Student getStudentByName (String name) {
Student student = studentDao.getStudentByName(name);
return student;
}
@Override
public List<Student> getStudentsByGender (String gender) {
List<Student> students = studentDao.getStudentsByGender(gender);
return students;
}
}
StudentController.java
package com .lanou .Controller
import java.io .IOException
import java.util .List
import javax.servlet .ServletException
import javax.servlet .http .HttpServletRequest
import javax.servlet .http .HttpServletResponse
import org.springframework .beans .factory .annotation .Autowired
import org.springframework .stereotype .Controller
import org.springframework .ui .ModelMap
import org.springframework .web .bind .annotation .RequestMapping
import org.springframework .web .servlet .ModelAndView
import com .lanou .Service .StudentService
import com .lanou .bean .Student
@Controller
public class StudentController {
@Autowired
private StudentService studentService
// 获取所有学生
@RequestMapping("getAllStudent.action" )
public ModelAndView getAllStudent() {
ModelAndView mv = new ModelAndView()
List<Student> students = studentService.getAllStudent ()
mv.addObject ("students" , students)
mv.setViewName ("list.jsp" )
return mv
}
// 根据ID获取学生
@RequestMapping("getStudentById.action" )
public ModelAndView getStudetById(Integer id) {
ModelAndView mv = new ModelAndView()
Student student = studentService.getStudentById (id)
mv.addObject ("student" , student)
mv.setViewName ("update.jsp" )
return mv
}
// 更新学生数据
@RequestMapping("updateStudent.action" )
public ModelAndView updateStudent(Student stu) {
ModelAndView mv = new ModelAndView()
System.out .println (stu)
boolean b = studentService.updateStudent (stu)
if(b) {
mv.setViewName ("forward:getAllStudent.action" )
}else {
mv.setViewName ("updateError.jsp" )
}
return mv
}
@RequestMapping("getStudentByName.action" )
public String getStudentByName(String name,ModelMap model) {
Student student = studentService.getStudentByName (name)
model.addAttribute ("student" , student)
return "index.jsp"
}
@RequestMapping("getStudentsByGender.action" )
public void getStudentsByGender(String gender,HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
List<Student> students = studentService.getStudentsByGender (gender)
request.setAttribute ("students" , students)
request.getRequestDispatcher ("list.jsp" ).forward (request, response)
}
}
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!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 > Insert title here</title >
</head >
<body >
<h1 > ${student }</h1 >
</body >
</html >
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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 > Insert title here</title >
</head >
<body >
<table width ="100%" border ="1px" >
<tr >
<th > 编号</th >
<th > 姓名</th >
<th > 年龄</th >
<th > 性别</th >
<th > 操作</th >
</tr >
<c:forEach items ="${students }" var ="item" >
<tr >
<th > ${item.s_id }</th >
<th > ${item.s_name }</th >
<th > ${item.s_age }</th >
<th > ${item.s_gender }</th >
<th > <a href ="getStudentById.action?id=${item.s_id }" > 修改</a >
</tr >
</c:forEach >
</table >
</body >
</html >
update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<!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 > Insert title here</title >
</head >
<body >
<form action ="${pageContext.request.contextPath }/updateStudent.action" action ="post" >
<input type ="hidden" name ="s_id" value ="${student.s_id }" >
<input type ="text" name ="s_name" value ="${student.s_name }" >
<input type ="text" name ="s_age" value ="${student.s_age }" >
<input type ="text" name ="s_gender" value ="${student.s_gender }" >
<input type ="submit" value ="更新" >
</form >
</body >
</html >