标签:star scheme 元素 cti format 记录 input use utf-8
1.springmvcAjax:
springmvc.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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描!!!--> <context:component-scan base-package="cn.zzsxt"></context:component-scan> <!-- 配置视图解析器 --> <!-- InternalResourceViewResolver:支持JSP视图解析 --> <!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; --> <!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: --> <!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,--> <!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 注解映射器 说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配 ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!-- 注解适配器 说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- springmvc使用<mvc:annotation-driven> --> <!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, --> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 --> <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven> <!-- 自定义类型转换器 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="cn.zzsxt.converter.CustomDateConverter"></bean> </list> </property> </bean> <!-- 处理静态资源 让静态资源可以直接访问--> <!--<mvc:resources mapping="/js/**" location="/js/"/> --> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --> <mvc:default-servlet-handler/> </beans>
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> <!-- 解决post提交乱码问题 --> <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>/*</url-pattern> </filter-mapping> <!-- spring mvc的前端控制器,类似struts2的核心过滤器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- servlet随web容器而启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
UserController.java:
package cn.zzsxt.controller; import java.util.HashMap; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import cn.zzsxt.model.Userinfo; import cn.zzsxt.service.UserService; import cn.zzsxt.service.impl.UserServiceImpl; import cn.zzsxt.vo.ResultMessage; @Controller @RequestMapping("/user") public class UserController { private UserService userService = new UserServiceImpl(); @RequestMapping(value="login",method=RequestMethod.GET) public String login(){ return "login"; } @RequestMapping(value="register",method=RequestMethod.GET) public String register(){ return "register"; } /** * @ResponseBody:将java对象转换为json对象 * @RequestBody:将json对象转换为java对象 * @param userName * @return */ @RequestMapping(value="check",method=RequestMethod.GET) @ResponseBody public Map<String,Object> check(@RequestBody String userName){ boolean isExist = userService.checkUserName(userName); Map<String,Object> map = new HashMap<String,Object>(); map.put("isExist", isExist); return map; } @RequestMapping(value="register",method=RequestMethod.POST) @ResponseBody public ResultMessage register(@RequestBody Userinfo user){ //此处@RequestBody出错的话不加? boolean success = userService.add(user); String message=success?"添加成功!":"添加失败!"; ResultMessage rm = new ResultMessage(); rm.setSuccess(success); rm.setMessage(message); return rm; } }
CustomDateConverter.java:
package cn.zzsxt.converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.springframework.core.convert.converter.Converter; /** * 自定义类型转换器 * @author Think * */ public class CustomDateConverter implements Converter<String, Date> { @Override public Date convert(String source) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = sdf.parse(source); return date; } catch (ParseException e) { e.printStackTrace(); } return null; } }
ResultMessage.java:
package cn.zzsxt.vo; public class ResultMessage { private boolean success;//是否新增成功 private String message;//操作完成后的提升消息 public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘login.jsp‘ starting page</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(function(){ $("#userName").blur(function(){ var userName = $("#userName").val(); $.get("user/check?userName="+userName,function(data){ if(data.isExist==true){ $("#msg").html("<font color=red>用户名已存在!</font>"); $("#submitBtn").attr("disabled",true); }else{ $("#msg").html("<font color=green>用户名可用!</font>"); $("#submitBtn").attr("disabled",false); } }); }); }) </script> </head> <body> <form action="" method="post"> 用户名:<input type="text" name="userName" id="userName"/><span id="msg"></span> <br> 密码:<input type="text" name="userPass"/><br> <input type="submit" value="登录" id="submitBtn"> </form> </body> </html>
register.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘login.jsp‘ starting page</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(function(){ //单机注册按钮 $("#submitBtn").click(function(){ //获取表单元素的值 var userName = $("#userName").val(); var userPass = $("#userPass").val(); var address = $("#address").val(); var birthday = $("#birthday").val(); var jsonData = ‘{"userName":"‘+userName+‘","userPass":"‘+userPass+‘","address":"‘+address+‘","birthday":"‘+birthday+‘"}‘; // alert(jsonData); $.ajax({ type:"POST", url:"user/register", contentType:"application/json", data:jsonData, success: function(msg){ // alert( "Data Saved: " + msg ); alert(msg.message); } }); }); }) </script> </head> <body> <form action="" method="post"> 用户名:<input type="text" name="userName" id="userName"/><span id="msg"></span> <br> 密码:<input type="text" name="userPass" id="userPass"/><br> 地址:<input type="text" name="address" id="address"><br> 生日:<input type="text" name="birthday" id="birthday"><br> <input type="button" value="注册" id="submitBtn"> </form> </body> </html>
2.springmvcInterceptor:
springmvc.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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 注解扫描!!!--> <context:component-scan base-package="cn.zzsxt.controller"></context:component-scan> <!-- 配置视图解析器 --> <!-- InternalResourceViewResolver:支持JSP视图解析 --> <!-- viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar包; --> <!-- prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为: --> <!-- 前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,--> <!-- 则最终返回的jsp视图地址 "WEB-INF/view/hello.jsp" --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 注解映射器 说明 :对类中标记@ResquestMapping的方法进行映射,根据ResquestMapping定义的url匹配 ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器,HandlerMethod对象中封装url对应的方法Method --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> --> <!-- 注解适配器 说明:注解式处理器适配器,对标记@ResquestMapping的方法进行适配。 --> <!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> --> <!-- springmvc使用<mvc:annotation-driven> --> <!-- 自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter, --> <!-- 可用在springmvc.xml配置文件中使用<mvc:annotation-driven>替代注解处理器和适配器的配置。 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 处理静态资源 让静态资源可以直接访问--> <!--<mvc:resources mapping="/jquery-ui-1.12.1.custom/**" location="/jquery-ui-1.12.1.custom/"/> --> <!-- 当在web.xml 中 DispatcherServlet使用 <url-pattern>/</url-pattern> 映射时,能映射静态资源 --> <mvc:default-servlet-handler/> <!--配置拦截器, 多个拦截器,顺序执行 --> <mvc:interceptors> <mvc:interceptor> <!-- 匹配的是url路径, 如果不配置或/**,将拦截所有的Controller --> <mvc:mapping path="/**"/> <bean class="cn.zzsxt.interceptor.MyCustomInterceptor"></bean> </mvc:interceptor> <!-- 当设置多个拦截器时,先按顺序调用preHandle方法,然后逆序调用每个拦截器的postHandle和afterCompletion方法 --> <mvc:interceptor> <!-- 配置拦截的匹配路径 --> <mvc:mapping path="/**"/> <!-- 配置放行的匹配路径 --> <mvc:exclude-mapping path="/user/login"/> <bean class="cn.zzsxt.interceptor.LoginInterceptor"></bean> </mvc:interceptor> </mvc:interceptors> </beans>
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> <!-- 解决post提交乱码问题 --> <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>/*</url-pattern> </filter-mapping> <!-- spring mvc的前端控制器,类似struts2的核心过滤器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 通过contextConfigLocation参数指定配置文件的位置,默认在WEB-INF/查找名称为 [servlet-name]-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- servlet随web容器而启动 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
TestController.java:
package cn.zzsxt.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/t") public class TestController { @RequestMapping("/hello") public String hello(){ System.out.println("TestController中hello()方法被执行了...."); return "success"; } }
UserController.java:
package cn.zzsxt.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import cn.zzsxt.model.Userinfo; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/login",method=RequestMethod.GET) public String login(){ return "login"; } @RequestMapping(value="/login",method=RequestMethod.POST) public String login(Userinfo user,HttpSession session){ if("admin".equals(user.getUserName())&&"admin".equals(user.getUserPass())){ //将用户信息保持到sesssion中 session.setAttribute("loginUser", user); return "redirect:/user/list"; } return "login"; } @RequestMapping(value="/list") public String list(Model model){ //从数据库中查询用户信息 List<Userinfo> list = new ArrayList<Userinfo>(); for (int i = 1; i <=5; i++) { Userinfo user = new Userinfo(i,"zhang"+i,"zhang"+i); list.add(user); } model.addAttribute("list", list); return "list"; } }
LoginInterceptor.java:
package cn.zzsxt.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import cn.zzsxt.model.Userinfo; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { HttpSession session = request.getSession();//获取session //从session中获取用户信息 Userinfo user=(Userinfo)session.getAttribute("loginUser"); if(user!=null){ return true; }else{ response.sendRedirect("login"); return false; } } @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } }
MyCustomInterceptor.java:
package cn.zzsxt.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class MyCustomInterceptor implements HandlerInterceptor { /** * 在控制器方法调用前执行 * 返回值为是否中断 * true,表示继续执行(下一个拦截器或处理器) * false则会中断后续的所有操作,所以我们需要使用response来继续响应后续请求 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception { System.out.println("preHandle()方法被执行了......."); return true; } /** * 在控制器方法调用后,解析视图前调用,我们可以对视图和模型做进一步渲染或修改 * 可在modelAndView中加入数据,比如当前时间 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView) throws Exception { System.out.println("postHandle()方法被执行了....."); } /** * 整个请求完成,即视图渲染结束后调用,这个时候可以做些资源清理工作,或日志记录 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception exception) throws Exception { System.out.println("afterCompletion方法被执行了...."); } }
java:Springmvc框架2(Ajax,Interceptor,)
标签:star scheme 元素 cti format 记录 input use utf-8
原文地址:http://www.cnblogs.com/kuangzhisen/p/7450600.html