SpringMVC 주해 와 비 주해
20645 단어 spring
[img]http://dl2.iteye.com/upload/attachment/0093/5380/60ef9462-e498-3385-a8ca-4344c3bb073a.jpg[/img]
웹. xml 파일 에 springmvc 전송 스케줄 러 servlet 와 Date 형식 매개 변수의 자동 변환 설정
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
springmvc
org.springframework.web.servlet.DispatcherServlet
springmvc
*.do
index.jsp
spring 프로필 을 작성 하여 맵 프로세서 와 컨트롤 러 또는 차단 기 를 설정 합 니 다.
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
testController
그리고 springmvc 컨트롤 러 를 작성 합 니 다.
package cn.sh.springmvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class TestController extends AbstractController {
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
HttpServletResponse arg1) throws Exception {
System.out.println("hello springmvc");
return new ModelAndView("homepage/index");
}
}
http://localhost:8080/springmvc- 1 / hello. do 방문 가능 합 니 다.
주해 류 설정 springmvc 사용 하기
[img]http://dl2.iteye.com/upload/attachment/0093/5390/c039b5c3-dbd8-3a9d-82f6-aa9cd1885cc8.jpg[/img]
웹. xml 에 spring 의 중앙 컨트롤 러 를 설정 합 니 다.
또한 초기 화 매개 변 수 를 지정 하여 spring 프로필 의 경 로 를 설정 할 수 있 습 니 다.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLoaction
classpath:springmvc.xml
springmvc
*.do
index.jsp
springmvc - servlet. xml 파일 작성
xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
컨트롤 러 작성 (struts 의 action 과 유사)
아래
전통 적 인 요구
비동기 요청 이 있 습 니 다.
파일 업로드 (jar 와 프로필 업로드 해상도 추가 주의)
리 셋 요청
package cn.sh.springmvc;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;
import cn.sh.springmvc.model.Person;
import cn.sh.springmvc.model.User;
@Controller // springmvc
@RequestMapping("/homepage") // struts2 namespace
public class TestController{
@RequestMapping("/hello.do") //
public String hello(){
System.out.println(" ");
return "homepage/index";
}
//
/**
* :HttpServletRequest
* @param request
* @return
*/
@RequestMapping("/toPesron.do")
public String toPerson(HttpServletRequest request){
String result=request.getParameter("name");
System.out.println(result);
return "homepage/index";
}
/**
* :
* @param name
* @param age
* @return
*/
@RequestMapping("/toPesron1.do")
public String toPerson1(String name,Integer age,Date birthday){ //
System.out.println(name);
System.out.println(age);
System.out.println(birthday);
return "homepage/index";
}
/**
* set ,
* set
* @param person
* @return
*/
@RequestMapping("/toPesron2.do")
public String toPerson2(Person person,User user){ //
System.out.println(person);
System.out.println(user);
return "homepage/index";
}
/**
*
* @param name
* @return
*/
@RequestMapping("/toPerson3.do")
public String upload(String[] name){ //
System.out.println(Arrays.toString(name));
return "homepage/index";
}
/**
* jsp
*
* @throws ParseException
*/
@RequestMapping("/toPerson4.do")
public ModelAndView toPerson4() throws ParseException{
Person person=new Person();
person.setName("james");
person.setAge(28);
person.setAddress("maiami");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date birthday=sdf.parse("1985-01-22");
person.setBirthday(birthday);
Map map=new HashMap();
map.put("p",person);
return new ModelAndView("index",map);
}
/**
*
* @param map
* @return
* @throws ParseException
*/
@RequestMapping("/toPerson5.do")
public String toPerson5(Map map) throws ParseException{
Person person=new Person();
person.setName("james");
person.setAge(28);
person.setAddress("maiami");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date birthday=sdf.parse("1985-01-22");
person.setBirthday(birthday);
map.put("p",person);
return "index";
}
/**
*
* @param model
* @return
* @throws ParseException
*/
@RequestMapping("/toPerson6.do")
public String toPerson6(Model model) throws ParseException{
Person person=new Person();
person.setName("james");
person.setAge(28);
person.setAddress("maiami");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date birthday=sdf.parse("1985-01-22");
person.setBirthday(birthday);
model.addAttribute("p", person);
return "index";
}
/**
*
* @param name
* @param response
* @throws ParseException
*/
@RequestMapping("/ajax.do")
public void ajax(String name,HttpServletResponse response) throws ParseException{
String result="hello"+name;
try {
response.getWriter().write(result);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @param name
* @param out
* @throws ParseException
*/
@RequestMapping("/ajax1.do")
public void ajax1(String name,PrintWriter out) throws ParseException{
String result="hello"+name;
try {
out.print(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@RequestMapping("/toajax.do")
public String toajax() throws ParseException{
return "ajax";
}
@RequestMapping("/toFrom.do")
public String toFrom() throws ParseException{
return "form";
}
@RequestMapping(value="/toPerson7.do",method=RequestMethod.POST)
public String toPerson7(Person person){ //
System.out.println(person);
return "homepage/index";
}
@RequestMapping(value="/toPerson8.do",method=RequestMethod.POST)
public String toPerson8(Person person,HttpServletRequest request) throws FileNotFoundException{ //
System.out.println(person);
MultipartHttpServletRequest rm=(MultipartHttpServletRequest)request;
CommonsMultipartFile cfile=(CommonsMultipartFile)rm.getFile("image");// input
byte[] bfile=cfile.getBytes();
String fileName="";
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmssSSS");
fileName=format.format(new Date());
fileName+=(int)(Math.random()*1000); //3
//
String origFileName=cfile.getOriginalFilename();
//
String suffix=origFileName.substring(origFileName.lastIndexOf("."));
//
String path=request.getSession().getServletContext().getRealPath("/");
System.out.println(path);
System.out.println(request.getServletPath());
OutputStream out=new FileOutputStream(new File(path+"/upload/"+fileName+suffix));
try {
out.write(bfile);
out.flush();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "homepage/index";
}
@RequestMapping("/redtoFrom.do")
public String redirectToFrom() throws ParseException{
return "redirect:toFrom.do"; // namespace;
}
@RequestMapping("/redtoFrom1.do")
public String redirectToFrom1() throws ParseException{
// "/"
return "redirect:/test/toFrom.do"; // namespace;
}
/**
*
* @param binder
*/
@InitBinder
public void initBinder(ServletRequestDataBinder binder){
// 2012-12-02 2012-22-12( 2013-10-12 )
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
}
}
여러 컨트롤 러 의 상호 참조
package cn.sh.springmvc;
import java.text.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller // springmvc
@RequestMapping("/test") // struts2 namespace
public class TestController1{
@RequestMapping("/toFrom.do")
public String toFrom() throws ParseException{
return "form";
}
}
사용자 정의 차단기
package cn.sh.springmvc.interceptor;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class MyInterceptor implements HandlerInterceptor {
/**
* :
* : try catch finally
*/
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception ex)
throws Exception {
System.out.println("afterCompletion");
ex.printStackTrace();
}
/**
* :control ,
* model ( )
*/
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView mv) throws Exception {
System.out.println("postHandle....");
Map map=mv.getModel();
map.put("test", "append something");
}
/**
* : control
* true: control
* false: control
* Object: control
*
*/
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2) throws Exception {
System.out.println("preHandle....");
return true;
}
}
두 매개 변수 실체 클래스
package cn.sh.springmvc.model;
import java.util.Date;
public class User {
private String name;
private Integer age;
private String address;
private Date birthday;
//get set ..
@Override
public String toString() {
return this.name+"/"+this.age+"/"+this.address+"/"+this.birthday;
}
}
package cn.sh.springmvc.model;
import java.util.Date;
public class Person {
private String name;
private Integer age;
private String address;
private Date birthday;
//get set...
@Override
public String toString() {
return this.name+"/"+this.age+"/"+this.address+"/"+this.birthday;
}
}
jsp 몇 개
form.jsp
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<br> $(function(){<br> $("#mybutton").click(<br> function(){<br> $.ajax({<br> url:"homepage/ajax1.do",<br> type:"POST", <br> dataType:"text",<br> data:{<br> name:"zhangh"<br> },<br> success:function(responseText){<br> alert(responseText);<br> },<br> error:function(){<br> alert("system error");<br> }<br> }); <br> } <br> );<br> });<br><br>
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
thymeleaf로 HTML 페이지를 동적으로 만듭니다 (spring + gradle)지난번에는 에서 화면에 HTML을 표시했습니다. 이번에는 화면을 동적으로 움직여보고 싶기 때문에 입력한 문자를 화면에 표시시키고 싶습니다. 초보자의 비망록이므로 이상한 점 등 있으면 지적 받을 수 있으면 기쁩니다! ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.