SSM:mybatis +Spring +SpringMVC MVC三层架构
JavaSE:认真学习,看视频老师带,入门快
JavaWeb:认真学习,看视频老师带,入门快
SSM框架:研究官方文档,锻炼自学能力,锻炼笔记能力,锻炼项目能力
SpringMVC + Vue +SpringBoot +SpringCloud + Linux
SSM=javaWeb做项目;
Spring: IOC 和 AOP
SpringMVC:SpringMVC的执行流程
SpringMVC:SSM框架整合!
Spring
MVC:模型(dao,service) 视图(view) 控制器(Controller)
dao
service
servlet:转发、重定向
jsp/html
前端 数据传输 实体类
实体类:用户名,密码,生日,爱好,。。。。20个
前端:用户名,密码
pojo:User
vo:UserVo (细化,只存放自己需要的东西)
dto:
JSP:本质是一个Servlet
假设:你的项目的架构,是设计好的,还是演进的?
肯定是演进的
MVC:
MVVM: M V VM ViewModel:双向绑定
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fyaRtd67-1624776864764)(SpringMVC.assets/image-20210622003758209.png)]
Spring的web框架围绕DispatcherServlet设计。DisPatcherServlet的作用将请求分发到不同的处理器。从Spring2.5开始,使用Java5或者以上版本的用户可以采用基于注解的controller声明方式。
Spring MVC框架就像许多其他MVC框架一样,以请求为驱动,围绕一个中心Servlet分派请求及提供其他功能,DisPatcherServlet是一个实际的Servlet(它继承自HttpServlet基类)。
SpringMVC的原理如下图所示:
当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图的结果,将结果返回给中心控制器,再将结果返回给请求者。
HelloSpringMVC
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
beans>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
package com.ljh.servlet;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModeLAndView模型和视图
ModelAndView mv = new ModelAndView();
//封装对象,放在ModelAndView中,Model
mv.addObject("msg","HelloSpringMVC!");
//封装要跳转的视图,放在ModelAndView中
mv.setViewName("hello");//:/WEB-INF/jsp/hello.jsp
return mv;
}
}
<bean id="/hello" class="com.ljh.servlet.HelloController"/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${msg}
11.配置Tomcat启动测试!
可能遇到的问题:访问出现404,排查步骤:
操作步骤:
点击file,进入Project Settings–>Artifacts
打开文件夹路径新建lib文件夹
3. 重启Tomcat即可解决!
小结:看到这个估计很多朋友都能理解其中的原理了,但是我们实际开发中才不会这么写,不然就疯了,还学这个玩意干嘛!我们来看个注解版实现,这才是SpringMVC的精髓,到底有多么简单?
**第一步:新建一个Moudle,添加web支持!**建立包结构com.ljh.controller
第二步:由于Maven可能存在资源过滤的问题,我们将配置完善
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
第三步:在pom.xml文件引入相关的依赖:
主要有Spring框架核心库、Spring MVC、servlet、JSTL等。我们在父依赖中已经引入了!
第四步:配置web.xml
注意点:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlert.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
第五步:添加Spring MVC 配置文件
在resource目录下添加springmvc-servlet.xml配置文件,配置的形式与Spring容器配置基本类似,为了支持基于注解的IOC,设置了自动扫描包的功能,具体配置信息如下:
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="com.ljh.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
在视图解析器中我们把所有的视图都存放在/WEB-INF/目录下,这样可以保证视图安全,因为这个目录下的文件,客户端不能直接访问。
第六步:创建Controller
编写一个Java控制类com.ljh.controller.HelloController,注意编码规范
package com.ljh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController{
@RequestMapping("/h1")
public String hello(Model model){
//封装数据
model.addAttribute("msg","注解");
return "hello";//会被视图解析器处理
}
}
第七步:
在WEB-INF/jsp目录中创建hello.jsp,视图可以直接取出并展示从Controller带回的信息;
可以通过EL表示取出Model中存放的值,或者对象:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${msg}
第八步:配置Tomcat运行
配置Tomcat,开启服务器,访问对应的请求路径
ok,运行成功!
实现步骤其实非常的简单:
使用springMVC必须配置的三大件:
处理器映射器、处理器适配器、视图解析器
通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可,而省去了大段的xml配置
图为SpringMVC的一个较完整的流程图,实线表示SpringMVC框架提供的技术,不需要开发者实现,虚线表示需要开发者实现。
1.DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心,用户发出请求,DispatcherServlet接收请求并拦截请求。
HandlerMapping,HandlerMapping根据请求url查找Handler.
在这里先听一边原理,不理解没有关系,我们马上来写一个对应的代码实现,如果不明白就写10遍,没有笨人,只有懒人。
我们来看看有哪些方式可以实现:
Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法:
//实现该接口的类获得控制器功能
public interface Controller {
//处理请求且返回一个模型与视图对象
ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
package com.ljh.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg","controller");
modelAndView.setViewName("hello");
return modelAndView;
}
}
<bean id="/h2" class="com.ljh.controller.HelloController"/>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
${msg}
5、配置Tomcat运行测试,我这里没有项目发布名配置的就是一个/,所以请求不用加项目名,OK!
说明:
使用注解@Controller
@Controller注解类型用于声明Spring类的实例是一个控制器(在讲IOC时还提到了另外三个注解)
Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描
<context:component-scan base-package="com.ljh.controller"/>
package com.ljh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController2 {
@RequestMapping("/h2")
public String hello(Model model){
//封装数据
model.addAttribute("msg","注解");
return "hello";//会被视图解析器处理
}
}
运行tomcat测试
可以发现,我们的两个请求都可以指向一个视图,但是页面结果的结果是不一样的,从这里可以看出视图是被复用的,而控制器与视图之间是弱耦合关系。
这个网站不错,狂神
@RequestMapping
@Controller
public class HelloController2 {
@RequestMapping("/h2")
public String hello(Model model){
//封装数据
model.addAttribute("msg","注解");
return "hello";//会被视图解析器处理
}
}
访问路径:http://localhost:8080/项目名/h2
@Controller
@RequestMapping("/c3")
public class HelloController3 {
@RequestMapping("/t1")
public String test(Model model){
model.addAttribute("msg","requestMapping");
return "hello";
}
}
访问路径:http://localhost:8080/项目名/c3/h2,需要先指定类的路径再指定方法的路径;
概念
Restful就是资源定位及资源操作的风格,不是标准的也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
功能
**传统方式操作资源:**通过不同的参数来实现不同的效果!方法单一,post和get
**使用RESTful操作资源:**可以通过不同的请求方式来实现不同的效果!如下:请求地址一样,但是功能可以不同!
学习测试
@Controller
public class RestFulController {
}
@Controller
public class RestFulController {
//原来的:http://localhost:8080/add?a=1&b=2
@RequestMapping("/add")
public String test(int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "hello";
}
//RestFul:http://localhost:8080/add/1/2
//映射访问路径
@RequestMapping("/add/{a}/{b}")
public String test2(@PathVariable int a, @PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "hello";
}
}
@RequestMapping("/add/{a}/{b}")
public String test3(@PathVariable int a, @PathVariable String b, Model model){
String res = b+a;
model.addAttribute("msg","结果为"+res);
return "hello";
}
用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET,POST,HEAD,OPTIONS,PUT,PATCH,DELETE,TRACE等
我们来测试一下:
@RequestMapping(value="/hello",method = RequestMethod.POST)
public String test4(Model model){
model.addAttribute("msg","测试方法");
return "hello";
}
@RequestMapping(value="/hello",method = RequestMethod.GET)
public String test4(Model model){
model.addAttribute("msg","测试方法");
return "hello";
}
Spring MVC的@RequestMapping注解能够处理HTTP请求的方法,比如GET,PUT,POST,DELETE一级PATCH。
所有的地址栏请求默认都会是HTTP GET类型的。
方法级别的注解变体有如下几个:组合注解
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
@GetMapping是一个组合注解
它所扮演的是@RequestMapping(method = RequestMethod.GET)的一个快捷方式。
平时使用的会比较多!
@GetMapping("/hello")
public String test4(Model model){
model.addAttribute("msg","测试方法");
return "hello";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
@PostMapping("/add/{a}/{b}")
public String test5(@PathVariable int a, @PathVariable String b, Model model){
String res = b+a;
model.addAttribute("msg","结果为"+res);
return "hello";
}
设置ModelAndView对象,根据view的名称,和视图解析器跳到指定的页面。
页面:{视图解析器前缀}+viewName + {视图解析器后缀}
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
对应的controller类
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg","controller");
modelAndView.setViewName("hello");
return modelAndView;
}
}
通过设置ServletAPI,不需要试图解析器
package com.ljh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Controller
public class ResultGo {
@RequestMapping("/m1/t1")
public String test(HttpServletRequest request, HttpServletResponse response){
HttpSession session = request.getSession();
System.out.println(session.getId());
return "hello";
}
@RequestMapping("/m1/t2")
public void test2(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().println("fkdalaslf");
}
@RequestMapping("/m1/t3")
public void test3(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.sendRedirect("/a.jsp");
}
@RequestMapping("/m1/t4")
public void test4(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.sendRedirect("/a.jsp");
request.setAttribute("msg","/dfad");
request.getRequestDispatcher("/WEB-INF/jsp/hello.jsp").forward(request,response);
}
}
通过SpringMVC来实现转发和重定向-无需视图解析器;
测试前,需要将视图解析器注释掉
package com.ljh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//转发
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//转发二
return "forward:/WEB-INF/jsp/test.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
通过SpringMVC来实现转发和重定向-需要视图解析器;
重定向,不需要视图解析器,本质就是重新请求一个新地方嘛,所以注意路径问题。
可以重定向到另外一个请求实现。
package com.ljh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//转发
return "hello";
}
@RequestMapping("/rsm2/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
提交数据:http://localhost:8080/add?a=1&b=3
处理方法:
@RequestMapping("/add")
public String test(int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "hello";
}
提交数据:http://localhost:8080/add?aa=1&b=3
@RequestMapping("/add")
public String test(@RequestParam("aa") int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","结果为"+res);
return "hello";
}
要求提交的表单域和对象的属性名一致,参数使用对象即可
package com.ljh.pojo;
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
@RequestMapping("/user")
public String test4(User user){
System.out.println(user);
//重定向
return "hello";
}
后台输出:User{id=3, name=‘ab’, age=1}
说明:如果使用对象的化,前端传递的参数名和对象名必须一直,否则就是null。
第一种:通过ModelAndView
前面一直都是如此,就不过多解释
public class HelloController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("msg","controller");
modelAndView.setViewName("hello");
return modelAndView;
}
}
第二种:通过ModelMap
ModelMap
@GetMapping("/t2")
public String test2(String name, ModelMap modelMap){
//1.接收前端参数
System.out.println("接收前端的参数为:"+name);
//2.将返回的结果传递给前端,Model
modelMap.addAttribute("msg",name);
//3.视图跳转
return "test";
}
第三种:通过Model
Model
@GetMapping("/t1")
public String test(String name, Model model){
//1.接收前端参数
System.out.println("接收前端的参数为:"+name);
//2.将返回的结果传递给前端,Model
model.addAttribute("msg",name);
//3.视图跳转
return "test";
}
就对于新手而言简单来说使用的区别就是:
Model 只有寥寥几个方法只适合用于储存数据,建华了新手对于Model对象的操作和理解
ModelMap 继承了LinkedMap,除了实现了自身的一些方法,同样的继承LinkedMap的方法和特性
ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转
当然更多的以后开发考虑的更多的是性能和优化,就不能单单仅限于此的了解。
使用80%的时间大号扎实的基础,剩下18%的时间研究框架,2%的时间去学点英文,框架的官方文档永远是最好的教程。
测试步骤
package com.ljh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class EncodingController {
//过滤器解决乱码
@GetMapping("/e/t1")
public String test1(String name, Model model){
model.addAttribute("msg",name);
return "test";
}
}
以前乱码问题通过过滤器解决,
package com.ljh.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
chain.doFilter(request,response);
}
public void destroy() {
}
}
web.xml增加内容
<filter>
<filter-name>encodingfilter-name>
<filter-class>com.ljh.filter.EncodingFilterfilter-class>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/url-pattern>
filter-mapping>
而SpringMVC给我们提供了一个过滤器,可以在web.xml中配置,修改了xml文件需要重启服务器!
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
表单form的post请求依然乱码,请改tomcat的配置
有些极端情况下,这个过滤器对get的支持不好。
处理方法:
<Connector port="8080" URIEncoding="utf-8" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
package com.ljh.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
public class GenericEncodingFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//处理response的字符编码
HttpServletResponse myResponse = (HttpServletResponse)response;
myResponse.setContentType("text/html;charset=UTF-8");
//转型为与协议相关对象
HttpServletRequest httpServletRequest = (HttpServletRequest)request;
//对request包装增强
HttpServletRequest myRequest = new MyRequest(httpServletRequest);
chain.doFilter(request,response);
}
public void destroy() {
}
}
class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
//是否编码的标记
private boolean hasEncode;
//定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
public MyRequest(HttpServletRequest request) {
super(request);//super必须写
this.request = request;
}
@Override
public Map getParameterMap(){
String method = request.getMethod();
if(method.equalsIgnoreCase("post")){
//post请求
try{
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
}else if(method.equalsIgnoreCase("get")){
//get请求
Map<String,String[]> parameterMap = request.getParameterMap();
if(!hasEncode){
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if(values != null){
for (int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一个值
@Override
public String getParameter(String name){
Map<String,String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if(values == null){
return null;
}
return values[0];//取回参数的第一个值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
<filter>
<filter-name>encodingfilter-name>
<filter-class>com.ljh.filter.GenericEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
这个自定义乱码过滤器算是终极大招了,一般springmvc自带过滤器应该够了,如果不行,可以用它。
在JavaScript语言中,一切都是对象。因此,任何JavaScript支持的类型都可以通过JSON来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:
JSON键值对是用来保存JavaScript对象的一种方式,和JavaScript对象的写法也大同小异,键/值对组合中键名写在前面并用双引号""包裹,使用冒号:分隔,然后紧接着值:
{"name":"ljh"}
{"age":"3"}
{"sex":"男"}
很多人搞不清楚JSON和JavaScript对象的关系,甚至连谁是谁都不清楚,其实,可以这么理解:
var obj = {a:'Hello',b:'World'};//这是一个对象,注意键名也是可以使用引号包裹的
var json = '{"a":"Hello","b":"World"}';//这是一个JSON字符串,本质是一个字符串
JSON和JavaScript对象互转
var obj = JSON.parse('{"a":"Hello","b":"World"}');
//结果是{a:'Hello',b:'World'}
var json = JSON.stringfy({a:'Hello',b:'World'});
//结果是'{"a":"Hello","b":"World"}'
代码测试
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
//编写一个javascript对象
var user = {
name:"ljh",
age:3,
sex:"男"
};
//将js对象转换为json对象
var json = JSON.stringify(user);
console.log(json);
console.log(user);
//将JSON对象转换为javascript对象
var obj = JSON.parse(json);
console.log(obj);
</script>
</head>
<body>
</body>
</html>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.8version>
dependency>
记得添加了依赖需要在Artifact里面的lib中添加进去
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlert.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/url-pattern>
filter-mapping>
web-app>
springmvc-servlert.xml
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<context:component-scan base-package="com.ljh.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
package com.ljh.pojo;
public class User {
private int id;
private String name;
private int age;
public User() {
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
package com.ljh.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljh.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class UserCntroller {
@RequestMapping("/j1")
@ResponseBody
public String json1(){
//创建一个对象
User user = new User(1,"ljh",3);
return user.toString();
}
//produces:指定响应体返回类型和编码
@RequestMapping(value = "/j2",produces = "application/json;charset=utf-8")
@ResponseBody
public String json2() throws JsonProcessingException {
//jackson,ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
//创建一个对象
User user = new User(1,"李",3);
String s = objectMapper.writeValueAsString(user);
return s;
}
}
http://localhost:8080/j1
//produces:指定响应体返回类型和编码
@RequestMapping(value = "/j2",produces = "application/json;charset=utf-8")
【注意:使用json记得处理乱码问题】
乱码统一解决
上一种方法比较麻烦,如果项目中有许多请求则每一个都要添加,可以通过Spring配置统一指定,这样就不用每次都去处理了!
我们可以在springmvc的配置文件上添加一段消息StringHttpMessageConverter转换配置!
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
返回json字符串统一解决
在类上使用@RestController,这样子,里面所有的方法都只会返回json字符串了,不用在每一个都添加@ResonseBody!我们在前后端分离开发中,一般都使用@RestController,十分便捷!
@RestController
public class UserCntroller {
@RequestMapping("/j1")
public String json1(){
//创建一个对象
User user = new User(1,"ljh",3);
return user.toString();
}
}
启动tomcat测试,结果都正常输出!
增加一个新的方法
@RestController
public class UserCntroller {
@RequestMapping("/j4")
public String json4() throws JsonProcessingException {
//jackson,ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
ArrayList<User> list = new ArrayList<User>();
//创建一个对象
User user = new User(1,"李",3);
User user1 = new User(2,"李",3);
User user2 = new User(3,"李",3);
list.add(user);
list.add(user1);
list.add(user2);
String s = objectMapper.writeValueAsString(list);
return s;
}
}
增加一个新的方法
@RequestMapping("/j5")
public String json5() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
//创建时间一个对象,java.util.Date
Date date = new Date();
String s = objectMapper.writeValueAsString(date);
return s;
}
运行结果:
解决方案:取消timestamps形式,自定义时间格式
@RequestMapping("/j6")
public String json6() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
//不使用时间戳的方式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定日期格式
objectMapper.setDateFormat(sdf);
Date date = new Date();
String s = objectMapper.writeValueAsString(date);
return s;
}
运行结果,成功的输出了时间!
如果要经常使用的话,这样是比较麻烦的,我们可以将这些代码封装到一个工具类中;我们去编写下
package com.ljh.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.text.SimpleDateFormat;
public class JsonUtils {
public static String getJson(Object object){
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
public static String getJson(Object object,String dateFormat){
ObjectMapper objectMapper = new ObjectMapper();
//不使用时间戳的方式
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//指定日期格式
objectMapper.setDateFormat(sdf);
try {
return objectMapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
大功告成,完美!
fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json转换方法很多,最后的实现结果都是一样的。
fastjson的pom依赖!
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.60version>
dependency>
fastjson三个主要的类:
代码测试
@RequestMapping("/j7")
public String json7(){
ArrayList<User> list = new ArrayList<User>();
//创建一个对象
User user = new User(1,"李",3);
User user1 = new User(2,"李",3);
User user2 = new User(3,"李",3);
list.add(user);
list.add(user1);
list.add(user2);
System.out.println("=========Java对象 转 JSON字符串===========");
String s = JSON.toJSONString(list);
String s1 = JSON.toJSONString(user);
System.out.println("=========JSON字符串 转 Java对象===========");
User user3 = JSON.parseObject(s1, User.class);
System.out.println("=========JSON.parseObject(s1, User.class)====>"+user3);
System.out.println("=========JSON字符串 转 Java数组===========");
List<User> list1 = JSON.parseArray(s, User.class);
System.out.println("=========JSON.parseArray(s, User.class)====>"+list1);
System.out.println("=========JSON字符串 转 JSON字符串数组===========");
JSONArray list2 = JSON.parseArray(s);
System.out.println("=========JSON.parseArray(s)====>"+list2);
System.out.println("========Java对象 转 JSON对象========");
JSONObject jsonObject = (JSONObject)JSON.toJSON(user2);
System.out.println("(JSONObject)JSON.toJSON(user2)====>"+jsonObject);
System.out.println("==========JSON对象 转 Java对象============");
User user4 = JSON.toJavaObject(jsonObject, User.class);
System.out.println("JSON.toJavaObject(jsonObject, User.class)==>"+user4);
return "Hello";
}
这种工具类,我们只需要掌握使用就好了,在使用的时候再根据具体的业务去找对应的实现。和以前的commons-io那种工具包一样,拿来用就好了!
环境:
要求:
创建一个存放数据数据的数据库表
CREATE DATABASE 'ssmbuild';
USE 'ssmbuild';
DROP TABLE IF EXISTS 'books';
CREATE TABLE `books` (
`bookID` int(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
`bookName` varchar(100) NOT NULL COMMENT '书名',
`bookCounts` int(11) NOT NULL COMMENT '数量',
`detail` varchar(200) NOT NULL COMMENT '描述',
PRIMARY KEY (`bookID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `ssmbuild`.`books`(`bookID`, `bookName`, `bookCounts`, `detail`) VALUES (1, 'JAVA', 1, '从入门到放弃');
INSERT INTO `ssmbuild`.`books`(`bookID`, `bookName`, `bookCounts`, `detail`) VALUES (2, 'MySQL', 10, '删库跑路');
INSERT INTO `ssmbuild`.`books`(`bookID`, `bookName`, `bookCounts`, `detail`) VALUES (3, 'Linux', 5, '从进门到进牢');
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.11version>
<scope>testscope>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.47version>
dependency>
<dependency>
<groupId>com.mchangegroupId>
<artifactId>c3p0artifactId>
<version>0.9.5.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.1version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.2version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.2.0.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.1.9.RELEASEversion>
dependency>
dependencies>
<build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
<resource>
<directory>src/main/resourcesdirectory>
<includes>
<include>**/*.propertiesinclude>
<include>**/*.xmlinclude>
includes>
<filtering>falsefiltering>
resource>
resources>
build>
com.ljh.pojo
com.ljh.controller
com.ljh.dao
com.ljh.service
mybatis-config.xml
configuration>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
beans>
jdbc.driver=com.mysql.jdbc.Driver
#如果使用的是MySQL8.0+,需要加上失去的配置: &serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8&useSSL=true
jdbc.username=root
jdbc.password=123456
<configuration>
<typeAliases>
<package name="com.ljh.pojo"/>
typeAliases>
<mappers>
<mapper class="com.ljh.dao.BookMapper"/>
mappers>
configuration>
package com.ljh.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
}
package com.ljh.dao;
import com.ljh.pojo.Books;
import java.util.List;
public interface BookMapper {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBooksById(int id);
//查询全部的书
List<Books> queryAllBooks();
}
<mapper namespace="com.ljh.dao.BookMapper">
<insert id="addBook" parameterType="Books">
insert into books (bookName,bookCounts,detail) values (#{bookName},#{bookCounts},#{detail})
insert>
<delete id="deleteBookById" parameterType="int">
delete from books where bookID=#{bookID}
delete>
<update id="updateBook" parameterType="Books">
update books set bookName =#{bookName},bookCounts=#{bookCounts},detail=#{detail} where bookID=#{bookID}
update>
<select id="queryBooksById" resultType="Books">
select * from books where bookID=#{bookID}
select>
<select id="queryAllBooks" resultType="Books">
select * from books
select>
mapper>
接口:
package com.ljh.service;
import com.ljh.pojo.Books;
import java.util.List;
public interface BookService {
//增加一本书
int addBook(Books books);
//删除一本书
int deleteBookById(int id);
//更新一本书
int updateBook(Books books);
//查询一本书
Books queryBooksById(int id);
//查询全部的书
List<Books> queryAllBooks();
}
实现类:
package com.ljh.service;
import com.ljh.dao.BookMapper;
import com.ljh.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBookById(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBooksById(int id) {
return bookMapper.queryBooksById(id);
}
public List<Books> queryAllBooks() {
return bookMapper.queryAllBooks();
}
}
ok,到此,底层需求操作编写完毕!
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
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
https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<property name="autoCommitOnClose" value="false"/>
<property name="checkoutTimeout" value="10000"/>
<property name="acquireRetryAttempts" value="2"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.ljh.dao"/>
bean>
beans>
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.ljh.service"/>
<bean id="BookServiceImpl" class="com.ljh.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
tx:advice>
<aop:config>
<aop:pointcut id="txPointCut" expression="execution(* com.ljh.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
aop:config>
beans>
Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!对吧!
SpringMVC层
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
web-app>
<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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<context:component-scan base-package="com.ljh.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
<import resource="classpath:spring-mvc.xml"/>
beans>
配置文件,暂时结束!Controller和视图层编写
package com.ljh.controller;
import com.ljh.pojo.Books;
import com.ljh.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
//controller调用service层
@Autowired
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model){
List<Books> list = bookService.queryAllBooks();
model.addAttribute("list",list);
return "allBook";
}
@RequestMapping("/toAddBook")
//跳转到增加书籍页面
public String toAddBook(){
return "addBook";
}
@RequestMapping("/addBook")
//增加书籍请求
public String addBook(Books books){
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
@RequestMapping("/toUpdateBook")
//跳转到修改书籍页面
public String toUpdateBook(int id,Model model){
Books books = bookService.queryBooksById(id);
model.addAttribute("books",books);
return "updateBook";
}
@RequestMapping("/updateBook")
//修改书籍请求
public String updateBook(Books books){
System.out.println(books);
bookService.addBook(books);
return "redirect:/book/allBook";
}
@RequestMapping("/deleteBook")
//删除书籍请求
public String deleteBook(int id){
bookService.deleteBookById(id);
return "redirect:/book/allBook";
}
@RequestMapping("/queryBook")
//删除书籍请求
public String queryBook(String queryName,Model model){
List<Books> list = bookService.queryBooks(queryName);
if(list.size()==0){
model.addAttribute("error","未查到");
}
model.addAttribute("list",list);
return "allBook";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
首页
进入书籍页面
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
书籍展示
<%-- --%>
<%-- --%>
<%-- --%>
<%-- --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
新增书籍
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
修改书籍
配置Tomcat,进行运行!
别目前为止,这个SSM项目整合已经完全OK了,可以直接运行进行测试!这个练习十分的重要,需要保证,不看任何东西,自己也可以完整的实现出来
这个是一个完整的SSM整合案例,一定要烂熟于胸!!!
伪造Ajax
我们可以使用前端的一个标签来伪造一个ajax的样子。iframe标签
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe测试体验页面无刷新title>
<script type="text/javascript">
function go() {
var url = document.getElementById("url").value;
document.getElementById("iframe1").src=url;
}
script>
head>
<body>
<div>
<p>请输入地址:p>
<p>
<input type="text" id="url" value="https://www.baidu.com">
<input type="submit" value="提交" onclick="go()">
p>
div>
<div>
<iframe id="iframe1" style="width: 100%;height: 500px">iframe>
div>
body>
html>
利用AJAX可以做:
jQuery.ajax
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:contex="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<contex:component-scan base-package="com.ljh.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
package com.ljh.controller;
import com.ljh.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
public class AjaxController {
@RequestMapping("/t1")
public String test(){
return "hello";
}
@RequestMapping("/a1")
public void test1(String name, HttpServletResponse response) throws IOException {
if("ljh".equals(name)){
response.getWriter().println("true");
}else {
response.getWriter().println("false");
}
}
@RequestMapping("/a2")
public List<User> test2(String name) throws IOException {
ArrayList<User> list = new ArrayList<User>();
list.add(new User("ljh",1,"男"));
list.add(new User("ljh1",2,"男"));
return list;
}
@RequestMapping("/a3")
public String test3(String name,String pwd) throws IOException {
String msg = "";
if(name != null){
if("admin".equals(name)){
msg = "ok";
}else {
msg = "用户名有误";
}
}
if(pwd != null){
if("123456".equals(pwd)){
msg = "ok";
}else {
msg = "密码有误";
}
}
return msg;
}
}
写一个User类
package com.ljh.pojo;
public class User {
private String name;
private int age;
private String sex;
public User() {
}
public User(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
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;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
<%--
Created by IntelliJ IDEA.
User: 86136
Date: 2021/6/26
Time: 20:07
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
<%-- 失去焦点的时候,发起一个请求到后台--%>
用户名:
<%--
Created by IntelliJ IDEA.
User: 86136
Date: 2021/6/26
Time: 23:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
姓名
年龄
性别
<%----%>
<%--
Created by IntelliJ IDEA.
User: 86136
Date: 2021/6/27
Time: 0:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
用户名:
用户名:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>
SpringMVC的处理器拦截器类似与Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理,开发者可以自己定义一些拦截器来实现特定的功能。
**过滤器与拦截器的区别:**拦截器是AOP思想的具体应用。
过滤器
拦截器
那如何实现拦截器呢?
想要自定义拦截器,必须实现HandlerInterceptor接口。
package com.ljh.config;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
//return true;执行下一个拦截器,放行
//return true;不执行下一个拦截器
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("处理前");
return true;
}
//日志
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable ModelAndView modelAndView) throws Exception {
System.out.println("处理后");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
@Nullable Exception ex) throws Exception {
System.out.println("清理");
}
}
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.ljh.config.MyInterceptor"/>
mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/user/**"/>
<bean class="com.ljh.config.LoginInterceptor"/>
mvc:interceptor>
mvc:interceptors>
package com.ljh.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@RequestMapping("/t1")
public String test(){
System.out.println("TestController==>test()执行了");
return "ok";
}
}
一、导入文件上传的jar包,commons-fileupload,Maven会自动帮我们导入他的依赖包commons-io包;
<dependencies>
<dependency>
<groupId>commons-fileuploadgroupId>
<artifactId>commons-fileuploadartifactId>
<version>1.3.3version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
dependency>
dependencies>
二、配置bean:multipartResolver
【注意!!!!这个bean的id必须为multipartResolver,否则上次文件会报400的错误!,在这里栽过坑,教训!】
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
bean>
CommonsMultipartFile的常用方法:
我们去实际测试一下
三、编写前端页面
四、Controller
package com.ljh.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@RestController
public class FileCnotroller {
@RequestMapping("/upload")
public String test(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {
//获取文件名:file.getOriginalFilename();
String uploadFilename = file.getOriginalFilename();
//如果文件名为空,直接回到首页!
if("".equals(uploadFilename)){
return "redirect:/index.jsp";
}
System.out.println("上传文件名:"+uploadFilename);
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
//如果路径不存在,创建一个
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
System.out.println("上传文件保存地址:"+realPath);
InputStream is = file.getInputStream();//文件输入流
FileOutputStream os = new FileOutputStream(new File(realPath, uploadFilename));//文件输出流
//读取写出
int len=0;
byte[] buffer = new byte[1024];
while ((len=is.read(buffer))!=-1){
os.write(buffer,0,len);
os.flush();
}
os.close();
is.close();
return "redirect:/index.jsp";
}
/**
* transferTo方法
* @param file
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/upload2")
public String fileUpload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException {
//上传路径保存设置
String path = request.getServletContext().getRealPath("/upload");
File realPath = new File(path);
if(!realPath.exists()){
realPath.mkdir();
}
//上传文件地址
System.out.println("上传文件保存地址:"+realPath);
//通过CommonsMultipaartFile的方法直接写文件(注意这个时候)
file.transferTo(new File(realPath+"/"+file.getOriginalFilename()));
return "redirect:/index.jsp";
}
@RequestMapping("/download")
public String downloads(HttpServletResponse response,HttpServletRequest request) throws IOException {
//要下载的图片地址
String path = request.getServletContext().getRealPath("/upload");
String fileName = "dd.txt";
//1.设置response响应头
response.reset();//设置页面不缓存,清空buffer
response.setCharacterEncoding("UTF-8");//字符编码
response.setContentType("multipart/form-data");//二进制传输数据
//设置响应头
response.setHeader("Content-Disposition","attachment,fileName="+ URLEncoder.encode(fileName,"UTF-8"));
File file = new File(path, fileName);
//2.读取文件--输入流
FileInputStream input = new FileInputStream(file);
//3.写出文件--输出流
ServletOutputStream out = response.getOutputStream();
byte[] buff = new byte[1024];
int index = 0;
//4.执行写出操作
while ((index=input.read(buff))!=-1){
out.write(buff,0,index);
out.flush();
}
out.close();
input.close();
return "ok";
}
}