I need to add multiple controllers to my Spring MVC project which only has one right now. My current project only has one SpringDispatcher in the web.xml and it maps the
/
to the '/' of the controllers
#RequestMapping(value = "/")
start-up controller. Because everything is in the one web.xml and there are no other xml files that do any dispatcher mapping, should I not be able to just add a new
/
with a different controller pattern to the web.xml? Below are the web.xml and the one working controller.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>SpringMvcJdbcTemplate</display-name>
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SpringDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>net.codejava.spring</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
HomeController.java
package net.codejava.spring.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.codejava.spring.dao.ContactDAO;
import net.codejava.spring.dao.ContactDAODS;
import net.codejava.spring.model.Contact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* This controller routes accesses to the application to the appropriate
* hanlder methods.
* #author www.codejava.net
*
*/
#Controller
public class HomeController {
#Autowired
private ContactDAO contactDAO;
#Autowired
private ContactDAODS contactDAODS;
#RequestMapping(value = "/")
public ModelAndView login() {
Contact contact = new Contact();
ModelAndView model = new ModelAndView("login");
model.addObject("contact", contact);
return model;
}
#RequestMapping(value = "/loginContact", method = RequestMethod.POST)
public ModelAndView loginContact(#ModelAttribute Contact loginContact) {
ModelAndView model;
Contact contact = contactDAO.login(loginContact);
if(contact != null)
{
model = new ModelAndView("menu");
return model;
}
else
{
Map<String, String> message = new HashMap<String, String>();
message.put("message", "Login password error");
//Message message = new Message();
//message.MessageText = "Login Error";
model = new ModelAndView("loginError");
model.addObject("message", message);
return model;
}
}
#RequestMapping(value = "/menuContact", method = RequestMethod.GET)
public ModelAndView menu(ModelAndView model){
model.setViewName("menu");
return model;
}
#RequestMapping(value = "/listContact", method = RequestMethod.GET)
public ModelAndView listContact(ModelAndView model) throws IOException{
List<Contact> listContact = contactDAO.list();
model.addObject("listContact", listContact);
model.setViewName("home");
return model;
}
#RequestMapping(value = "/newContact", method = RequestMethod.GET)
public ModelAndView newContact(ModelAndView model) {
Contact newContact = new Contact();
model.addObject("contact", newContact);
model.setViewName("ContactForm");
return model;
}
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute Contact contact) {
contactDAO.saveOrUpdate(contact);
return new ModelAndView("redirect:/");
}
#RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
public ModelAndView deleteContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
contactDAO.delete(contactId);
return new ModelAndView("redirect:/");
}
#RequestMapping(value = "/editContact", method = RequestMethod.GET)
public ModelAndView editContact(HttpServletRequest request) {
int contactId = Integer.parseInt(request.getParameter("id"));
Contact contact = contactDAO.get(contactId);
ModelAndView model = new ModelAndView("ContactForm");
model.addObject("contact", contact);
return model;
}
#RequestMapping(value="/showContact")
public ModelAndView getContact(ModelAndView model) throws IOException{
Contact contact = contactDAODS.get((Integer)25);
model.addObject("contact", contact);
model.setViewName("ContactSP");
return model;
}
}
First of all, this mapping should only work for the application root. If you want any path under the application root then use
/*
Now, in your case spring dispatcher will only be called if you open your browser to point to web application root without specifying any path which as i might guess is not what you want. So, use /* to forward all requests to the spring dispatcher and the use any request mapping in your controllers
Related
When I open my browser (Chrome) on
http://localhost:8084/Staff_Member_office_hours_management/EmailSendingServlet, then I see "service" from doService() being logged on console and my thread works correctly, however I don't see "It Works" from doGet() being logged and I get the following error in the browser:
HTTP method GET is not supported by this URL
How is this caused and how can I solve it?
I have the following servlet:
import java.io.IOException;
import static java.lang.System.out;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.apache.coyote.http11.Constants.a;
/**
* A servlet that takes message details from user and send it as a new e-mail
* through an SMTP server.
*
* #author www.codejava.net
*
*/
#WebServlet("/EmailSendingServlet")
public class EmailSendingServlet extends HttpServlet {
private String host;
private String port;
private String user;
private String pass;
private static final Random RANDOM = new SecureRandom();
public static final int PASSWORD_LENGTH = 8;
public static String generateRandomPassword()
{
// Pick from some letters that won't be easily mistaken for each
// other. So, for example, omit o O and 0, 1 l and L.
String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789+#";
String pw = "";
for (int i=0; i<PASSWORD_LENGTH; i++)
{
int index = (int)(RANDOM.nextDouble()*letters.length());
pw += letters.substring(index, index+1);
}
return pw;
}
public void init() {
// reads SMTP server setting from web.xml file
ServletContext context = getServletContext();
host = context.getInitParameter("host");
port = context.getInitParameter("port");
user = context.getInitParameter("user");
pass = context.getInitParameter("pass");
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("registeration.jsp");
String recipient = request.getParameter("mail");
String id = request.getParameter("id");
String subject = "Temporary Password to your account";
String content = generateRandomPassword();
String resultMessage = "";
try {
Class.forName("com.mysql.jdbc.Driver");
String urldb = "jdbc:mysql://localhost:3306/staffmember";
String userdb = "root";
String passworddb = "";
String Line;
Connection Con = null;
Statement Stmt = null;
PreparedStatement preparedStatement = null;
Con = DriverManager.getConnection(urldb, userdb, passworddb);
Stmt = Con.createStatement();
//out.print("mmmmmm");
String query4 = "UPDATE student SET password = '" + content + "' WHERE id = '" + id + "';";
preparedStatement = Con.prepareStatement(query4);
int rows3 = preparedStatement.executeUpdate(query4);
} catch (SQLException cnfe) {
System.err.println("Exception: " + cnfe);
} catch (ClassNotFoundException ex) {
Logger.getLogger(EmailSendingServlet.class.getName()).log(Level.SEVERE, null, ex);
}
try {
EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
content);
resultMessage = "The e-mail was sent successfully";
} catch (Exception ex) {
ex.printStackTrace();
resultMessage = "There were an error: " + ex.getMessage();
} finally {
request.setAttribute("Message", resultMessage);
getServletContext().getRequestDispatcher("/Result.jsp").forward(
request, response);
}
}
}
I have another the following servlet:
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.http.HttpSession;
public class registeration extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
response.setContentType("text/html");
String id = request.getParameter("id");
String name = request.getParameter("name");
String mail = request.getParameter("mail");
String phone = request.getParameter("mobile");
String password ="";
response.setContentType("text/html;charset=UTF-8");
Connection con = null;
Statement stmt = null;
ResultSet RS = null;
PreparedStatement pst = null;
boolean status = true;
try (PrintWriter out = response.getWriter()) {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/staffmember";
String user = "root";
String passworddb = "";
con = DriverManager.getConnection(url, user, passworddb);
//out.println("Registered Successfully 1");
if (mail != null && mail.trim().length() > 0) {
stmt = con.createStatement();
String fetchEmail = "Select mail from student where mail=" + "'" + mail + "'";
ResultSet rs = stmt.executeQuery(fetchEmail);
//out.println("Registered Successfully 2");
if (!rs.next()) {
String sql = "insert into student values('" + name + "','" + mail + "','" + phone + "','" +id + "','" + password +"')";
status = stmt.execute(sql);
out.println("Registered Successfully");
response.sendRedirect("EmailSendingServlet");
out.println("Click " + "Here" + " to signin");
} else {
out.print("<span id=\"msg\" style=\"color:red;\">" + mail + "</span>" + " is already registered. Click "
+ " Here" + " to signin");
}
} else {
String sql = "insert into student values('" + name + "','" + mail + "','" + phone + "' ,'" + id + "','" + password +"')";
status = stmt.execute(sql);
out.println("Registered Successfully");
out.print("Click " + "Here" + " to signin");
}
} catch (Exception e) {
out.println(e);
} finally {
try {
con.close();
} catch (SQLException e) {
}
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" 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_3_1.xsd">
<servlet>
<servlet-name>FileUploadPdf</servlet-name>
<servlet-class>FileUploadPdf</servlet-class>
</servlet>
<servlet>
<servlet-name>Search</servlet-name>
<servlet-class>Search</servlet-class>
</servlet>
<servlet>
<servlet-name>showStaff</servlet-name>
<servlet-class>showStaff</servlet-class>
</servlet>
<servlet>
<servlet-name>makeReservation</servlet-name>
<servlet-class>makeReservation</servlet-class>
</servlet>
<servlet>
<servlet-name>canelTransaction</servlet-name>
<servlet-class>canelReservation</servlet-class>
</servlet>
<servlet>
<servlet-name>cancelReservation</servlet-name>
<servlet-class>cancelReservation</servlet-class>
</servlet>
<servlet>
<servlet-name>notification</servlet-name>
<servlet-class>notification</servlet-class>
</servlet>
<servlet>
<servlet-name>messagetostaff</servlet-name>
<servlet-class>messagetostaff</servlet-class>
</servlet>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>registeration</servlet-name>
<servlet-class>registeration</servlet-class>
</servlet>
<servlet>
<servlet-name>EmailSendingServlet</servlet-name>
<servlet-class>EmailSendingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadPdf</servlet-name>
<url-pattern>/FileUploadPdf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Search</servlet-name>
<url-pattern>/Search</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>showStaff</servlet-name>
<url-pattern>/showStaff</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>makeReservation</servlet-name>
<url-pattern>/makeReservation</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>canelTransaction</servlet-name>
<url-pattern>/canelTransaction</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>cancelReservation</servlet-name>
<url-pattern>/cancelReservation</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>notification</servlet-name>
<url-pattern>/notification</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>messagetostaff</servlet-name>
<url-pattern>/messagetostaff</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>registeration</servlet-name>
<url-pattern>/registeration</url-pattern>
</servlet-mapping>
<context-param>
<param-name>tls</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>host</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>user</param-name>
<param-value>mohamedmagdysoffar#gmail.com</param-value>
</context-param>
<context-param>
<param-name>pass</param-name>
<param-value>wcfhecitqrdkfkka</param-value>
</context-param>
<servlet-mapping>
<servlet-name>EmailSendingServlet</servlet-name>
<url-pattern>/EmailSendingServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
It is probably because you have not overriden doGet method in EmailSendingServlet. This class has overriden only doPost method. You have to move your code to doGet overridden method from doPost.
My project is some java web projects which using Spring+SpringMVC+Mybaits framework.Here is a requirement that encrypt some data like user's name,mobile,identify_number in database and post requirement.I have encrypt these colums in database.I add two filter in a project named mobile-project,which provide post service to other people.In the doFilter() method of filter,I replace the servletRequest with my encryptRequestWrapper,which extends HttpServletRequestWrapper.I Override its getParameter() method and encrypt some data in this method.It work well,data has been encrypted/decrypted well.
Now I copy this to other project,It did not work.Here is my filter code:
package com.xinrong.web.admin.security;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class RequestEncryptFilter implements Filter {
private Set<String> prefixUrls = new HashSet<String>();
#Override
public void init(FilterConfig filterConfig) throws ServletException {
String contextPath = filterConfig.getServletContext().getContextPath();
String ignoreStr = filterConfig.getInitParameter("ignoreReqPrefix");
String[] ignorePatterns = ignoreStr.split(",");
for (String prefix : ignorePatterns) {
prefixUrls.add(contextPath + prefix);
}
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (!isIgnoreUrl(req)) {
String requestType = (String) req.getHeader("X-Requested-With");
if (requestType != null && requestType.equals("XMLHttpRequest")) {
chain.doFilter(new RequestBodyEncryptWrapper(req), response);
} else {
chain.doFilter(new RequestEncryptWapper(req), response);
}
chain.doFilter(new RequestEncryptWapper(req), response);
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
prefixUrls = null;
}
private boolean isIgnoreUrl(HttpServletRequest request) {
String url = request.getRequestURI();
for (String prefix : prefixUrls) {
if (url.startsWith(prefix)) {
return true;
}
}
return false;
}
}
package com.xinrong.web.admin.security;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang3.ArrayUtils;
import com.xinrong.service.bank.rongbao.pay.AES;
import com.xinrong.utils.UrlUtil;
public class RequestBodyEncryptWrapper extends HttpServletRequestWrapper {
private final byte[] body;
public RequestBodyEncryptWrapper(HttpServletRequest request)
throws IOException {
super(request);
ServletInputStream stream = request.getInputStream();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while ((rc = stream.read(buff, 0, 100)) > 0) {
swapStream.write(buff, 0, rc);
}
this.body = swapStream.toByteArray();
String tmpStr=new String(body,"UTF-8");
System.out.println("request tmp str:"+tmpStr);
}
#Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
}
#Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() {
#Override
public int read() throws IOException {
return bais.read();
}
};
}
#Override
public String getParameter(String name) {
String queryUrl = getRequestPayload();
return UrlUtil.getEncryptPara(queryUrl, name);
}
#Override
public String[] getParameterValues(String name) {
String[] vals=super.getParameterValues(name);
if(ArrayUtils.contains(UrlUtil.encryptKeyArr, name)){
vals[0]=AES.encryptToBase64(vals[0]);
}
return vals;
}
private String getRequestPayload() {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = getReader();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
}
package com.xinrong.web.admin.security;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.log4j.Logger;
import com.xinrong.service.bank.rongbao.pay.AES;
import com.xinrong.utils.UrlUtil;
public class RequestEncryptWapper extends HttpServletRequestWrapper {
public RequestEncryptWapper(HttpServletRequest request) {
super(request);
}
private Logger logger = Logger.getLogger(RequestEncryptWapper.class);
#Override
public String[] getParameterValues(String name) {
String[] strs = super.getParameterValues(name);
if (strs == null || strs.length == 0) {
return strs;
}
if (ArrayUtils.contains(UrlUtil.encryptKeyArr, name)) {
logger.info("before encrypt:" + strs[0]);
strs[0] = AES.encryptToBase64(strs[0]);
logger.info("after encrypt:stri is:" + strs[0]);
}
return strs;
}
}
Here is web.xml configuration.
<filter>
<filter-name>encryptRequestFilter</filter-name>
<filter-class>com.xinrong.web.admin.security.RequestEncryptFilter</filter-class>
<init-param>
<param-name>ignoreReqPrefix</param-name>
<param-value>/statics,/main,/login,/investor/getUnAuthStatusPage</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encryptRequestFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
The problem is that when I type "12345678912" as mobile value condition in this page,value of investorVO's mobile attribute is null,
queryPage
code in controller method:
* #param
* #param
* #param session
* #return
* #throws
*/
#RequestMapping(value = "dataGrid")
#ResponseBody
public EasyuiDataGrid dataGrid(InvestorVO investorVO, HttpSession session) {
return investorService.query(investorVO);
}
But if I invalid the filter,value of investorVO's mobile attribute get "12345678912".I guess something in SpringMVC cause this,but I don't know the exact reason.
-- EDIT
Version of SpringMVC is 3.2.8,it not support #requestBodyAdvice #responseBodyAdvice.
Here is web.xml configuration:
<?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>backend</display-name>
<!-- 设置Spring容器加载配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j.properties</param-value>
</context-param>
<!-- 解决工程编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!-- added LiYongjie encrypt -->
<filter>
<filter-name>encryptRequestFilter</filter-name>
<filter-class>com.xinrong.web.admin.security.RequestEncryptFilter</filter-class>
<init-param>
<param-name>ignoreReqPrefix</param-name>
<param-value>/statics,/main,/login,/investor/getUnAuthStatusPage</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encryptRequestFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!-- Spring Security配置 -->
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- SpringSecurity 核心过滤器配置 -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- <filter> <filter-name>decryptResponseFilter</filter-name> <filter-class>com.xinrong.web.admin.security.ResponseDecryptFilter</filter-class>
<init-param> <param-name>ignoreResPrefix</param-name> <param-value>/statics,/main,/login,/investor/getUnAuthStatusPage</param-value>
</init-param> </filter> <filter-mapping> <filter-name>decryptResponseFilter</filter-name>
<url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher>
</filter-mapping> -->
<!-- 加载Spring容器配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载Log4j配置 -->
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<!-- 加载防止内存溢出监听器 -->
<listener>
<listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>
</listener>
<!-- 扩展Request作用域 scope="request" 分别是 singleton、prototype、request、session、global
session -->
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<!-- Spring MVC Servlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/config/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--超时 -->
<session-config>
<session-timeout>600</session-timeout>
</session-config>
</web-app>
Perhaps I know the reason now.SpringMVC wrapper params from request to pojo Objects.Methods getInputStream(),getReader(),getParameter() from request can be invoked only once.I invoke getInputStream() in my RequestBodyEncryptWrapper Class,so when SpringMVC try to getParameter from request,it get null. But I still don't know how to do it.
I have configured spring security in my Rest API.I have three controller methods. One uses GET and other two use POST.
Now, I have used basic authentication.
The problem is that the security is working fine for GET request but not for the POST requests.
I am always getting 403 Forbidden response for the requests when POST method is used.
Controller class:
package com.base.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.base.model.User;
import com.base.service.UserService;
#RestController
public class CountryController {
#Autowired
UserService userService; //Service which will do all data retrieval/manipulation work
//-------------------Retrieve All Users--------------------------------------------------------
#RequestMapping(value = "/user/", method = RequestMethod.POST)
public ResponseEntity<List<User>> listAllUsers() {
List<User> users = userService.findAllUsers();
if(users.isEmpty()){
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);//You many decide to return HttpStatus.NOT_FOUND
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
//-------------------Retrieve Single User--------------------------------------------------------
#RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
public ResponseEntity<User> getUser(#PathVariable("id") long id) {
System.out.println("Fetching User with id " + id);
User user = userService.findById(id);
if (user == null) {
System.out.println("User with id " + id + " not found");
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
#RequestMapping(value = "/user123", method = RequestMethod.POST)
#ResponseStatus(HttpStatus.ALREADY_REPORTED)
public User postUser(#RequestBody #Valid User user) {
System.out.println("Fetching User with id " + user.getId());
user.setName("Tou added");
return user;
}
}
Security Config:
#Configuration
#EnableWebSecurity
#ComponentScan("com.base.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
MyUSerService userService;
#Autowired
public void configureGlobalAuth(final AuthenticationManagerBuilder auth)throws Exception{
auth.userDetailsService(userService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.authorizeRequests().anyRequest().authenticated().and().httpBasic().and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
MyUserService (to provide the usename and password)
#Service
public class MyUSerService implements UserDetailsService{
#Override
public UserDetails loadUserByUsername(String arg0) throws UsernameNotFoundException {
// TODO Auto-generated method stub
List<SimpleGrantedAuthority> authoriities = new ArrayList<SimpleGrantedAuthority>();
authoriities.add(new SimpleGrantedAuthority("WRITE"));
return new User("ayush","ayush123",authoriities);
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>Archetype Created Web Application</display-name>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springrest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>com.base.config</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springrest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
I am using 'Google Advanced Rest Client'.
You need to disable CRSF. CRSF is enabled by default in spring security 4.
http.csrf().disable()
or send the request with CRSF token.
In Spring Security 4.0, CSRF protection is enabled by default with XML configuration. You have to disable CSRF protection, the corresponding XML.
<http>
<!-- ... -->
<csrf disabled="true"/>
</http>
Or you to disable in Java configration file in code base by following
http.csrf().disable();
I work with Spring MVC 3.2.6.RELEASE and weblogic 10.3.6 and Eclipse Juno
When I execute the application I want to go a controller and get a jsp.
This is my 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" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>eusurveyadmin</display-name>
<servlet>
<servlet-name>eusurveyadmin</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/eusurveyadmin-servlet.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>eusurveyadmin</servlet-name>
<url-pattern>/eusurveyadmin/*</url-pattern>
</servlet-mapping>
<jsp-config>
<taglib>
<taglib-uri>http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API</taglib-uri>
<taglib-location>/WEB-INF/Content/esapi.tld</taglib-location>
</taglib>
</jsp-config>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>file:ecalcpAdminlog4j.xml</param-value>
</context-param>
<listener>
<listener-class>
eusurvey.listener.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>propertiesConfigLocation</param-name>
<param-value>file://C://OEPEJUNO//user_projects//domains//test38//configuracion.properties</param-value>
</context-param>
<listener>
<listener-class>
eusurvey.listener.CustomContextLoaderListener
</listener-class>
</listener>
<error-page>
<error-code>500</error-code>
<location>/500</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/404</location>
</error-page>
</web-app>
Controller is WelcomeController.java
package eusurvey.controller;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
import java.util.Locale;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
import eusurvey.modelA.daos.Preferencia;
import eusurvey.services.PreferencesService;
#Controller
#RequestMapping("/welcome")
public class WelcomeController extends ExceptionsController {
private static final Logger logger = Logger
.getLogger(WelcomeController.class);
#Resource(name = "preferencesService")
private PreferencesService preferencesService;
private int a = 0;
private Preferencia results = null;
#ModelAttribute("Preferencia")
public Preferencia fechaUltimaEncuesta() {
results = preferencesService.consultaPreferencia();
return results;
}
#RequestMapping(value = "/*")
public String welcome(HttpServletRequest request, ModelMap model) {
logger.info("WelcomeController welcome");
results = fechaUltimaEncuesta();
model.addAttribute("fechaUltimaEncuesta", results.getValor());
request.getSession().setAttribute("fechaUltimaEncuesta",
results.getValor());
String fechaUltimaEncuesta = (String) request.getSession()
.getAttribute("fechaUltimaEncuesta");
//return "welcome1";
return "/menu/pantallaInicio";
}
#ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception e, Locale locale, HttpServletRequest request) {
logger.error("WelcomeController handleException "+e.getLocalizedMessage()+" exception "+ e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String mensajeException = sw.toString();
logger.error("WelcomeController handleException exception "+e.getClass().getSimpleName()+" mensaje "+mensajeException );
ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName("errores/errorGeneral");
return mav;
}
}
When I run the applicacion I get the error
This is my weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app
xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app"
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 http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.3/weblogic-web-app.xsd">
<wls:weblogic-version>10.3.6</wls:weblogic-version>
<wls:context-root>EcalpAdmin</wls:context-root>
<wls:container-descriptor>
<wls:prefer-web-inf-classes>true</wls:prefer-web-inf-classes>
</wls:container-descriptor>
</wls:weblogic-web-app>
How do I have to write my web.xml to go the controller?
It appears that your RequestMapping at the class level is /welcome. Any method level RequestMapping will be relative to that. So your URL should be http://localhost/EcalpAdmin/welcome.
I was trying to run a servlet using ServletContextListener ,I've put the codes from the book
"Head-First" writter "Kathy sierra", but this is not working.Its shows 404 error.I have put the class files in the directory C:\Tomcat 5.5\webapps\Listener_exe\web-inf\classes\com\example. and web.xml file in web-inf directory. So please show where I have
done wrong. Here are the servlet, java files, and xml file.`
package com.example;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ListenerTester extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>test context attributes set by listener<br>");
Dog dog = (Dog) getServletContext().getAttribute("dog");
out.println("Dog's breed is: "+dog.getBreed()+</body></html>);
}
}
package com.example;
public class Dog
{
private String breed;
public Dog(String breed)
{
this.breed=breed;
}
public String getBreed()
{
return breed;
}
}
package com.example;
import javax.servlet.*;
public class MyServletContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
ServletContext sc = event.getServletContext();
String dogBreed = sc.getInitParameter("breed");
Dog d = new Dog(dogBreed);
sc.setAttribute("dog",d);
}
public void contextDestroyed(ServletContextEvent event)
{}
}
<web-app>
<servlet>
<servlet-name>ListenerTester</servlet-name>
<servlet-class>com.example.ListenerTester</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListenerTester</servlet-name>
<url-pattern>/ListenerTester</url-pattern>
</servlet-mapping>
<Context-param>
<param-name>breed</param-name>
<param-value>Great Dane</param-value>
</Context-param>
<listener>
<listener-class>
com.example.MyServletContextListener
</listener-class>
</listener>
</web-app>
Did you use the correct URL to reach the page? Your URL should be something like,
http://localhost:8080/Listener_exe/ListenerTester
Use whatever hostname or port number you set for your connector.